SNMP: Add MIB compiler (code generator)

This commit is contained in:
Dirk Ziegelmeier 2016-01-09 12:39:48 +01:00
parent 708beb4874
commit 84cd489d24
115 changed files with 11646 additions and 15 deletions

View File

@ -0,0 +1,67 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProductVersion>8.0.30703</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{7DA7C0AB-0982-4BF5-9324-F59A7A08D65B}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>CCodeGeneration</RootNamespace>
<AssemblyName>CCodeGeneration</AssemblyName>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<TargetFrameworkProfile />
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
</ItemGroup>
<ItemGroup>
<Compile Include="CFile.cs" />
<Compile Include="Code.cs" />
<Compile Include="CodeContainerBase.cs" />
<Compile Include="CodeElement.cs" />
<Compile Include="Comment.cs" />
<Compile Include="EmptyLine.cs" />
<Compile Include="Function.cs" />
<Compile Include="CGenerator.cs" />
<Compile Include="IfThenElse.cs" />
<Compile Include="PlainText.cs" />
<Compile Include="Switch.cs" />
<Compile Include="PP_If.cs" />
<Compile Include="PP_Ifdef.cs" />
<Compile Include="PP_Include.cs" />
<Compile Include="FunctionDeclaration.cs" />
<Compile Include="PP_Macro.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="VariableDeclaration.cs" />
<Compile Include="VariablePrototype.cs" />
<Compile Include="VariableType.cs" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>

View File

@ -0,0 +1,54 @@
/*
* Copyright (c) 2001-2004 Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
*
* This file is part of the lwIP TCP/IP stack.
*
* Author: Martin Hentschel <info@cl-soft.de>
*
*/
using System;
namespace CCodeGeneration
{
public class CFile: CodeContainerBase
{
public CFile()
{
base.IncreaseLevel = false;
}
public void Save(CGenerator generator)
{
if (generator == null)
{
throw new ArgumentNullException("generator");
}
this.GenerateCode(0, generator);
}
}
}

View File

@ -0,0 +1,119 @@
/*
* Copyright (c) 2001-2004 Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
*
* This file is part of the lwIP TCP/IP stack.
*
* Author: Martin Hentschel <info@cl-soft.de>
*
*/
using System;
using System.IO;
namespace CCodeGeneration
{
public class CGenerator
{
public TextWriter OutputStream { get; private set; }
public string File { get; private set; }
public uint IndentCount { get; private set; }
public string IndentChar { get; private set; }
public string NewLine { get; private set; }
public CGenerator(System.IO.TextWriter outputStream, string file, uint indentCount, string indentChar, string newLine)
{
this.OutputStream = outputStream;
this.File = file;
this.IndentCount = indentCount;
this.IndentChar = indentChar;
this.NewLine = newLine;
}
public string FileName
{
get
{
if (!String.IsNullOrWhiteSpace(this.File))
{
return Path.GetFileName(this.File);
}
return null;
}
}
public void WriteSequence(string value, uint repetitions)
{
while (repetitions > 0)
{
this.OutputStream.Write(value);
repetitions--;
}
}
public void IndentLine(int level)
{
while (level > 0)
{
WriteSequence(this.IndentChar, this.IndentCount);
level--;
}
}
public void WriteNewLine()
{
this.OutputStream.Write(this.NewLine);
}
public void WriteMultilineString(string value, int level = 0)
{
if (String.IsNullOrEmpty(value))
{
return;
}
// only \n and \r\n are recognized as linebreaks
string[] lines = value.Split(new char[] { '\n' }, StringSplitOptions.None);
for (int l = 0; l < (lines.Length - 1); l++)
{
if (lines[l].EndsWith("\r"))
{
this.OutputStream.Write(lines[l].Substring(0, lines[l].Length-1));
}
else
{
this.OutputStream.Write(lines[l]);
}
this.WriteNewLine();
this.IndentLine(level);
}
this.OutputStream.Write(lines[lines.Length - 1]);
}
}
}

View File

@ -0,0 +1,56 @@
/*
* Copyright (c) 2001-2004 Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
*
* This file is part of the lwIP TCP/IP stack.
*
* Author: Martin Hentschel <info@cl-soft.de>
*
*/
namespace CCodeGeneration
{
public class Code: CodeElement
{
public string Code_ { get; set; }
public Code()
{
}
public Code(string code)
{
this.Code_ = code;
}
public override void GenerateCode(int level, CGenerator generator)
{
generator.IndentLine(level);
generator.WriteMultilineString(this.Code_, level);
generator.WriteNewLine();
}
}
}

View File

@ -0,0 +1,139 @@
/*
* Copyright (c) 2001-2004 Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
*
* This file is part of the lwIP TCP/IP stack.
*
* Author: Martin Hentschel <info@cl-soft.de>
*
*/
using System.Collections.Generic;
using System;
namespace CCodeGeneration
{
public class CodeContainerBase: CodeElement
{
private readonly List<CodeElement> declarations = new List<CodeElement>();
private readonly List<CodeElement> innerElements = new List<CodeElement>();
private bool increaseLevel = true;
public List<CodeElement> Declarations
{
get { return this.declarations; }
}
public List<CodeElement> InnerElements
{
get { return this.innerElements; }
}
protected bool IncreaseLevel
{
get { return this.increaseLevel; }
set { this.increaseLevel = value; }
}
public void AddElements(IList<CodeElement> elements, params CodeElement[] spacerElements)
{
if (elements != null)
{
if ((spacerElements == null) || (spacerElements.Length == 0))
{
this.innerElements.AddRange(elements);
}
else
{
bool spacerAdded = false;
foreach (CodeElement element in elements)
{
this.innerElements.Add(element);
this.innerElements.AddRange(spacerElements);
spacerAdded = true;
}
if (spacerAdded)
{
// remove last spacer again
this.innerElements.RemoveRange(this.innerElements.Count - spacerElements.Length, spacerElements.Length);
}
}
}
}
public CodeElement AddElement(CodeElement element)
{
if (element != null)
{
this.innerElements.Add(element);
}
return element;
}
public Code AddCode(string code)
{
return this.AddElement(new Code(code)) as Code;
}
public Code AddCodeFormat(string codeFormat, params object[] args)
{
return this.AddElement(new Code(String.Format(codeFormat, args))) as Code;
}
public CodeElement AddDeclaration(CodeElement declaration)
{
if (declaration != null)
{
this.declarations.Add(declaration);
}
return declaration;
}
public override void GenerateCode(int level, CGenerator generator)
{
if (this.increaseLevel)
level++;
if (this.declarations.Count > 0)
{
foreach (CodeElement element in this.declarations)
{
element.GenerateCode(level, generator);
}
EmptyLine.SingleLine.GenerateCode(level, generator);
}
foreach (CodeElement element in this.innerElements)
{
element.GenerateCode(level, generator);
}
}
}
}

View File

@ -0,0 +1,41 @@
/*
* Copyright (c) 2001-2004 Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
*
* This file is part of the lwIP TCP/IP stack.
*
* Author: Martin Hentschel <info@cl-soft.de>
*
*/
namespace CCodeGeneration
{
public class CodeElement
{
public virtual void GenerateCode(int level, CGenerator generator)
{
}
}
}

View File

@ -0,0 +1,75 @@
/*
* Copyright (c) 2001-2004 Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
*
* This file is part of the lwIP TCP/IP stack.
*
* Author: Martin Hentschel <info@cl-soft.de>
*
*/
namespace CCodeGeneration
{
public class Comment: CodeElement
{
public const string CommentStart = "/*";
public const string CommentEnd = "*/";
public string Comment_ { get; set; }
public bool SingleLine { get; set; }
public Comment()
{
}
public Comment(string comment, bool singleLine = false)
{
this.Comment_ = comment;
this.SingleLine = singleLine;
}
public override void GenerateCode(int level, CGenerator generator)
{
generator.IndentLine(level);
generator.OutputStream.Write(CommentStart);
if (!this.SingleLine)
{
generator.WriteNewLine();
generator.IndentLine(level);
generator.WriteMultilineString(this.Comment_, level);
generator.WriteNewLine();
generator.IndentLine(level);
}
else
{
generator.OutputStream.Write(" " + Comment_ + " ");
}
generator.OutputStream.Write(CommentEnd);
generator.WriteNewLine();
}
}
}

View File

@ -0,0 +1,64 @@
/*
* Copyright (c) 2001-2004 Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
*
* This file is part of the lwIP TCP/IP stack.
*
* Author: Martin Hentschel <info@cl-soft.de>
*
*/
namespace CCodeGeneration
{
public class EmptyLine : CodeElement
{
public static readonly EmptyLine SingleLine = new EmptyLine();
public static readonly EmptyLine TwoLines = new EmptyLine(2);
public static readonly EmptyLine ThreeLines = new EmptyLine(3);
public uint Count { get; set; }
public EmptyLine()
{
this.Count = 1;
}
public EmptyLine(uint count)
{
this.Count = count;
}
public override void GenerateCode(int level, CGenerator generator)
{
uint c = this.Count;
while (c > 0)
{
generator.WriteNewLine();
c--;
}
}
}
}

View File

@ -0,0 +1,129 @@
/*
* Copyright (c) 2001-2004 Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
*
* This file is part of the lwIP TCP/IP stack.
*
* Author: Martin Hentschel <info@cl-soft.de>
*
*/
using System;
using System.Collections.Generic;
namespace CCodeGeneration
{
public class Function: CodeContainerBase
{
public string Name { get; set; }
public bool IsStatic { get; set; }
private readonly List<VariableType> parameter = new List<VariableType>();
private VariableType returnType = VariableType.Void;
public Function()
{
}
public Function(string name, bool isStatic = false)
{
this.Name = name;
this.IsStatic = isStatic;
}
public List<VariableType> Parameter
{
get { return this.parameter; }
}
public VariableType ReturnType
{
get { return this.returnType; }
set
{
if (value == null)
{
throw new ArgumentNullException("ReturnValue");
}
this.returnType = value;
}
}
public static Function FromDeclaration(FunctionDeclaration decl)
{
Function result = new Function(decl.Name, decl.IsStatic);
result.ReturnType = decl.ReturnType.Clone() as VariableType;
foreach (VariableType param in decl.Parameter)
{
result.parameter.Add(param.Clone() as VariableType);
}
return result;
}
public override void GenerateCode(int level, CGenerator generator)
{
generator.IndentLine(level);
if (this.IsStatic)
{
generator.OutputStream.Write("static ");
}
this.returnType.GenerateCode(generator);
generator.OutputStream.Write(" " + this.Name + "(");
if (this.Parameter.Count > 0)
{
for (int i = 0; i < this.parameter.Count; i++)
{
this.parameter[i].GenerateCode(generator);
if (i < (this.parameter.Count - 1))
{
generator.OutputStream.Write(", ");
}
}
}
else
{
generator.OutputStream.Write("void");
}
generator.OutputStream.Write(")");
generator.WriteNewLine();
generator.IndentLine(level);
generator.OutputStream.Write("{");
generator.WriteNewLine();
base.GenerateCode(level, generator);
generator.IndentLine(level);
generator.OutputStream.Write("}");
generator.WriteNewLine();
}
}
}

View File

@ -0,0 +1,114 @@
/*
* Copyright (c) 2001-2004 Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
*
* This file is part of the lwIP TCP/IP stack.
*
* Author: Martin Hentschel <info@cl-soft.de>
*
*/
using System;
using System.Collections.Generic;
namespace CCodeGeneration
{
public class FunctionDeclaration: CodeElement
{
public string Name { get; set; }
public bool IsStatic { get; set; }
public bool IsExtern { get; set; }
private readonly List<VariableType> parameter = new List<VariableType>();
private VariableType returnType = VariableType.Void;
public FunctionDeclaration()
{
}
public FunctionDeclaration(string name, bool isStatic = false, bool isExtern = false)
{
this.Name = name;
this.IsStatic = isStatic;
this.IsExtern = isExtern;
}
public List<VariableType> Parameter
{
get { return this.parameter; }
}
public VariableType ReturnType
{
get { return this.returnType; }
set
{
if (value == null)
{
throw new ArgumentNullException("ReturnValue");
}
this.returnType = value;
}
}
public override void GenerateCode(int level, CGenerator generator)
{
generator.IndentLine(level);
if (this.IsExtern)
{
generator.OutputStream.Write("extern ");
}
if (this.IsStatic)
{
generator.OutputStream.Write("static ");
}
this.returnType.GenerateCode(generator);
generator.OutputStream.Write(" " + this.Name + "(");
if (this.Parameter.Count > 0)
{
for (int i = 0; i < this.parameter.Count; i++)
{
this.parameter[i].GenerateCode(generator);
if (i < (this.parameter.Count - 1))
{
generator.OutputStream.Write(", ");
}
}
}
else
{
generator.OutputStream.Write("void");
}
generator.OutputStream.Write(");");
generator.WriteNewLine();
}
}
}

View File

@ -0,0 +1,137 @@
/*
* Copyright (c) 2001-2004 Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
*
* This file is part of the lwIP TCP/IP stack.
*
* Author: Martin Hentschel <info@cl-soft.de>
*
*/
using System;
using System.Collections.Generic;
namespace CCodeGeneration
{
public class ElseIf : CodeContainerBase
{
public string Condition { get; set; }
public ElseIf()
{
}
public ElseIf(string condition)
{
this.Condition = condition;
}
public override void GenerateCode(int level, CGenerator generator)
{
if (!String.IsNullOrWhiteSpace(this.Condition))
{
generator.IndentLine(level);
generator.OutputStream.Write(String.Format("else if ({0})", this.Condition));
generator.WriteNewLine();
generator.IndentLine(level);
generator.OutputStream.Write("{");
generator.WriteNewLine();
base.GenerateCode(level, generator);
generator.IndentLine(level);
generator.OutputStream.Write("}");
generator.WriteNewLine();
}
}
}
public class IfThenElse: CodeContainerBase
{
public string Condition { get; set; }
private List<ElseIf> elseIf = new List<ElseIf>();
private CodeContainerBase else_ = new CodeContainerBase();
public IfThenElse()
{
}
public IfThenElse(string condition)
{
this.Condition = condition;
}
public List<ElseIf> ElseIf
{
get { return this.elseIf; }
}
public CodeContainerBase Else
{
get { return this.else_; }
}
public override void GenerateCode(int level, CGenerator generator)
{
if (!String.IsNullOrWhiteSpace(this.Condition))
{
generator.IndentLine(level);
generator.OutputStream.Write(String.Format("if ({0})", this.Condition));
generator.WriteNewLine();
generator.IndentLine(level);
generator.OutputStream.Write("{");
generator.WriteNewLine();
base.GenerateCode(level, generator);
generator.IndentLine(level);
generator.OutputStream.Write("}");
generator.WriteNewLine();
foreach (ElseIf elif in this.elseIf)
{
elif.GenerateCode(level, generator);
}
if (this.else_.InnerElements.Count > 0)
{
generator.IndentLine(level);
generator.OutputStream.Write("else");
generator.WriteNewLine();
generator.IndentLine(level);
generator.OutputStream.Write("{");
generator.WriteNewLine();
this.else_.GenerateCode(level, generator);
generator.IndentLine(level);
generator.OutputStream.Write("}");
generator.WriteNewLine();
}
}
}
}
}

View File

@ -0,0 +1,67 @@
/*
* Copyright (c) 2001-2004 Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
*
* This file is part of the lwIP TCP/IP stack.
*
* Author: Martin Hentschel <info@cl-soft.de>
*
*/
using System;
namespace CCodeGeneration
{
public class PP_If: CodeContainerBase
{
public string Condition { get; set; }
public PP_If()
{
base.IncreaseLevel = false;
}
public PP_If(string condition)
: this()
{
this.Condition = condition;
}
public override void GenerateCode(int level, CGenerator generator)
{
if (!String.IsNullOrWhiteSpace(this.Condition))
{
generator.OutputStream.Write("#if " + this.Condition);
generator.WriteNewLine();
base.GenerateCode(level, generator);
generator.OutputStream.Write("#endif /* " + this.Condition + " */");
generator.WriteNewLine();
}
}
}
}

View File

@ -0,0 +1,76 @@
/*
* Copyright (c) 2001-2004 Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
*
* This file is part of the lwIP TCP/IP stack.
*
* Author: Martin Hentschel <info@cl-soft.de>
*
*/
using System;
namespace CCodeGeneration
{
public class PP_Ifdef: CodeContainerBase
{
public string Macro { get; set; }
public bool Inverted { get; set; }
public PP_Ifdef()
{
base.IncreaseLevel = false;
}
public PP_Ifdef(string macro, bool inverted = false)
: this()
{
this.Macro = macro;
this.Inverted = inverted;
}
public override void GenerateCode(int level, CGenerator generator)
{
if (!String.IsNullOrWhiteSpace(this.Macro))
{
if (this.Inverted)
{
generator.OutputStream.Write("#ifndef " + this.Macro);
}
else
{
generator.OutputStream.Write("#ifdef " + this.Macro);
}
generator.WriteNewLine();
base.GenerateCode(level, generator);
generator.OutputStream.Write("#endif /* " + this.Macro + " */");
generator.WriteNewLine();
}
}
}
}

View File

@ -0,0 +1,71 @@
/*
* Copyright (c) 2001-2004 Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
*
* This file is part of the lwIP TCP/IP stack.
*
* Author: Martin Hentschel <info@cl-soft.de>
*
*/
using System;
namespace CCodeGeneration
{
public class PP_Include : CodeElement
{
public string File { get; set; }
public bool IsLocal { get; set; }
public PP_Include()
{
this.IsLocal = true;
}
public PP_Include(string file, bool isLocal = true)
{
this.File = file;
this.IsLocal = isLocal;
}
public override void GenerateCode(int level, CGenerator generator)
{
if (!String.IsNullOrWhiteSpace(this.File))
{
// includes are never indented
if (this.IsLocal)
{
generator.OutputStream.Write("#include \"" + this.File + "\"");
}
else
{
generator.OutputStream.Write("#include <" + this.File + ">");
}
generator.WriteNewLine();
}
}
}
}

View File

@ -0,0 +1,59 @@
/*
* Copyright (c) 2001-2004 Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
*
* This file is part of the lwIP TCP/IP stack.
*
* Author: Martin Hentschel <info@cl-soft.de>
*
*/
namespace CCodeGeneration
{
public class PP_Macro: CodeElement
{
public string Name { get; set; }
public string Value { get; set; }
public PP_Macro()
{
}
public PP_Macro(string name, string value)
{
this.Name = name;
this.Value = value;
}
public override void GenerateCode(int level, CGenerator generator)
{
// macros are not indented at all
generator.OutputStream.Write("#define " + this.Name + " ");
generator.WriteMultilineString(this.Value);
generator.WriteNewLine();
}
}
}

View File

@ -0,0 +1,49 @@
/*
* Copyright (c) 2001-2004 Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
*
* This file is part of the lwIP TCP/IP stack.
*
* Author: Martin Hentschel <info@cl-soft.de>
*
*/
namespace CCodeGeneration
{
public class PlainText : CodeElement
{
public string Value { get; set; }
public PlainText(string value)
{
this.Value = value;
}
public override void GenerateCode(int level, CGenerator generator)
{
generator.WriteMultilineString(this.Value);
}
}
}

View File

@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// Allgemeine Informationen über eine Assembly werden über die folgenden
// Attribute gesteuert. Ändern Sie diese Attributwerte, um die Informationen zu ändern,
// die mit einer Assembly verknüpft sind.
[assembly: AssemblyTitle("CCodeGeneration")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("CCodeGeneration")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Durch Festlegen von ComVisible auf "false" werden die Typen in dieser Assembly unsichtbar
// für COM-Komponenten. Wenn Sie auf einen Typ in dieser Assembly von
// COM zugreifen müssen, legen Sie das ComVisible-Attribut für diesen Typ auf "true" fest.
[assembly: ComVisible(false)]
// Die folgende GUID bestimmt die ID der Typbibliothek, wenn dieses Projekt für COM verfügbar gemacht wird
[assembly: Guid("8f07a0fa-86f4-48a0-97c7-f94fc5c3f103")]
// Versionsinformationen für eine Assembly bestehen aus den folgenden vier Werten:
//
// Hauptversion
// Nebenversion
// Buildnummer
// Revision
//
// Sie können alle Werte angeben oder die standardmäßigen Build- und Revisionsnummern
// übernehmen, indem Sie "*" eingeben:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

View File

@ -0,0 +1,146 @@
/*
* Copyright (c) 2001-2004 Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
*
* This file is part of the lwIP TCP/IP stack.
*
* Author: Martin Hentschel <info@cl-soft.de>
*
*/
using System;
using System.Collections.Generic;
namespace CCodeGeneration
{
public class SwitchCase : CodeContainerBase
{
public string Value { get; set; }
public SwitchCase()
{
}
public SwitchCase(string value)
{
this.Value = value;
}
public bool IsDefault
{
get { return (this.Value.ToLowerInvariant() == "default"); }
}
public static SwitchCase GenerateDefault()
{
return new SwitchCase("default");
}
public override void GenerateCode(int level, CGenerator generator)
{
if (!String.IsNullOrWhiteSpace(this.Value))
{
generator.IndentLine(level);
if (this.IsDefault)
{
generator.OutputStream.Write("default:");
}
else
{
generator.OutputStream.Write(String.Format("case {0}:", this.Value));
}
generator.WriteNewLine();
generator.IndentLine(level + 1);
generator.OutputStream.Write("{");
generator.WriteNewLine();
base.GenerateCode(level + 1, generator);
generator.IndentLine(level + 1);
generator.OutputStream.Write("}");
generator.WriteNewLine();
generator.IndentLine(level + 1);
generator.OutputStream.Write("break;");
generator.WriteNewLine();
}
}
}
public class Switch: CodeElement
{
public string SwitchVar { get; set; }
private List<SwitchCase> switches = new List<SwitchCase>();
public Switch()
{
}
public Switch(string switchVar)
{
this.SwitchVar = switchVar;
}
public List<SwitchCase> Switches
{
get { return this.switches; }
}
public override void GenerateCode(int level, CGenerator generator)
{
if (!String.IsNullOrWhiteSpace(this.SwitchVar))
{
generator.IndentLine(level);
generator.OutputStream.Write(String.Format("switch ({0})", this.SwitchVar));
generator.WriteNewLine();
generator.IndentLine(level);
generator.OutputStream.Write("{");
generator.WriteNewLine();
SwitchCase defaultCase = null; // generate 'default' always as last case
foreach (SwitchCase switchCase in this.switches)
{
if (switchCase.IsDefault)
{
defaultCase = switchCase;
}
else
{
switchCase.GenerateCode(level + 1, generator);
}
}
if (defaultCase != null)
{
defaultCase.GenerateCode(level + 1, generator);
}
generator.IndentLine(level);
generator.OutputStream.Write("}");
generator.WriteNewLine();
}
}
}
}

View File

@ -0,0 +1,82 @@
/*
* Copyright (c) 2001-2004 Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
*
* This file is part of the lwIP TCP/IP stack.
*
* Author: Martin Hentschel <info@cl-soft.de>
*
*/
using System;
namespace CCodeGeneration
{
public class VariableDeclaration : CodeElement
{
public VariableType Type { get; set; }
public string InitialValue { get; set; }
public bool IsStatic { get; set; }
public VariableDeclaration()
: base()
{
}
public VariableDeclaration(VariableType type, string initialValue = null, bool isStatic = false) :
base()
{
this.Type = type;
this.InitialValue = initialValue;
this.IsStatic = isStatic;
}
public override void GenerateCode(int level, CGenerator generator)
{
if (this.Type != null)
{
generator.IndentLine(level);
if (this.IsStatic)
{
generator.OutputStream.Write("static ");
}
// declare the variable
this.Type.GenerateCode(generator);
if (!String.IsNullOrWhiteSpace(this.InitialValue))
{
// add initialization value
generator.OutputStream.Write(" = ");
generator.WriteMultilineString(this.InitialValue, level);
}
generator.OutputStream.Write(";");
generator.WriteNewLine();
}
}
}
}

View File

@ -0,0 +1,73 @@
/*
* Copyright (c) 2001-2004 Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
*
* This file is part of the lwIP TCP/IP stack.
*
* Author: Martin Hentschel <info@cl-soft.de>
*
*/
namespace CCodeGeneration
{
public class VariablePrototype : CodeElement
{
public VariableType Type { get; set; }
public VariablePrototype()
: base()
{
}
public VariablePrototype(VariableType type) :
base()
{
Type = type;
}
public static VariablePrototype FromVariableDeclaration(VariableDeclaration declaration)
{
return new VariablePrototype(declaration.Type);
}
public override void GenerateCode(int level, CGenerator generator)
{
if (this.Type != null)
{
generator.IndentLine(level);
generator.OutputStream.Write("extern ");
// declare the variable
this.Type.GenerateCode(generator);
generator.OutputStream.Write(";");
generator.WriteNewLine();
}
}
}
}

View File

@ -0,0 +1,130 @@
/*
* Copyright (c) 2001-2004 Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
*
* This file is part of the lwIP TCP/IP stack.
*
* Author: Martin Hentschel <info@cl-soft.de>
*
*/
using System;
using System.Text;
namespace CCodeGeneration
{
public enum ConstType
{
None,
Value,
Indirection,
Both
}
public class VariableType : ICloneable
{
public const string VoidString = "void";
public static readonly VariableType Void = new VariableType(null, "void");
public string Name { get; set; }
public string Type { get; set; }
public string Indirection { get; set; }
public ConstType Const { get; set; }
public string ArraySpecifier { get; set; }
public VariableType()
{
}
public VariableType(string name, string type, string indirection = null, ConstType const_ = ConstType.None, string arraySpecifier = null)
{
this.Name = name;
this.Type = type;
this.Indirection = indirection;
this.Const = const_;
this.ArraySpecifier = arraySpecifier;
}
public void GenerateCode(CGenerator generator)
{
if (!String.IsNullOrWhiteSpace(this.Type))
{
generator.OutputStream.Write(this.ToString().Trim());
}
}
public override string ToString()
{
if (!String.IsNullOrWhiteSpace(this.Type))
{
StringBuilder vt = new StringBuilder();
if ((this.Const == ConstType.Value) || (this.Const == ConstType.Both))
{
vt.Append("const ");
}
vt.Append(this.Type);
vt.Append(" ");
if (!String.IsNullOrWhiteSpace(this.Indirection))
{
vt.Append(this.Indirection);
}
if ((this.Const == ConstType.Indirection) || (this.Const == ConstType.Both))
{
vt.Append("const ");
}
if (!String.IsNullOrWhiteSpace(this.Name))
{
vt.Append(this.Name);
}
if (this.ArraySpecifier != null)
{
vt.Append("[");
vt.Append(this.ArraySpecifier);
vt.Append("]");
}
return vt.ToString().Trim();
}
return base.ToString();
}
#region ICloneable Member
public object Clone()
{
// we only have value types as members -> simply use .net base function
return this.MemberwiseClone();
}
#endregion
}
}

View File

@ -0,0 +1,47 @@

Microsoft Visual Studio Solution File, Format Version 11.00
# Visual Studio 2010
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LwipMibCompiler", "LwipMibCompiler\LwipMibCompiler.csproj", "{C25D5640-D999-49BD-82E0-A1975296A91E}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LwipSnmpCodeGeneration", "LwipSnmpCodeGeneration\LwipSnmpCodeGeneration.csproj", "{AABCAB90-1540-45D4-A159-14831A54E9A3}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CCodeGeneration", "CCodeGeneration\CCodeGeneration.csproj", "{7DA7C0AB-0982-4BF5-9324-F59A7A08D65B}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SharpSnmpLib.Mib", "SharpSnmpLib\SharpSnmpLib.Mib.csproj", "{CBE20411-5DB7-487D-825D-7694267BB6F5}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LwipMibViewer", "LwipMibViewer\LwipMibViewer.csproj", "{86CC0B65-7985-4017-A252-0A7A18DCAEF3}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{7DA7C0AB-0982-4BF5-9324-F59A7A08D65B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{7DA7C0AB-0982-4BF5-9324-F59A7A08D65B}.Debug|Any CPU.Build.0 = Debug|Any CPU
{7DA7C0AB-0982-4BF5-9324-F59A7A08D65B}.Release|Any CPU.ActiveCfg = Release|Any CPU
{7DA7C0AB-0982-4BF5-9324-F59A7A08D65B}.Release|Any CPU.Build.0 = Release|Any CPU
{86CC0B65-7985-4017-A252-0A7A18DCAEF3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{86CC0B65-7985-4017-A252-0A7A18DCAEF3}.Debug|Any CPU.Build.0 = Debug|Any CPU
{86CC0B65-7985-4017-A252-0A7A18DCAEF3}.Release|Any CPU.ActiveCfg = Release|Any CPU
{86CC0B65-7985-4017-A252-0A7A18DCAEF3}.Release|Any CPU.Build.0 = Release|Any CPU
{AABCAB90-1540-45D4-A159-14831A54E9A3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{AABCAB90-1540-45D4-A159-14831A54E9A3}.Debug|Any CPU.Build.0 = Debug|Any CPU
{AABCAB90-1540-45D4-A159-14831A54E9A3}.Release|Any CPU.ActiveCfg = Release|Any CPU
{AABCAB90-1540-45D4-A159-14831A54E9A3}.Release|Any CPU.Build.0 = Release|Any CPU
{C25D5640-D999-49BD-82E0-A1975296A91E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{C25D5640-D999-49BD-82E0-A1975296A91E}.Debug|Any CPU.Build.0 = Debug|Any CPU
{C25D5640-D999-49BD-82E0-A1975296A91E}.Release|Any CPU.ActiveCfg = Release|Any CPU
{C25D5640-D999-49BD-82E0-A1975296A91E}.Release|Any CPU.Build.0 = Release|Any CPU
{CBE20411-5DB7-487D-825D-7694267BB6F5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{CBE20411-5DB7-487D-825D-7694267BB6F5}.Debug|Any CPU.Build.0 = Debug|Any CPU
{CBE20411-5DB7-487D-825D-7694267BB6F5}.Release|Any CPU.ActiveCfg = Release|Any CPU
{CBE20411-5DB7-487D-825D-7694267BB6F5}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(MonoDevelopProperties) = preSolution
StartupItem = LwipMibViewer\LwipMibViewer.csproj
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal

View File

@ -0,0 +1,71 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProductVersion>8.0.30703</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{C25D5640-D999-49BD-82E0-A1975296A91E}</ProjectGuid>
<OutputType>Exe</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>LwipMibCompiler</RootNamespace>
<AssemblyName>LwipMibCompiler</AssemblyName>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<TargetFrameworkProfile />
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|AnyCPU'">
<DebugSymbols>true</DebugSymbols>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<DebugType>full</DebugType>
<PlatformTarget>AnyCPU</PlatformTarget>
<ErrorReport>prompt</ErrorReport>
<CodeAnalysisIgnoreBuiltInRuleSets>false</CodeAnalysisIgnoreBuiltInRuleSets>
<CodeAnalysisIgnoreBuiltInRules>false</CodeAnalysisIgnoreBuiltInRules>
<WarningLevel>4</WarningLevel>
<Optimize>false</Optimize>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|AnyCPU'">
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<Optimize>true</Optimize>
<DebugType>pdbonly</DebugType>
<PlatformTarget>AnyCPU</PlatformTarget>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
</ItemGroup>
<ItemGroup>
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<None Include="app.config" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\CCodeGeneration\CCodeGeneration.csproj">
<Project>{7DA7C0AB-0982-4BF5-9324-F59A7A08D65B}</Project>
<Name>CCodeGeneration</Name>
</ProjectReference>
<ProjectReference Include="..\LwipSnmpCodeGeneration\LwipSnmpCodeGeneration.csproj">
<Project>{AABCAB90-1540-45D4-A159-14831A54E9A3}</Project>
<Name>LwipSnmpCodeGeneration</Name>
</ProjectReference>
<ProjectReference Include="..\SharpSnmpLib\SharpSnmpLib.Mib.csproj">
<Project>{CBE20411-5DB7-487D-825D-7694267BB6F5}</Project>
<Name>SharpSnmpLib.Mib</Name>
</ProjectReference>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<PropertyGroup />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>

View File

@ -0,0 +1,470 @@
/*
* Copyright (c) 2001-2004 Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
*
* This file is part of the lwIP TCP/IP stack.
*
* Author: Martin Hentschel <info@cl-soft.de>
*
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Text.RegularExpressions;
using CCodeGeneration;
using Lextm.SharpSnmpLib.Mib;
using Lextm.SharpSnmpLib.Mib.Elements.Entities;
using Lextm.SharpSnmpLib.Mib.Elements.Types;
using LwipSnmpCodeGeneration;
namespace LwipMibCompiler
{
class Program
{
private static readonly Regex _alphaNumericRegex = new Regex("[^a-zA-Z0-9]");
static void Main(string[] args)
{
Console.WriteLine("lwIP MIB Compiler");
Console.WriteLine("");
// check args
if ((args.Length < 2) || String.IsNullOrWhiteSpace(args[0]) || String.IsNullOrWhiteSpace(args[1]))
{
PrintUsage();
return;
}
string mibFile = args[0];
if (!File.Exists(mibFile))
{
Console.WriteLine(String.Format("Unable to find file '{0}'!", mibFile));
}
string destFile = args[1];
string destHeaderFile;
if (Directory.Exists(destFile))
{
// only directory passed -> create dest filename from mib filename
string mibFileName = Path.GetFileNameWithoutExtension(mibFile).ToLowerInvariant();
destFile = Path.Combine(destFile, mibFileName + ".c");
}
string destFileExt = Path.GetExtension(destFile);
if (!String.IsNullOrEmpty(destFileExt))
{
destHeaderFile = destFile.Substring(0, destFile.Length - destFileExt.Length);
}
else
{
destHeaderFile = destFile;
}
destHeaderFile += ".h";
for (int i=2; i<args.Length; i++)
{
if (!String.IsNullOrWhiteSpace(args[i]) && Directory.Exists(args[i]))
{
MibTypesResolver.RegisterResolver(new FileSystemMibResolver(args[i], true));
}
}
// read and resolve MIB
Console.WriteLine(" Reading MIB file...");
MibDocument md = new MibDocument(mibFile);
MibTypesResolver.ResolveTypes(md.Modules[0]);
MibTree mt = new MibTree(md.Modules[0] as MibModule);
if (mt.Root == null)
{
Console.WriteLine("No root element found inside MIB!");
return;
}
// create LWIP object tree from MIB structure
Console.WriteLine(" Creating lwIP object tree...");
SnmpMib snmpMib = new SnmpMib();
snmpMib.Oid = mt.Root.Entity.Value;
snmpMib.BaseOid = (int[])(object)MibTypesResolver.ResolveOid(mt.Root.Entity).GetOidValues();
snmpMib.Name = _alphaNumericRegex.Replace(md.Modules[0].Name, "").ToLowerInvariant();
ProcessMibTreeNode(mt.Root, snmpMib);
// let the tree transform itself depending on node structure
snmpMib.Analyze();
// generate code from LWIP object tree
Console.WriteLine(" Generating code files...");
MibCFile generatedFile = new MibCFile();
MibHeaderFile generatedHeaderFile = new MibHeaderFile();
snmpMib.Generate(generatedFile, generatedHeaderFile);
string preservedCode = MibCFile.GetPreservedCode(destFile);
if (!string.IsNullOrEmpty(preservedCode))
{
generatedFile.PreservedCode.Add(new PlainText(preservedCode));
}
else
{
generatedFile.PreservedCode.AddRange(generatedFile.Implementation);
}
generatedFile.Implementation.Clear();
using (StreamWriter fileWriter = new StreamWriter(destHeaderFile))
{
CGenerator cGenerator = new CGenerator(fileWriter, destHeaderFile, 3, " ", Environment.NewLine);
generatedHeaderFile.Save(cGenerator);
}
using (StreamWriter fileWriter = new StreamWriter(destFile))
{
CGenerator cGenerator = new CGenerator(fileWriter, destFile, 3, " ", Environment.NewLine);
generatedFile.Save(cGenerator);
}
Console.WriteLine(" Done");
}
private static void PrintUsage()
{
string codeBase = Assembly.GetExecutingAssembly().CodeBase;
string appName = Path.GetFileName(codeBase);
Console.WriteLine("Usage:");
Console.WriteLine(String.Format(" {0} <source MIB file> <dest C file> [<search path 1 for referred MIB's> <search path 2 for referred MIB's> ...]", appName));
Console.WriteLine("");
Console.WriteLine(" <source MIB file>");
Console.WriteLine(" Path and filename of MIB file to convert.");
Console.WriteLine("");
Console.WriteLine(" <dest C file>");
Console.WriteLine(" Destination path and file. If a path is passed only, filename is auto");
Console.WriteLine(" generated from MIB file name.");
Console.WriteLine("");
Console.WriteLine(" <search path X for referred MIB's>");
Console.WriteLine(" It's important to provide all referred MIB's in order to correctly ");
Console.WriteLine(" resolve all used types.");
Console.WriteLine("");
}
#region Generation of LWIP Object Tree
private static void ProcessMibTreeNode(MibTreeNode mibTreeNode, SnmpTreeNode assignedSnmpNode)
{
foreach (MibTreeNode mtn in mibTreeNode.ChildNodes)
{
// in theory container nodes may also be scalars or tables at the same time (for now only process real containers)
if (mtn.NodeType == MibTreeNodeType.Container)
{
SnmpTreeNode snmpTreeNode = GenerateSnmpTreeNode(mtn, assignedSnmpNode);
assignedSnmpNode.ChildNodes.Add(snmpTreeNode);
ProcessMibTreeNode(mtn, snmpTreeNode);
}
else if ((mtn.NodeType & MibTreeNodeType.Scalar) != 0)
{
SnmpScalarNode snmpScalarNode = GenerateSnmpScalarNode(mtn, assignedSnmpNode);
if (snmpScalarNode != null)
{
assignedSnmpNode.ChildNodes.Add(snmpScalarNode);
}
}
else if ((mtn.NodeType & MibTreeNodeType.Table) != 0)
{
SnmpTableNode snmpTableNode = GenerateSnmpTableNode(mtn, assignedSnmpNode);
if (snmpTableNode != null)
{
assignedSnmpNode.ChildNodes.Add(snmpTableNode);
}
}
}
}
private static SnmpTreeNode GenerateSnmpTreeNode(MibTreeNode mibTreeNode, SnmpTreeNode parentNode)
{
SnmpTreeNode result = new SnmpTreeNode(parentNode);
result.Name = _alphaNumericRegex.Replace(mibTreeNode.Entity.Name, "").ToLowerInvariant();
result.Oid = mibTreeNode.Entity.Value;
result.FullOid = MibTypesResolver.ResolveOid(mibTreeNode.Entity).GetOidString();
return result;
}
private static SnmpScalarNode GenerateSnmpScalarNode(MibTreeNode mibTreeNode, SnmpTreeNode parentNode, bool ignoreAccessibleFlag = false)
{
ObjectType ote = mibTreeNode.Entity as ObjectType;
if (ote != null)
{
return GenerateSnmpScalarNode(ote, parentNode, ignoreAccessibleFlag);
}
return null;
}
private static SnmpScalarNode GenerateSnmpScalarNode(ObjectType ote, SnmpTreeNode parentNode, bool ignoreAccessibleFlag = false)
{
SnmpScalarNode result;
ITypeAssignment mibType = ote.BaseType;
IntegerType it = (mibType as IntegerType);
if (it != null)
{
if (ote.ReferredType.Name == Symbol.TruthValue.ToString())
{
result = new SnmpScalarNodeTruthValue(parentNode);
}
else if ((it.Type == IntegerType.Types.Integer) || (it.Type == IntegerType.Types.Integer32))
{
result = new SnmpScalarNodeInt(parentNode);
}
else
{
Console.WriteLine(String.Format("Unsupported IntegerType '{0}'!", it.Type));
return null;
}
if (it.IsEnumeration)
{
result.Restrictions.AddRange(CreateRestrictions(it.Enumeration));
}
else
{
result.Restrictions.AddRange(CreateRestrictions(it.Ranges));
}
}
else
{
UnsignedType ut = (mibType as UnsignedType);
if (ut != null)
{
if ((ut.Type == UnsignedType.Types.Unsigned32) ||
(ut.Type == UnsignedType.Types.Gauge32))
{
result = new SnmpScalarNodeUint(SnmpDataType.Gauge, parentNode);
}
else if (ut.Type == UnsignedType.Types.Counter32)
{
result = new SnmpScalarNodeUint(SnmpDataType.Counter, parentNode);
}
else if (ut.Type == UnsignedType.Types.TimeTicks)
{
result = new SnmpScalarNodeUint(SnmpDataType.TimeTicks, parentNode);
}
else if (ut.Type == UnsignedType.Types.Counter64)
{
result = new SnmpScalarNodeCounter64(parentNode);
if ((ut.Ranges != null) && (ut.Ranges.Count > 0))
{
Console.WriteLine(String.Format("Generation of ranges is not supported for Counter64 type!"));
return null;
}
}
else
{
Console.WriteLine(String.Format("Unsupported UnsignedType '{0}'!", ut.Type));
return null;
}
result.Restrictions.AddRange(CreateRestrictions(ut.Ranges));
}
else if (mibType is IpAddressType)
{
result = new SnmpScalarNodeOctetString(SnmpDataType.IpAddress, parentNode);
result.Restrictions.AddRange(CreateRestrictions((mibType as OctetStringType).Size));
}
else if (mibType is OpaqueType)
{
result = new SnmpScalarNodeOctetString(SnmpDataType.Opaque, parentNode);
result.Restrictions.AddRange(CreateRestrictions((mibType as OctetStringType).Size));
}
else if (mibType is OctetStringType)
{
result = new SnmpScalarNodeOctetString(SnmpDataType.OctetString, parentNode);
result.Restrictions.AddRange(CreateRestrictions((mibType as OctetStringType).Size));
}
else if (mibType is ObjectIdentifierType)
{
result = new SnmpScalarNodeObjectIdentifier(parentNode);
}
else if (mibType is BitsType)
{
result = new SnmpScalarNodeBits(parentNode, (uint)((mibType as BitsType).Map.GetHighestValue() + 1));
result.Restrictions.AddRange(CreateRestrictions(mibType as BitsType));
}
else
{
TypeAssignment ta = mibType as TypeAssignment;
if (ta != null)
{
Console.WriteLine(String.Format("Unsupported BaseType: Module='{0}', Name='{1}', Type='{2}'!", ta.Module.Name, ta.Name, ta.Type));
}
else
{
Console.WriteLine(String.Format("Unsupported BaseType: Module='{0}', Name='{1}'!", mibType.Module, mibType.Name));
}
return null;
}
}
result.Name = _alphaNumericRegex.Replace(ote.Name, "").ToLowerInvariant();
result.Oid = ote.Value;
if (ote.Access == MaxAccess.readWrite)
{
result.AccessMode = SnmpAccessMode.ReadWrite;
}
else if (ote.Access == MaxAccess.readOnly)
{
result.AccessMode = SnmpAccessMode.ReadOnly;
}
else if (ignoreAccessibleFlag && (ote.Access == MaxAccess.notAccessible))
{
result.AccessMode = SnmpAccessMode.NotAccessible;
}
else
{
// not accessible or unsupported accress type
return null;
}
return result;
}
private static IEnumerable<IRestriction> CreateRestrictions(ValueRanges ranges)
{
List<IRestriction> result = new List<IRestriction>();
if (ranges != null)
{
foreach (ValueRange range in ranges)
{
if (!range.End.HasValue)
{
result.Add(new IsEqualRestriction(range.Start));
}
else
{
result.Add(new IsInRangeRestriction(range.Start, range.End.Value));
}
}
}
return result;
}
private static IEnumerable<IRestriction> CreateRestrictions(ValueMap map)
{
if ((map != null) && (map.Count > 0))
{
return CreateRestrictions(map.GetContinousRanges());
}
return new List<IRestriction>();
}
private static IEnumerable<IRestriction> CreateRestrictions(BitsType bt)
{
List<IRestriction> result = new List<IRestriction>();
if ((bt != null) && (bt.Map != null))
{
result.Add(new BitMaskRestriction(bt.Map.GetBitMask()));
}
return result;
}
private static SnmpTableNode GenerateSnmpTableNode(MibTreeNode mibTreeNode, SnmpTreeNode parentNode)
{
SnmpTableNode result = new SnmpTableNode(parentNode);
result.Name = mibTreeNode.Entity.Name;
result.Oid = mibTreeNode.Entity.Value;
// expect exactly one row entry
if ((mibTreeNode.ChildNodes.Count != 1) || ((mibTreeNode.ChildNodes[0].NodeType & MibTreeNodeType.TableRow) == 0) || (mibTreeNode.ChildNodes[0].Entity.Value != 1))
{
Console.WriteLine("Found table with unsupported properties! Table needs exactly one (fixed) TableRow with OID=1 ! (" + mibTreeNode.Entity.Name + ")");
return null;
}
MibTreeNode rowNode = mibTreeNode.ChildNodes[0];
ObjectType rot = rowNode.Entity as ObjectType;
if (rot != null)
{
if (!String.IsNullOrWhiteSpace(rot.Augments))
{
result.AugmentedTableRow = rot.Augments;
// the indeces from another table shall be used because this table is only an extension of it
rot = MibTypesResolver.ResolveDeclaration(rot.Module, rot.Augments) as ObjectType;
}
if (rot.Indices != null)
{
foreach (string index in rot.Indices)
{
ObjectType indexEntity = MibTypesResolver.ResolveDeclaration(rot.Module, index) as ObjectType;
if (indexEntity == null)
{
Console.WriteLine(String.Format("Could not resolve index '{0}' for table '{1}'! Table omitted!", index, result.Name));
return null;
}
result.IndexNodes.Add(GenerateSnmpScalarNode(indexEntity, parentNode, ignoreAccessibleFlag: true));
}
}
}
if (result.IndexNodes.Count == 0)
{
// a table cannot be used without index
Console.WriteLine("Found table without any index column ! (" + mibTreeNode.Entity.Name + ")");
return null;
}
// add child nodes
foreach (MibTreeNode cellNode in rowNode.ChildNodes)
{
SnmpScalarNode ssn = GenerateSnmpScalarNode(cellNode, parentNode);
if (ssn != null)
{
result.CellNodes.Add(ssn);
}
}
return result;
}
#endregion
}
}

View File

@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// Allgemeine Informationen über eine Assembly werden über die folgenden
// Attribute gesteuert. Ändern Sie diese Attributwerte, um die Informationen zu ändern,
// die mit einer Assembly verknüpft sind.
[assembly: AssemblyTitle("ConsoleApplication28")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ConsoleApplication28")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Durch Festlegen von ComVisible auf "false" werden die Typen in dieser Assembly unsichtbar
// für COM-Komponenten. Wenn Sie auf einen Typ in dieser Assembly von
// COM zugreifen müssen, legen Sie das ComVisible-Attribut für diesen Typ auf "true" fest.
[assembly: ComVisible(false)]
// Die folgende GUID bestimmt die ID der Typbibliothek, wenn dieses Projekt für COM verfügbar gemacht wird
[assembly: Guid("0abf7541-6a96-43cd-9e24-462e074b2c96")]
// Versionsinformationen für eine Assembly bestehen aus den folgenden vier Werten:
//
// Hauptversion
// Nebenversion
// Buildnummer
// Revision
//
// Sie können alle Werte angeben oder die standardmäßigen Build- und Revisionsnummern
// übernehmen, indem Sie "*" eingeben:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

View File

@ -0,0 +1,3 @@
<?xml version="1.0"?>
<configuration>
<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/></startup></configuration>

View File

@ -0,0 +1,166 @@
namespace LwipMibViewer
{
partial class FormMain
{
/// <summary>
/// Erforderliche Designervariable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Verwendete Ressourcen bereinigen.
/// </summary>
/// <param name="disposing">True, wenn verwaltete Ressourcen gelöscht werden sollen; andernfalls False.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Vom Windows Form-Designer generierter Code
/// <summary>
/// Erforderliche Methode für die Designerunterstützung.
/// Der Inhalt der Methode darf nicht mit dem Code-Editor geändert werden.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FormMain));
this.treeMib = new System.Windows.Forms.TreeView();
this.imagelistTreeNodeImages = new System.Windows.Forms.ImageList(this.components);
this.splitContainerMain = new System.Windows.Forms.SplitContainer();
this.listviewNodeDetails = new System.Windows.Forms.ListView();
this.columnHeader1 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
this.columnHeader2 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
this.toolStripMain = new System.Windows.Forms.ToolStrip();
this.toolbuttonOpenMib = new System.Windows.Forms.ToolStripButton();
this.dialogOpenMib = new System.Windows.Forms.OpenFileDialog();
((System.ComponentModel.ISupportInitialize)(this.splitContainerMain)).BeginInit();
this.splitContainerMain.Panel1.SuspendLayout();
this.splitContainerMain.Panel2.SuspendLayout();
this.splitContainerMain.SuspendLayout();
this.toolStripMain.SuspendLayout();
this.SuspendLayout();
//
// treeMib
//
this.treeMib.Dock = System.Windows.Forms.DockStyle.Fill;
this.treeMib.ImageIndex = 0;
this.treeMib.ImageList = this.imagelistTreeNodeImages;
this.treeMib.Location = new System.Drawing.Point(0, 0);
this.treeMib.Name = "treeMib";
this.treeMib.SelectedImageIndex = 0;
this.treeMib.Size = new System.Drawing.Size(1028, 418);
this.treeMib.TabIndex = 0;
this.treeMib.AfterSelect += new System.Windows.Forms.TreeViewEventHandler(this.treeMib_AfterSelect);
//
// imagelistTreeNodeImages
//
this.imagelistTreeNodeImages.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imagelistTreeNodeImages.ImageStream")));
this.imagelistTreeNodeImages.TransparentColor = System.Drawing.Color.Transparent;
this.imagelistTreeNodeImages.Images.SetKeyName(0, "ntimgContainer");
this.imagelistTreeNodeImages.Images.SetKeyName(1, "ntimgTable");
this.imagelistTreeNodeImages.Images.SetKeyName(2, "ntimgRow");
this.imagelistTreeNodeImages.Images.SetKeyName(3, "ntimgColumn");
this.imagelistTreeNodeImages.Images.SetKeyName(4, "ntimgScalar");
this.imagelistTreeNodeImages.Images.SetKeyName(5, "ntimgUnknown");
//
// splitContainerMain
//
this.splitContainerMain.Dock = System.Windows.Forms.DockStyle.Fill;
this.splitContainerMain.Location = new System.Drawing.Point(0, 25);
this.splitContainerMain.Name = "splitContainerMain";
this.splitContainerMain.Orientation = System.Windows.Forms.Orientation.Horizontal;
//
// splitContainerMain.Panel1
//
this.splitContainerMain.Panel1.Controls.Add(this.treeMib);
//
// splitContainerMain.Panel2
//
this.splitContainerMain.Panel2.Controls.Add(this.listviewNodeDetails);
this.splitContainerMain.Size = new System.Drawing.Size(1028, 625);
this.splitContainerMain.SplitterDistance = 418;
this.splitContainerMain.TabIndex = 1;
//
// listviewNodeDetails
//
this.listviewNodeDetails.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
this.columnHeader1,
this.columnHeader2});
this.listviewNodeDetails.Dock = System.Windows.Forms.DockStyle.Fill;
this.listviewNodeDetails.FullRowSelect = true;
this.listviewNodeDetails.HeaderStyle = System.Windows.Forms.ColumnHeaderStyle.None;
this.listviewNodeDetails.Location = new System.Drawing.Point(0, 0);
this.listviewNodeDetails.Name = "listviewNodeDetails";
this.listviewNodeDetails.Size = new System.Drawing.Size(1028, 203);
this.listviewNodeDetails.TabIndex = 0;
this.listviewNodeDetails.UseCompatibleStateImageBehavior = false;
this.listviewNodeDetails.View = System.Windows.Forms.View.Details;
//
// columnHeader1
//
this.columnHeader1.Text = "";
this.columnHeader1.Width = 150;
//
// columnHeader2
//
this.columnHeader2.Text = "";
this.columnHeader2.Width = 777;
//
// toolStripMain
//
this.toolStripMain.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.toolbuttonOpenMib});
this.toolStripMain.Location = new System.Drawing.Point(0, 0);
this.toolStripMain.Name = "toolStripMain";
this.toolStripMain.Size = new System.Drawing.Size(1028, 25);
this.toolStripMain.TabIndex = 2;
//
// toolbuttonOpenMib
//
this.toolbuttonOpenMib.Image = ((System.Drawing.Image)(resources.GetObject("toolbuttonOpenMib.Image")));
this.toolbuttonOpenMib.Name = "toolbuttonOpenMib";
this.toolbuttonOpenMib.Size = new System.Drawing.Size(65, 22);
this.toolbuttonOpenMib.Text = "Open...";
this.toolbuttonOpenMib.Click += new System.EventHandler(this.toolbuttonOpenMib_Click);
//
// FormMain
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(1028, 650);
this.Controls.Add(this.splitContainerMain);
this.Controls.Add(this.toolStripMain);
this.Name = "FormMain";
this.Text = "MIB Viewer";
this.WindowState = System.Windows.Forms.FormWindowState.Maximized;
this.splitContainerMain.Panel1.ResumeLayout(false);
this.splitContainerMain.Panel2.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.splitContainerMain)).EndInit();
this.splitContainerMain.ResumeLayout(false);
this.toolStripMain.ResumeLayout(false);
this.toolStripMain.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.TreeView treeMib;
private System.Windows.Forms.SplitContainer splitContainerMain;
private System.Windows.Forms.ListView listviewNodeDetails;
private System.Windows.Forms.ColumnHeader columnHeader1;
private System.Windows.Forms.ColumnHeader columnHeader2;
private System.Windows.Forms.ImageList imagelistTreeNodeImages;
private System.Windows.Forms.ToolStrip toolStripMain;
private System.Windows.Forms.ToolStripButton toolbuttonOpenMib;
private System.Windows.Forms.OpenFileDialog dialogOpenMib;
}
}

View File

@ -0,0 +1,217 @@
/*
* Copyright (c) 2001-2004 Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
*
* This file is part of the lwIP TCP/IP stack.
*
* Author: Martin Hentschel <info@cl-soft.de>
*
*/
using System.Windows.Forms;
using Lextm.SharpSnmpLib.Mib;
using Lextm.SharpSnmpLib.Mib.Elements;
using Lextm.SharpSnmpLib.Mib.Elements.Types;
using Lextm.SharpSnmpLib.Mib.Elements.Entities;
using System.IO;
namespace LwipMibViewer
{
public partial class FormMain : Form
{
readonly ListViewGroup listviewgroupAbstract;
readonly ListViewGroup listviewgroupElement;
readonly ListViewGroup listviewgroupBaseType;
readonly ListViewGroup listviewgroupTypeChain;
public FormMain()
{
this.Font = SystemInformation.MenuFont;
InitializeComponent();
this.listviewgroupAbstract = new ListViewGroup("Abstract", System.Windows.Forms.HorizontalAlignment.Left);
this.listviewgroupElement = new ListViewGroup("Element Properties", System.Windows.Forms.HorizontalAlignment.Left);
this.listviewgroupBaseType = new ListViewGroup("Element Base Type", System.Windows.Forms.HorizontalAlignment.Left);
this.listviewgroupTypeChain = new ListViewGroup("Element Type Chain", System.Windows.Forms.HorizontalAlignment.Left);
this.listviewNodeDetails.Groups.AddRange(new System.Windows.Forms.ListViewGroup[] {
listviewgroupAbstract,
listviewgroupElement,
listviewgroupBaseType,
listviewgroupTypeChain});
try
{
DirectoryInfo dirInfo = new DirectoryInfo(Path.GetDirectoryName(Application.ExecutablePath));
if (dirInfo != null)
{
dirInfo = dirInfo.Parent;
if (dirInfo != null)
{
dirInfo = dirInfo.Parent;
if (dirInfo != null)
{
dirInfo = new DirectoryInfo(Path.Combine(dirInfo.FullName, "Mibs"));
if (dirInfo.Exists)
{
MibTypesResolver.RegisterResolver(new FileSystemMibResolver(dirInfo.FullName, true));
}
}
}
}
}
catch
{ }
}
#region GUI Event Handler
private void toolbuttonOpenMib_Click(object sender, System.EventArgs e)
{
if (this.dialogOpenMib.ShowDialog() == DialogResult.OK)
{
OpenMib(this.dialogOpenMib.FileName);
}
}
private void treeMib_AfterSelect(object sender, TreeViewEventArgs e)
{
listviewNodeDetails.Items.Clear();
if (e.Node != null)
{
MibTreeNode mtn = e.Node.Tag as MibTreeNode;
if (mtn != null)
{
listviewNodeDetails.Items.Add(new ListViewItem(new string[] { "Abstract", mtn.NodeType.ToString() }, this.listviewgroupAbstract));
listviewNodeDetails.Items.Add(new ListViewItem(new string[] { "Module", (mtn.Entity.Module != null) ? mtn.Entity.Module.Name : "" }, this.listviewgroupElement));
listviewNodeDetails.Items.Add(new ListViewItem(new string[] { "Type", mtn.Entity.GetType().Name }, this.listviewgroupElement));
listviewNodeDetails.Items.Add(new ListViewItem(new string[] { "Name", mtn.Entity.Name }, this.listviewgroupElement));
listviewNodeDetails.Items.Add(new ListViewItem(new string[] { "Description", mtn.Entity.Description }, this.listviewgroupElement));
listviewNodeDetails.Items.Add(new ListViewItem(new string[] { "OID", mtn.Entity.Value.ToString() }, this.listviewgroupElement));
listviewNodeDetails.Items.Add(new ListViewItem(new string[] { "Full OID", MibTypesResolver.ResolveOid(mtn.Entity).GetOidString() }, this.listviewgroupElement));
if (mtn.Entity is ObjectType)
{
listviewNodeDetails.Items.Add(new ListViewItem(new string[] { "Access", (mtn.Entity as ObjectType).Access.ToString() }, this.listviewgroupElement));
}
ITypeReferrer tr = mtn.Entity as ITypeReferrer;
if (tr != null)
{
ShowTypeDetails(listviewNodeDetails, this.listviewgroupBaseType, tr.BaseType);
ShowTypeChain(listviewNodeDetails, tr.ReferredType);
}
}
}
}
#endregion
#region Methods
private void OpenMib(string file)
{
try
{
MibDocument md = new MibDocument(file);
MibTypesResolver.ResolveTypes(md.Modules[0]);
this.treeMib.Nodes.Clear();
this.listviewNodeDetails.Items.Clear();
MibTree mt = new MibTree(md.Modules[0] as MibModule);
if (mt.Root != null)
{
AddNode(mt.Root, this.treeMib.Nodes);
foreach (TreeNode node in this.treeMib.Nodes)
{
node.Expand();
}
}
}
catch
{
}
}
private void AddNode(MibTreeNode mibNode, TreeNodeCollection parentNodes)
{
int imgIndex = 5; //unknown
if ((mibNode.NodeType & MibTreeNodeType.Table) != 0)
{
imgIndex = 1;
}
else if ((mibNode.NodeType & MibTreeNodeType.TableRow) != 0)
{
imgIndex = 2;
}
else if ((mibNode.NodeType & MibTreeNodeType.TableCell) != 0)
{
imgIndex = 3;
}
else if ((mibNode.NodeType & MibTreeNodeType.Scalar) != 0)
{
imgIndex = 4;
}
else if ((mibNode.NodeType & MibTreeNodeType.Container) != 0)
{
imgIndex = 0;
}
TreeNode newNode = new TreeNode(mibNode.Entity.Name, imgIndex, imgIndex);
newNode.Tag = mibNode;
parentNodes.Add(newNode);
foreach (MibTreeNode child in mibNode.ChildNodes)
{
AddNode(child, newNode.Nodes);
}
}
private void ShowTypeChain(ListView lv, ITypeAssignment type)
{
ShowTypeDetails(lv, this.listviewgroupTypeChain, type);
ITypeReferrer tr = type as ITypeReferrer;
if ((tr != null) && (tr.ReferredType != null))
{
lv.Items.Add(new ListViewItem(new string[] { " >>>", "" }, this.listviewgroupTypeChain));
ShowTypeChain(listviewNodeDetails, tr.ReferredType);
}
}
private void ShowTypeDetails(ListView lv, ListViewGroup lvg, ITypeAssignment type)
{
lv.Items.Add(new ListViewItem(new string[] { "Module", (type.Module != null) ? type.Module.Name : "" }, lvg));
lv.Items.Add(new ListViewItem(new string[] { "Type", type.GetType().Name }, lvg));
lv.Items.Add(new ListViewItem(new string[] { "Name", type.Name }, lvg));
}
#endregion
}
}

View File

@ -0,0 +1,298 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<metadata name="imagelistTreeNodeImages.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>17, 17</value>
</metadata>
<data name="imagelistTreeNodeImages.ImageStream" mimetype="application/x-microsoft.net.object.binary.base64">
<value>
AAEAAAD/////AQAAAAAAAAAMAgAAAFdTeXN0ZW0uV2luZG93cy5Gb3JtcywgVmVyc2lvbj00LjAuMC4w
LCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPWI3N2E1YzU2MTkzNGUwODkFAQAAACZTeXN0
ZW0uV2luZG93cy5Gb3Jtcy5JbWFnZUxpc3RTdHJlYW1lcgEAAAAERGF0YQcCAgAAAAkDAAAADwMAAABo
IQAAAk1TRnQBSQFMAgEBBgEAARABAAEQAQABEAEAARABAAT/ASEBAAj/AUIBTQE2BwABNgMAASgDAAFA
AwABIAMAAQEBAAEgBgABIBIAAwQBBQMWAR4DIgEyAzEBTwJGAUQBhwMvAUsDHgErAxsBJgMYASIDFQEd
AxIBGAMNARIDCgENAwcBCQMEAQUDAQECAwQBBQMWAR4DIgEyAzEBTgJGAUQBhwMvAUsDHgErAxsBJgMb
ASYDIQExAyEBMAMdASoDGwEmAxgBIQMLAQ8DAQECgAADAgEDAwwBEAMrAUMCRgFEAYIC/wHwAf8CRgFE
AYIDKgFAAw8BFAMNAREDCwEPAwkBDAMHAQoDBQEHAwQBBQMCAQMDAAEBAwIBAwMLAQ8DKwFDAkYBRAGC
Av8B8AH/AkYBRAGCAyoBQAMOARMDEgEZAT0COwFpAVwBRQFCAawBZwE+AToBxAFaAUUBQwGqATwBOwE6
AWYDEAEWAwABAYQAAx4BKwJEAUIBewL/AfAB/wLpAdoD/wHxAf8CRAFCAXsDHgErJAADHgErAkQBQgF7
Av8B8AH/AukB2gP/AfEB/wJEAUIBewMeASsBLgItAUcBdwFHATwByQG7AVQBPQHxA+4B/wG7AVMBPAHx
AXcBRgE8AckBLgItAUeEAAMdASoCRAFCAXcC/wHwAf8B6wHdAbEB/wH3AcEBNwH/Ae0B3wGzA/8B8gH/
AkQBQgF3Ax0BKhwAAx0BKgJEAUIBdwL/AfAB/wLpAdoB/wLqAdwB/wLrAd4D/wHyAf8CRAFCAXcBZAFJ
AUIBrwG2AVkBQQHxAc0BVAEyAf8BvQF5AWIB/wHFAVABLgH/AbEBUQE1AfEBXAFIAUQBn4QAAkMBQQF2
Av8B8AH/AukB2gH/AecBqwEhAf8B5wGrASEB/wHnAasBIQH/AeoB2wGwA/8B9AH/AkMBQQF2Ax0BKhgA
AkMBQQF2Av8B8AH/AukB2gH/AuoB3AH/AusB3gH/AuwB3wH/Au0B4QP/AfQB/wGAAUQBMQHaAc4BcAFN
AfwBugFMASoB/wPSAf8BvgGLAXgB/wG7AVIBMgH8AW8BSQE/AbqEAAMdASkCQwFBAXQC/wHxAf8B5wHX
AasB/wHXAZYBDAH/AdcBlgEMAf8B1wGWAQwB/wHoAdgBrgP/AfUB/wJDAUEBdAMdASkUAAMdASkCQwFB
AXQC/wHxAf8C6wHeAf8C7AHfAf8C7QHhAf8C7gHjAf8C7wHlAf8BzQF5AV4B/wHOAXcBWAH3AbwBVAEy
Af8BtAFMASoB/wPmAf8BtwFlAUsB8AFdAUkBRAGdiAADHQEpAkIBQQFyAv8B8gH/AeUB1AGpAf8BzQGJ
AQAB/wHNAYkBAAH/Ac0BiQEAAf8B6AHXAa8D/wH3Af8CQgFBAXIDHAEoFAADHQEpAkIBQQFyAv8B8gH/
Au0B4QH/Au4B4wH/Au8B5QH/AvAB5wH/AeABuwGqAf8BzgFpAUgB/wHjAcsBwQH5BP8B3gHHAb0B9QF+
AU8BQgHEAi0BLAFFjAADHAEoAkEBQAFxAv8B9AH/AecB1gGsAf8B0QGOAQQB/wHRAY4BBAH/AdEBjgEE
Af8B7AHbAbMD/wH4Af8CQQFAAXEDHAEoFAADHAEoAkEBQAFxAv8B9AH/Au8B5QH/AvAB5wH/AvEB6QH/
AvMB6gH/AeQBvgGsAf8B1AGBAWIB/wGGAUoBNAHXAWYBTQFEAaoCLQEsAUWUAAMcAScCQQFAAW8C/wH1
Af8B7AHcAbMB/wHfAaEBFwH/Ad8BoQEXAf8B3wGhARcB/wHxAeIBuwP/AfoB/wJBAUABbwMcAScUAAMc
AScCQQFAAW8C/wH1Af8C8QHpAf8C8wHqAf8C9AHsAf8C9QHuAf8C9gHwA/8B+gH/AkEBQAFvAxwBJ5gA
AxwBJwJAAT8BbQL/AfcB/wHyAeMBuwH/AfABuAEuAf8B8AG4AS4B/wHwAbgBLgH/AvgB9AP/AfsB/wJA
AT8BbQMcAScUAAMcAScCQAE/AW0C/wH3Af8C9AHsAf8C9QHuAf8C9gHwAf8C9wHyAf8C+AH0A/8B+wH/
AkABPwFtAxwBJ5gAAxsBJgJAAT8BbAL/AfgB/wH3AeoBwwH/Af0ByQE/Af8B+QHsAccB/wL7AfcB/wL8
AfkD/wH8Af8CQAE/AWwDGwEmFAADGwEmAkABPwFsAv8B+AH/AvYB8AH/AvcB8gH/AvgB9AH/AvsB9wH/
AvwB+QP/AfwB/wJAAT8BbAMbASaYAAMbASYCPwE+AWsC/wH6Af8C+AH0Af8C+wH3Af8C3wHVAf8CyQG5
Af8C4AHWA/8B/gH/Aj8BPgFrGAADGwEmAj8BPgFrAv8B+gH/AvgB9AH/AvsB9wH/At8B1QH/AskBuQH/
AuAB1gP/Af4B/wI/AT4Ba5wAAxoBJQI/AT0BaQL/AfsB/wL8AfkB/wK8AawB/wQAArwBrAP/Af4B/wI/
AT0BaRwAAxoBJQI/AT0BaQL/AfsB/wL8AfkB/wK8AawB/wQAArwBrAP/Af4B/wI/AT0BaaAAAxoBJQI+
AT0BaAL/AfwB/wLLAcEB/wKgAZAB/wLLAcED/wH+Af8CPgE9AWggAAMaASUCPgE9AWgC/wH8Af8CywHB
Af8CoAGQAf8CywHBA/8B/gH/Aj4BPQFopAADGgElAj4BPQFnAv8B/gP/Af4D/wH+Bf8CPgE9AWckAAMa
ASUCPgE9AWcC/wH+A/8B/gP/Af4F/wI+AT0BZ6gAAxoBJAI+AT0BZgI+AT0BZgI+AT0BZgI+AT0BZgMx
AU0oAAMaASQCPgE9AWYCPgE9AWYCPgE9AWYCPgE9AWYDMQFNlAADIQEwAUABRgFIAXwBQwFOAVIBkgMF
AQccAAMHAQkDEAEWAxMBGgMTARoDEwEaAxMBGgMTARoDEwEaAxMBGgMTARoDEwEaAxMBGgMTARoDEwEa
AxABFgMHAQkDBwEJAxABFgMTARoDEwEaAxMBGgMTARoDEwEaAxMBGgMTARoDEwEaAxMBGgMTARoDEwEa
AxMBGgMQARYDBwEJAwcBCQMQARYDEwEaAxMBGgMTARoDEwEaAxMBGgMTARoDEwEaAxMBGgMTARoDEwEa
AxMBGgMTARoDEAEWAwcBCQwAAjIBMwFQAUMBUQFXAZkBRQFkAXQBwAFYAYsBogHgATwBWAFqAcEDEwEa
AwUBBxgAAjwBOwFpAkYBRAGHAkYBRAGHAkYBRAGHAkYBRAGHAkYBRAGHAkYBRAGHAkYBRAGHAkYBRAGH
AkYBRAGHAkYBRAGHAkYBRAGHAkYBRAGHAkYBRAGHAkYBRAGHAjwBOwFpAjkBNAFpAkABNwGHAkABNwGH
AkABNwGHAkABNwGHAkABNwGHAkABNwGHAkABNwGHAkABNwGHAkABNwGHAkABNwGHAkABNwGHAkABNwGH
AkABNwGHAkABNwGHAjkBNAFpAjwBOwFpAkYBRAGHAkYBRAGHAkYBRAGHAkYBRAGHAkYBRAGHAkYBRAGH
AkYBRAGHAkYBRAGHAkYBRAGHAkYBRAGHAkYBRAGHAkYBRAGHAkYBRAGHAkYBRAGHAjwBOwFpAw0BEQMa
ASQBRAFNAVEBmAE8AYkBrAHyAWcBrwHTAfoBggHLAewB/wGFAc4B7gH/ARUBWwGCAe8BOgFXAWYBxAE6
AVcBZgHEAT4BWgFqAb4BPgFaAWoBvgE+AVoBagG+AUQBTQFRAZgDGgEkAw0BEQJGAUMBgQL5AekB/wLz
AeIB/wLzAeIB/wLzAeIB/wLzAeIB/wLzAeIB/wLzAeIB/wLzAeIB/wLzAeIB/wLzAeIB/wLzAeIB/wLz
AeIB/wLzAeIB/wL5AekB/wJGAUMBgQJDAToBgQL5AekB/wLzAeIB/wLzAeIB/wLzAeIB/wLzAeIB/wLz
AeIB/wLzAeIB/wLzAeIB/wLzAeIB/wLzAeIB/wLzAeIB/wLzAeIB/wLzAeIB/wL5AekB/wJDAToBgQJG
AUMBgQL5AekB/wLzAeIB/wLzAeIB/wLzAeIB/wLzAeIB/wLzAeIB/wLzAeIB/wLzAeIB/wLzAeIB/wLz
AeIB/wLzAeIB/wLzAeIB/wLzAeIB/wL5AekB/wJGAUMBgQMHAQkDDQESAUIBWwFmAbIBiAHQAe8B/wF9
AcoB6QH/AX0BygHpAf8BhwHQAe8B/wEkAXsBqQH/AX0BvAHbAf8BfQG8AdsB/wGNAdEB8wH/AY0B0QHz
Af8BkAHUAfUB/wFCAVsBZgGyATACMQFNAwcBCQJEAUMBegL0AeQC/wHMAUIB/wH+AcsBQQH/AewB0gGG
Af8C2gHJAf8C2AHHAf8C1gHFAf8C1AHDAf8C0wHCAf8C0QHAAf8CzwG+Af8CzgG9Af8CzQG8Af8C9AHk
Af8CRAFDAXoCRgE+AXoC9AHkAv8BzAFDAf8B/gHLAUIB/wHsAdIBhgH/AtoByQH/AtgBxwH/AtYBxQH/
AtQBwwH/AtMBwgH/AtEBwAH/As8BvgH/As4BvQH/As0BvAH/AvQB5AH/AkYBPgF6AkQBQwF6AvQB5AL/
AcwBQgH/Af4BywFBAf8B7AHSAYYB/wLaAckB/wLYAccB/wHnAWEBPwH/AecBYQE/Af8B5wFhAT8B/wHn
AWEBPwH/As8BvgH/As4BvQH/As0BvAH/AvQB5AH/AkQBQwF6CAABQwFXAWABpAGKAdMB8AH/AYIBzQHr
Af8BggHNAesB/wGKAdMB8AH/ASQBfAGrAf8BegG5AdgB/wF6AbkB2AH/AYoBzgHwAf8BigHOAfAB/wGP
AdMB9AH/AfQBtgEsAf8BQwFXAWABpAQAAkQBQgF3AvUB5gL/AcwBQgL/Ae4BiAH/AewB0gGGAf8C9QHu
Af8C9QHuAf8C1gHFAf8C9QHuAf8C9QHuAf8C0QHAAf8C9QHuAf8C9QHuAf8CzQG8Af8C9QHmAf8CRAFC
AXcCRwE/AXcC9QHmAv8BzAFDAv8B7gGIAf8B7AHSAYYB/wL1Ae4B/wL1Ae4B/wLWAcUB/wL1Ae4B/wL1
Ae4B/wLRAcAB/wL1Ae4B/wL1Ae4B/wLNAbwB/wL1AeYB/wJHAT8BdwJEAUIBdwL1AeYC/wHMAUIC/wHu
AYgB/wHsAdIBhgH/AvUB7gH/AvUB7gH/AdkBWAE2Af8B8gHJAbgB/wHyAckBuAH/AdkBWAE2Af8C9QHu
Af8C9QHuAf8CzQG8Af8C9QHmAf8CRAFCAXcIAAFDAVUBXgGeAY4B1gHyAf8BhwHQAe0B/wGHAdAB7QH/
AY4B1gHyAf8BJgGCAa8B/wF7AboB2AH/AXsBugHYAf8BiwHPAfEB/wGLAc8B8QH/AZEB1QH1Af8B/gHJ
AT8B/wFDAVUBXgGeBAACQwFBAXUC9gHpAv8BzAFCAf8B/gHLAUEB/wHsAdIBhgH/AtoByQH/AtgBxwH/
AtwBzAH/AtQBwwH/AtMBwgH/AtgByAH/As8BvgH/As4BvQH/As0BvAH/AvYB6QH/AkMBQQF1AkcBPwF1
AvYB6QL/AcwBQwH/Af4BywFCAf8B7AHSAYYB/wLaAckB/wLYAccB/wLcAcwB/wLUAcMB/wLTAcIB/wLY
AcgB/wLPAb4B/wLOAb0B/wLNAbwB/wL2AekB/wJHAT8BdQJDAUEBdQL2AekC/wHMAUIB/wH+AcsBQQH/
AewB0gGGAf8C2gHJAf8C2AHHAf8ByAFPAS0B/wHeAbYBngH/Ad4BtQGdAf8ByAFPAS0B/wLPAb4B/wLO
Ab0B/wLNAbwB/wL2AekB/wJDAUEBdQgAAUQBVQFdAZsBkgHaAfQB/wGLAdQB8AH/AYsB1AHwAf8BkgHa
AfQB/wEpAYUBswH/AX0BvAHaAf8BfQG8AdoB/wGNAdEB8wH/AY0B0QHzAf8BkwHXAfYB/wLrAd0B/wFE
AVUBXQGbBAACQgFBAXMC9wHrAv8BzAFCAv8B7gGIAf8B7AHSAYYB/wL3AfEB/wL3AfEB/wLWAcUB/wL3
AfEB/wL3AfEB/wLRAcAB/wL3AfEB/wL3AfEB/wLNAbwB/wL3AesB/wJCAUEBcwJHAT8BcwL3AesC/wHM
AUMC/wHuAYgB/wHsAdIBhgH/AvcB8QH/AvcB8QH/AtYBxQH/AvcB8QH/AvcB8QH/AtEBwAH/AvcB8QH/
AvcB8QH/As0BvAH/AvcB6wH/AkcBPwFzAkIBQQFzAvcB6wL/AcwBQgL/Ae4BiAH/AewB0gGGAf8C9wHx
Af8C9wHxAf8BuAFHASUB/wHzAcsBuQH/AfMBywG5Af8BuAFHASUB/wL3AfEB/wL3AfEB/wLNAbwB/wL3
AesB/wJCAUEBcwgAAUQBUwFbApcB3gH2Af8BkAHYAfIB/wGQAdgB8gH/AZcB3gH2Af8BKwGJAbcB/wGA
Ab0B3AH/AYABvQHcAf8BjwHTAfUB/wGPAdMB9QH/AZUB2QH4Af8C9QHuAf8BRAFTAVsBlwQAAkIBQQFy
AvgB7gL/AcwBQgH/Af4BywFBAf8B7AHSAYYB/wLaAckB/wLYAccB/wLdAc4B/wLUAcMB/wLTAcIB/wLZ
AcoB/wLPAb4B/wLOAb0B/wLNAbwB/wL4Ae4B/wJCAUEBcgJIAUABcgL4Ae4B/wHsAYYBYwH/AeIBewFZ
Af8B1AFuAUwB/wHEAWABPgH/AbYBUgEwAf8BrQFHASUB/wGrAUMBIQH/AbEBRAEiAf8BvQFKASgB/wHM
AVIBMAH/AdsBWgE4Af8B6AFiAUAB/wL4Ae4B/wJIAUABcgJCAUEBcgL4Ae4C/wHMAUIB/wH+AcsBQQH/
AewB0gGGAf8C2gHJAf8C2AHHAf8BrQFCASAB/wHeAbYBngH/Ad4BtQGdAf8BrQFCASAB/wLPAb4B/wLO
Ab0B/wLNAbwB/wL4Ae4B/wJCAUEBcggAAUQBUwFaAZQBmwHhAfcB/wGUAdsB9AH/AZQB2wH0Af8BmwHh
AfcB/wEuAY0BvAH/AYEBvgHdAf8BgQG+Ad0B/wGQAdQB9gH/AZAB1AH2Af8BlwHbAfkB/wL+Af0B/wFE
AVMBWgGUBAACQQFAAXAC+QHxAv8BzAFCAv8B7gGIAf8B7AHSAYYB/wL5AfUB/wL5AfUB/wLWAcUB/wL5
AfUB/wL5AfUB/wLRAcAB/wL5AfUB/wL5AfUB/wLNAbwB/wL5AfEB/wJBAUABcAJHAUABcAL5AfEB/wHs
AYYBYwH/AfgBxQF5Af8B7QG1AXgB/wH1AcwBvAH/AfUBzAG8Af8B4AG3AZ8B/wH1AcwBvAH/AfUBzAG8
Af8B3QG0AZwB/wH1AcwBvAH/AfUBzAG8Af8B6AFiAUAB/wL5AfEB/wJHAUABcAJBAUABcAL5AfEC/wHM
AUIC/wHuAYgB/wHsAdIBhgH/AvkB9QH/AvkB9QH/AasBRAEiAf8B9QHMAbwB/wH1AcwBvAH/AasBRAEi
Af8C+QH1Af8C+QH1Af8CzQG8Af8C+QHxAf8CQQFAAXAIAAFEAVEBVwGQAZ4B5QH5Af8BmAHfAfYB/wGY
Ad8B9gH/AZ4B5QH5Af8BMAGQAcAB/wGDAcAB3wH/AYMBwAHfAf8BkgHWAfgB/wGSAdYB+AH/AZkB3QH6
Af8BRAFRAVcBkAMjATMEAAJBAUABbgL7AfQC/wHMAUIB/wH+AcsBQQH/AewB0gGGAf8C2gHJAf8C2AHH
Af8C3gHQAf8C1AHDAf8C0wHCAf8C2gHMAf8CzwG+Af8CzgG9Af8CzQG8Af8C+wH0Af8CQQFAAW4CRwFA
AW4C+wH0Af8B7AGGAWMB/wHiAXsBWQH/AdQBbgFMAf8BxAFgAT4B/wG2AVIBMAH/Aa0BRwElAf8BqwFD
ASEB/wGxAUQBIgH/Ab0BSgEoAf8BzAFSATAB/wHbAVoBOAH/AegBYgFAAf8C+wH0Af8CRwFAAW4CQQFA
AW4C+wH0Av8BzAFCAf8B/gHLAUEB/wHsAdIBhgH/AtoByQH/AtgBxwH/AbIBTAEqAf8B3gG2AZ4B/wHe
AbUBnQH/AbIBTAEqAf8CzwG+Af8CzgG9Af8CzQG8Af8C+wH0Af8CQQFAAW4IAAFDAU8BVQGNAaMB6AH7
Af8BnQHjAfkB/wGdAeMB+QH/AaMB6AH7Af8BMwGUAcUB/wGFAcIB4QH/AYUBwgHhAf8BlAHYAfoB/wGU
AdgB+gH/AZsB3wH8Af8BQwFPAVUBjQgAAkABPwFtAvwB9wL/AcwBQgL/Ae4BiAH/AewB0gGGAf8C/AH6
Af8C/AH6Af8C1gHFAf8C/AH6Af8C/AH6Af8C0QHAAf8C/AH6Af8C/AH6Af8CzQG8Af8C/AH3Af8CQAE/
AW0CRwFAAW0C/AH3Av8BzAFDAv8B7gGIAf8B7AHSAYYB/wL8AfoB/wL8AfoB/wLWAcUB/wL8AfoB/wL8
AfoB/wLRAcAB/wL8AfoB/wL8AfoB/wLNAbwB/wL8AfcB/wJHAUABbQJAAT8BbQL8AfcC/wHMAUIC/wHu
AYgB/wHsAdIBhgH/AvwB+gH/AvwB+gH/AcABWgE4Af8B9gHOAb8B/wH2Ac4BvwH/AcABWgE4Af8C/AH6
Af8C/AH6Af8CzQG8Af8C/AH3Af8CQAE/AW0IAAFDAU8BVAGKAaYB6wH8Af8BoQHmAfsB/wGhAeYB+wH/
AaYB6wH8Af8BOgGdAc8B/wGHAcQB4gH/AYcBxAHiAf8BlgHaAfwB/wGWAdoB/AH/AZ4B4gH9Af8BQwFP
AVQBiggAAj8BPgFrAv0B+QL/AcwBQgH/Af4BywFBAf8B9QHOAWIB/wHrAdIBhQH/AekB0AGDAf8B5wHO
AYEB/wHlAcwBgAH/AeQBywF8Af8B4gHJAXoB/wHgAccBeAH/Ad8BxgF3Af8B3gHFAXYB/wL9AfkB/wI/
AT4BawJHAUABawL9AfkC/wHMAUMB/wH+AcsBQgH/AfUBzgFjAf8B6wHSAYUB/wHpAdABgwH/AecBzgGB
Af8B5QHMAYAB/wHkAcsBfQH/AeIByQF7Af8B4AHHAXkB/wHfAcYBeAH/Ad4BxQF3Af8C/QH5Af8CRwFA
AWsCPwE+AWsC/QH5Av8BzAFCAf8B/gHLAUEB/wH1Ac4BYgH/AesB0gGFAf8B6QHQAYMB/wHRAWoBSAH/
AekBsQF0Af8B6AGwAXMB/wHRAWoBSAH/AeABxwF4Af8B3wHGAXcB/wHeAcUBdgH/Av0B+QH/Aj8BPgFr
CAABQgFNAVIBhwGpAe4B/QH/AaQB6QH8Af8BpAHpAfwB/wGqAe8B/QH/AUABoQHRAf8BkAHRAfEB/wGW
AdoB+wH/AZcB2wH9Af8BlwHbAf0B/wGfAeMB/gH/AUIBTQFSAYcIAAI/AT4BagL+AfwC/wHMAUIC/wHu
AYgB/wH9AcoBQAH/AfwB6wGFAf8B+wHqAYQB/wH4AcUBOwH/AfYB5QF9Af8B9AHjAXsB/wHzAcABNgH/
AfEB4AF4Af8B7wHeAXYB/wHvAbwBMgH/Av4B/AH/Aj8BPgFqAkcBQAFqAv4B/AL/AcwBQwL/Ae4BiAH/
Af0BygFBAf8B/AHrAYUB/wH7AeoBhAH/AfgBxQE8Af8B9gHlAX4B/wH0AeMBfAH/AfMBwAE3Af8B8QHg
AXkB/wHvAd4BdwH/Ae8BvAEzAf8C/gH8Af8CRwFAAWoCPwE+AWoC/gH8Av8BzAFCAv8B7gGIAf8B/QHK
AUAB/wH8AesBhQH/AfsB6gGEAf8B4QF5AVcB/wHzAcABcwH/AfIBvwFyAf8B4QF5AVcB/wHxAeABeAH/
Ae8B3gF2Af8B7wG8ATIB/wL+AfwB/wI/AT4BaggAAUMBTAFSAYUBrQHxAv8BqwHvAf4B/wGVAeIB+AH/
AWwByQHtAf8BRgGpAdkB/wGYAdwB/gH/AZgB3AH+Af8BmAHcAf4B/wGYAdwB/gH/AaEB5QL/AUMBTAFS
AYUIAAI+AT0BaAL/Af4C/wHMAUIB/wH+AcsBQQH/Af0BygFAAf8B/AHJAT8B/wH6AccBPQH/AfgBxQE7
Af8B9gHDAToB/wH1AcIBOAH/AfMBwAE2Af8B8QG+ATQB/wHwAb0BMwH/Ae8BvAEyA/8B/gH/Aj4BPQFo
AkcBQAFoAv8B/gL/AcwBQwH/Af4BywFCAf8B/QHKAUEB/wH8AckBQAH/AfoBxwE+Af8B+AHFATwB/wH2
AcMBOwH/AfUBwgE5Af8B8wHAATcB/wHxAb4BNQH/AfABvQE0Af8B7wG8ATMD/wH+Af8CRwFAAWgCPgE9
AWgC/wH+Av8BzAFCAf8B/gHLAUEB/wH9AcoBQAH/AfwByQE/Af8B+gHHAT0B/wHsAYYBYgH/AewBhgFi
Af8B7AGGAWIB/wHsAYYBYgH/AfEBvgE0Af8B8AG9ATMB/wHvAbwBMgP/Af4B/wI+AT0BaAgAAUMBTAFQ
AYMBiAHcAfQB/wFeAcAB6QH/AV0BvwHqAf8BgAHTAfQB/wGcAeMB/QH/AaIB5gL/AaIB5gL/AaIB5gL/
AaIB5gL/AaYB6gL/AUMBTAFQAYMIAAI+AT0BZzj/Aj4BPQFnAkcBQAFnOP8CRwFAAWcCPgE9AWc4/wI+
AT0BZwgAATkBOwE9AWEBQgFLAU8BgQFCAUsBTwGBAUIBSwFPAYEBQgFLAU8BgQFCAUsBTwGBAUIBSwFP
AYEBQgFLAU8BgQFCAUsBTwGBAUIBSwFPAYEBQgFLAU8BgQE5ATsBPQFhCAADMQFNAj4BPQFmAj4BPQFm
Aj4BPQFmAj4BPQFmAj4BPQFmAj4BPQFmAj4BPQFmAj4BPQFmAj4BPQFmAj4BPQFmAj4BPQFmAj4BPQFm
Aj4BPQFmAj4BPQFmAzEBTQI3ATQBTQJHAUABZgJHAUABZgJHAUABZgJHAUABZgJHAUABZgJHAUABZgJH
AUABZgJHAUABZgJHAUABZgJHAUABZgJHAUABZgJHAUABZgJHAUABZgJHAUABZgI3ATQBTQMxAU0CPgE9
AWYCPgE9AWYCPgE9AWYCPgE9AWYCPgE9AWYCPgE9AWYCPgE9AWYCPgE9AWYCPgE9AWYCPgE9AWYCPgE9
AWYCPgE9AWYCPgE9AWYCPgE9AWYDMQFNAUIBTQE+BwABPgMAASgDAAFAAwABIAMAAQEBAAEBBgABARYA
A/8RAAGAAf8BgAEBBQABfwEAAQEFAAE/AQABAQUAAR8BAAEBBAABgAEPAYABAQQAAcABBwHAAQMEAAHg
AQMB4AEDBAAB8AEBAfABAQQAAfgBAAH4BQAB/AEAAfwFAAH+AQgB/gEIBAAB/wEAAf8FAAH/AYAB/wGA
BAAB/wHAAf8BwAQAAfgBfwYAAeABPxYAAcABAQYAAcABAQYAAcABAQYAAcABAQYAAcABAQYAAcABAQYA
AcABAwYAAcABAwYAAcABAwYAAcABAwYAAcABAwYAAcABAwYACw==
</value>
</data>
<metadata name="toolStripMain.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>211, 17</value>
</metadata>
<assembly alias="System.Drawing" name="System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<data name="toolbuttonOpenMib.Image" type="System.Drawing.Bitmap, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>
iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8
YQUAAAAJcEhZcwAADsIAAA7CARUoSoAAAAK6SURBVDhPjZNbSNNRHMfPU9DtwR71oZf5IgkF0YMEEYb2
EGgG5YNgGQmGSUoYimbel5KKmlM0u3jJSpv3ad7WnGkzb2yO4bByF3WuuTnnnLv47Zw/9YclQQc+/L//
P+d8/r/f+Z8/Ib/HjJDcmhaS3P+Bzf2zjr8qiki+QyuE6dNNbIzFw6F8DJ++AVh97c9GK9jcA4LJAlKI
rQ7sW9/DpauGZSoFg6JwfJSU+TE0XIXOgqCaAwJ5ASn2bb6F19TM4bO+w4z4HgwWC9YcDugpK3Y7umQy
FOZEDMRkZQX7SWS5pMRrboVn9RUHy1/aEqDSajGn0WDZbIZ6bQ0t/f1gIzojI8lPMvaIPPWsN2FP/5yD
ZdmLWLwUi/FhZASSqSlOUtXczBMcGZnFVzGUTSr2jI1wfq/lYHms4Tqkc3MYnZ2F0mDAqs3GV8LaiUhN
TeYFA5mkenelHg5tNQfLw3UxaOrpQZdUiu7xca5/Mc0do6PQb28jPDk5hRf0PiQi5zcR7JoKDpYHaqIg
VyohW1jg+lcZjVwlCzod1p1OXEhMvM8LOtNJvWOpEjZVKQfL/ZVX0NrXh165HP2Tk5hQqzGuUmFQocCm
y4XzCQlpvKA9jTTa1WWwzBdzsNxdfhmfFxcxQRct0Q3UmEzY2t2FdWcHdrcb5+LiHvCC1hTSbFOWwDyT
x8GyuDQCbRIJ3tBPp6CfU0pbcdA3M4mDCs7ExqYzwWHKibo7pNs6T4+yIofDSqtof3IJBtqzTq+Hx+uF
y+OBky5kkh2aT0VFZTNBAEWQFEFqhyvO2pclSe6f03nYnC1EW9FFGOnGGSi+/X14KW6fD3tUtkdzYFiY
0O801iWSaNFtUteWGST92nL1R/q1Q7ojAkHV0ZCQkuOhocV/c0wguHvgn2APyuPJ6dI4kpV/gzyjtycp
gf8g4Begs1B6Kbj3cQAAAABJRU5ErkJggg==
</value>
</data>
<metadata name="dialogOpenMib.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>337, 17</value>
</metadata>
</root>

View File

@ -0,0 +1,92 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProductVersion>8.0.30703</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{86CC0B65-7985-4017-A252-0A7A18DCAEF3}</ProjectGuid>
<OutputType>WinExe</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>LwipMibViewer</RootNamespace>
<AssemblyName>LwipMibViewer</AssemblyName>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<TargetFrameworkProfile />
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|AnyCPU'">
<DebugSymbols>true</DebugSymbols>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<DebugType>full</DebugType>
<ErrorReport>prompt</ErrorReport>
<CodeAnalysisIgnoreBuiltInRuleSets>true</CodeAnalysisIgnoreBuiltInRuleSets>
<CodeAnalysisIgnoreBuiltInRules>true</CodeAnalysisIgnoreBuiltInRules>
<WarningLevel>4</WarningLevel>
<Optimize>false</Optimize>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|AnyCPU'">
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<Optimize>true</Optimize>
<DebugType>pdbonly</DebugType>
<PlatformTarget>AnyCPU</PlatformTarget>
<ErrorReport>prompt</ErrorReport>
<CodeAnalysisIgnoreBuiltInRuleSets>true</CodeAnalysisIgnoreBuiltInRuleSets>
<CodeAnalysisIgnoreBuiltInRules>true</CodeAnalysisIgnoreBuiltInRules>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Drawing" />
<Reference Include="System.Windows.Forms" />
</ItemGroup>
<ItemGroup>
<Compile Include="FormMain.cs">
<SubType>Form</SubType>
</Compile>
<Compile Include="FormMain.Designer.cs">
<DependentUpon>FormMain.cs</DependentUpon>
</Compile>
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<EmbeddedResource Include="FormMain.resx">
<DependentUpon>FormMain.cs</DependentUpon>
</EmbeddedResource>
<EmbeddedResource Include="Properties\Resources.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.cs</LastGenOutput>
<SubType>Designer</SubType>
</EmbeddedResource>
<Compile Include="Properties\Resources.Designer.cs">
<AutoGen>True</AutoGen>
<DependentUpon>Resources.resx</DependentUpon>
<DesignTime>True</DesignTime>
</Compile>
<None Include="app.config" />
<None Include="Properties\Settings.settings">
<Generator>SettingsSingleFileGenerator</Generator>
<LastGenOutput>Settings.Designer.cs</LastGenOutput>
</None>
<Compile Include="Properties\Settings.Designer.cs">
<AutoGen>True</AutoGen>
<DependentUpon>Settings.settings</DependentUpon>
<DesignTimeSharedInput>True</DesignTimeSharedInput>
</Compile>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\SharpSnmpLib\SharpSnmpLib.Mib.csproj">
<Project>{CBE20411-5DB7-487D-825D-7694267BB6F5}</Project>
<Name>SharpSnmpLib.Mib</Name>
</ProjectReference>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<PropertyGroup />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>

View File

@ -0,0 +1,51 @@
/*
* Copyright (c) 2001-2004 Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
*
* This file is part of the lwIP TCP/IP stack.
*
* Author: Martin Hentschel <info@cl-soft.de>
*
*/
using System;
using System.Windows.Forms;
namespace LwipMibViewer
{
static class Program
{
/// <summary>
/// Der Haupteinstiegspunkt für die Anwendung.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new FormMain());
}
}
}

View File

@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// Allgemeine Informationen über eine Assembly werden über die folgenden
// Attribute gesteuert. Ändern Sie diese Attributwerte, um die Informationen zu ändern,
// die mit einer Assembly verknüpft sind.
[assembly: AssemblyTitle("LwipMibViewer")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("LwipMibViewer")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Durch Festlegen von ComVisible auf "false" werden die Typen in dieser Assembly unsichtbar
// für COM-Komponenten. Wenn Sie auf einen Typ in dieser Assembly von
// COM zugreifen müssen, legen Sie das ComVisible-Attribut für diesen Typ auf "true" fest.
[assembly: ComVisible(false)]
// Die folgende GUID bestimmt die ID der Typbibliothek, wenn dieses Projekt für COM verfügbar gemacht wird
[assembly: Guid("7ffbd1c1-1c64-45bb-b243-2400446c649d")]
// Versionsinformationen für eine Assembly bestehen aus den folgenden vier Werten:
//
// Hauptversion
// Nebenversion
// Buildnummer
// Revision
//
// Sie können alle Werte angeben oder die standardmäßigen Build- und Revisionsnummern
// übernehmen, indem Sie "*" eingeben:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

View File

@ -0,0 +1,63 @@
//------------------------------------------------------------------------------
// <auto-generated>
// Dieser Code wurde von einem Tool generiert.
// Laufzeitversion:4.0.30319.225
//
// Änderungen an dieser Datei können falsches Verhalten verursachen und gehen verloren, wenn
// der Code erneut generiert wird.
// </auto-generated>
//------------------------------------------------------------------------------
namespace LwipMibViewer.Properties {
using System;
/// <summary>
/// Eine stark typisierte Ressourcenklasse zum Suchen von lokalisierten Zeichenfolgen usw.
/// </summary>
// Diese Klasse wurde von der StronglyTypedResourceBuilder automatisch generiert
// -Klasse über ein Tool wie ResGen oder Visual Studio automatisch generiert.
// Um einen Member hinzuzufügen oder zu entfernen, bearbeiten Sie die .ResX-Datei und führen dann ResGen
// mit der /str-Option erneut aus, oder Sie erstellen Ihr VS-Projekt neu.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources() {
}
/// <summary>
/// Gibt die zwischengespeicherte ResourceManager-Instanz zurück, die von dieser Klasse verwendet wird.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("LwipMibViewer.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Überschreibt die CurrentUICulture-Eigenschaft des aktuellen Threads für alle
/// Ressourcenzuordnungen, die diese stark typisierte Ressourcenklasse verwenden.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
}
}

View File

@ -0,0 +1,117 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

View File

@ -0,0 +1,26 @@
//------------------------------------------------------------------------------
// <auto-generated>
// Dieser Code wurde von einem Tool generiert.
// Laufzeitversion:4.0.30319.225
//
// Änderungen an dieser Datei können falsches Verhalten verursachen und gehen verloren, wenn
// der Code erneut generiert wird.
// </auto-generated>
//------------------------------------------------------------------------------
namespace LwipMibViewer.Properties {
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "10.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default {
get {
return defaultInstance;
}
}
}
}

View File

@ -0,0 +1,7 @@
<?xml version='1.0' encoding='utf-8'?>
<SettingsFile xmlns="http://schemas.microsoft.com/VisualStudio/2004/01/settings" CurrentProfile="(Default)">
<Profiles>
<Profile Name="(Default)" />
</Profiles>
<Settings />
</SettingsFile>

View File

@ -0,0 +1,3 @@
<?xml version="1.0"?>
<configuration>
<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/></startup></configuration>

View File

@ -0,0 +1,120 @@
/*
* Copyright (c) 2001-2004 Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
*
* This file is part of the lwIP TCP/IP stack.
*
* Author: Martin Hentschel <info@cl-soft.de>
*
*/
using System;
namespace LwipSnmpCodeGeneration
{
public interface IRestriction
{
string GetCheckCodeValid(string varNameToCheck);
string GetCheckCodeInvalid(string varNameToCheck);
}
public class BitMaskRestriction : IRestriction
{
UInt32 mask;
public BitMaskRestriction(UInt32 mask)
{
this.mask = mask;
}
public string GetCheckCodeValid(string varNameToCheck)
{
return String.Format("(({0} & {1}) == {0})", varNameToCheck, this.mask);
}
public string GetCheckCodeInvalid(string varNameToCheck)
{
return String.Format("(({0} & {1}) != {0})", varNameToCheck, this.mask);
}
}
public class IsEqualRestriction : IRestriction
{
private Int64 value;
public IsEqualRestriction(Int64 value)
{
this.value = value;
}
public long Value
{
get { return value; }
}
public string GetCheckCodeValid(string varNameToCheck)
{
return String.Format("({0} == {1})", varNameToCheck, this.value);
}
public string GetCheckCodeInvalid(string varNameToCheck)
{
return String.Format("({0} != {1})", varNameToCheck, this.value);
}
}
public class IsInRangeRestriction : IRestriction
{
private Int64 rangeStart;
private Int64 rangeEnd;
public IsInRangeRestriction(Int64 rangeStart, Int64 rangeEnd)
{
this.rangeStart = rangeStart;
this.rangeEnd = rangeEnd;
}
public long RangeStart
{
get { return this.rangeStart; }
}
public long RangeEnd
{
get { return this.rangeEnd; }
}
public string GetCheckCodeValid(string varNameToCheck)
{
return String.Format("(({0} >= {1}) && ({0} <= {2}))", varNameToCheck, this.rangeStart, this.rangeEnd);
}
public string GetCheckCodeInvalid(string varNameToCheck)
{
return String.Format("(({0} < {1}) || ({0} > {2}))", varNameToCheck, this.rangeStart, this.rangeEnd);
}
}
}

View File

@ -0,0 +1,199 @@
/*
* Copyright (c) 2001-2004 Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
*
* This file is part of the lwIP TCP/IP stack.
*
* Author: Martin Hentschel <info@cl-soft.de>
*
*/
using System;
namespace LwipSnmpCodeGeneration
{
public static class LwipOpts
{
public static bool GenerateEmptyFolders = false;
/// <summary>
/// If a tree node only has scalar nodes as child nodes, it is replaced by
/// a single scalar array node in order to save memory and have only one single get/test/set method for all scalars.
/// </summary>
public static bool GenerateScalarArrays = true;
/// <summary>
/// If a tree node has multiple scalars as subnodes as well as other treenodes it
/// defines a single get/test/set method for all scalar child node.
/// (without other treenodes as child it would have been converted to scalar array node).
/// </summary>
public static bool GenerateSingleAccessMethodsForTreeNodeScalars = GenerateScalarArrays;
}
public static class LwipDefs
{
public const string Null = "NULL";
public const string Vt_U8 = "u8_t";
public const string Vt_U16 = "u16_t";
public const string Vt_U32 = "u32_t";
public const string Vt_S8 = "s8_t";
public const string Vt_S16 = "s16_t";
public const string Vt_S32 = "s32_t";
public const string Vt_Snmp_err = "snmp_err_t";
public const string Incl_SnmpOpts = "lwip/apps/snmp_opts.h";
public const string Opt_SnmpEnabled = "LWIP_SNMP";
public const string Vt_StMib = "struct snmp_mib";
public const string Vt_StObjectId = "struct snmp_obj_id";
public const string Vt_StNode = "struct snmp_node";
public const string Vt_StNodeInstance = "struct snmp_node_instance";
public const string Vt_StTreeNode = "struct snmp_tree_node";
public const string Vt_StScalarNode = "struct snmp_scalar_node";
public const string Vt_StScalarArrayNode = "struct snmp_scalar_array_node";
public const string Vt_StScalarArrayNodeDef = "struct snmp_scalar_array_node_def";
public const string Vt_StTableNode = "struct snmp_table_node";
public const string Vt_StTableColumnDef = "struct snmp_table_col_def";
public const string Vt_StNextOidState = "struct snmp_next_oid_state";
public const string Def_NodeAccessReadOnly = "SNMP_NODE_INSTANCE_READ_ONLY";
public const string Def_NodeAccessReadWrite = "SNMP_NODE_INSTANCE_READ_WRITE";
public const string Def_NodeAccessWriteOnly = "SNMP_NODE_INSTANCE_WRITE_ONLY";
public const string Def_NodeAccessNotAccessible = "SNMP_NODE_INSTANCE_NOT_ACCESSIBLE";
public const string Def_ErrorCode_Ok = "SNMP_ERR_NOERROR";
public const string Def_ErrorCode_WrongValue = "SNMP_ERR_WRONGVALUE";
public const string Def_ErrorCode_NoSuchInstance = "SNMP_ERR_NOSUCHINSTANCE";
public const string FnctSuffix_GetValue = "_get_value";
public const string FnctSuffix_SetTest = "_set_test";
public const string FnctSuffix_SetValue = "_set_value";
public const string FnctSuffix_GetInstance = "_get_instance";
public const string FnctSuffix_GetNextInstance = "_get_next_instance";
public const string FnctName_SetTest_Ok = "snmp_set_test_ok";
public static string GetLwipDefForSnmpAccessMode(SnmpAccessMode am)
{
switch (am)
{
case SnmpAccessMode.ReadOnly: return Def_NodeAccessReadOnly;
case SnmpAccessMode.ReadWrite: return Def_NodeAccessReadWrite;
case SnmpAccessMode.NotAccessible: return Def_NodeAccessNotAccessible;
case SnmpAccessMode.WriteOnly: return Def_NodeAccessWriteOnly;
default: throw new NotSupportedException("Unknown SnmpAccessMode!");
}
}
public static string GetAsn1DefForSnmpDataType(SnmpDataType dt)
{
switch (dt)
{
// primitive
case SnmpDataType.Null:
return "SNMP_ASN1_TYPE_NULL";
case SnmpDataType.Bits:
case SnmpDataType.OctetString:
return "SNMP_ASN1_TYPE_OCTET_STRING";
case SnmpDataType.ObjectIdentifier:
return "SNMP_ASN1_TYPE_OBJECT_ID";
case SnmpDataType.Integer:
return "SNMP_ASN1_TYPE_INTEGER";
// application
case SnmpDataType.IpAddress:
return "SNMP_ASN1_TYPE_IPADDR";
case SnmpDataType.Counter:
return "SNMP_ASN1_TYPE_COUNTER";
case SnmpDataType.Gauge:
return "SNMP_ASN1_TYPE_GAUGE";
case SnmpDataType.TimeTicks:
return "SNMP_ASN1_TYPE_TIMETICKS";
case SnmpDataType.Opaque:
return "SNMP_ASN1_TYPE_OPAQUE";
case SnmpDataType.Counter64:
return "SNMP_ASN1_TYPE_COUNTER64";
default:
throw new NotSupportedException("Unknown SnmpDataType!");
}
}
public static string GetLengthForSnmpDataType(SnmpDataType dt)
{
switch (dt)
{
case SnmpDataType.Null:
return "0";
case SnmpDataType.Integer:
case SnmpDataType.Counter:
case SnmpDataType.IpAddress:
case SnmpDataType.Gauge:
case SnmpDataType.TimeTicks:
return "4";
case SnmpDataType.Counter64:
return "8";
case SnmpDataType.OctetString:
case SnmpDataType.ObjectIdentifier:
case SnmpDataType.Bits:
case SnmpDataType.Opaque:
return null;
default:
throw new NotSupportedException("Unknown SnmpDataType!");
}
}
}
public enum SnmpDataType
{
Null,
Integer, // INTEGER, Integer32
Counter, // Counter, Counter32
Gauge, // Gauge, Gauge32, Unsigned32
TimeTicks,
Counter64,
OctetString,
Opaque,
Bits,
ObjectIdentifier,
IpAddress,
}
public enum SnmpAccessMode
{
ReadOnly,
ReadWrite,
WriteOnly,
NotAccessible
}
}

View File

@ -0,0 +1,72 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProductVersion>8.0.30703</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{AABCAB90-1540-45D4-A159-14831A54E9A3}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>LwipSnmpCodeGeneration</RootNamespace>
<AssemblyName>LwipSnmpCodeGeneration</AssemblyName>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<TargetFrameworkProfile />
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
</ItemGroup>
<ItemGroup>
<Compile Include="IRestriction.cs" />
<Compile Include="SnmpScalarNodeCounter64.cs" />
<Compile Include="SnmpScalarNodeTruthValue.cs" />
<Compile Include="SnmpScalarAggregationNode.cs" />
<Compile Include="SnmpTableNode.cs" />
<Compile Include="SnmpScalarArrayNode.cs" />
<Compile Include="MibHeaderFile.cs" />
<Compile Include="SnmpScalarNodeBits.cs" />
<Compile Include="SnmpMib.cs" />
<Compile Include="SnmpScalarNodeInt.cs" />
<Compile Include="SnmpScalarNodeObjectIdentifier.cs" />
<Compile Include="SnmpScalarNodeOctetString.cs" />
<Compile Include="SnmpScalarNodeUint.cs" />
<Compile Include="SnmpTreeNode.cs" />
<Compile Include="LwipSnmp.cs" />
<Compile Include="MibCFile.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="SnmpNode.cs" />
<Compile Include="SnmpScalarNode.cs" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\CCodeGeneration\CCodeGeneration.csproj">
<Project>{7DA7C0AB-0982-4BF5-9324-F59A7A08D65B}</Project>
<Name>CCodeGeneration</Name>
</ProjectReference>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>

View File

@ -0,0 +1,196 @@
/*
* Copyright (c) 2001-2004 Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
*
* This file is part of the lwIP TCP/IP stack.
*
* Author: Martin Hentschel <info@cl-soft.de>
*
*/
using System.Collections.Generic;
using CCodeGeneration;
using System;
using System.IO;
namespace LwipSnmpCodeGeneration
{
public class MibCFile
{
#region Fields
private const string PreservedSectionMarker = "LWIP MIB generator - preserved section begin";
private const string PreservedSectionHeader =
"+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n" +
PreservedSectionMarker + "\n" +
"Code below is preserved on regeneration. Remove these comment lines to regenerate code.\n" +
"+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";
private readonly List<CodeElement> includes = new List<CodeElement>();
private readonly List<CodeElement> defines = new List<CodeElement>();
private readonly List<CodeElement> declarations = new List<CodeElement>();
private readonly List<CodeElement> implementation = new List<CodeElement>();
private readonly List<CodeElement> preservedCode = new List<CodeElement>();
#endregion
public MibCFile()
{
}
#region Accessors
public List<CodeElement> Includes
{
get { return this.includes; }
}
public List<CodeElement> Defines
{
get { return this.defines; }
}
public List<CodeElement> Declarations
{
get { return this.declarations; }
}
public List<CodeElement> Implementation
{
get { return this.implementation; }
}
public List<CodeElement> PreservedCode
{
get { return this.preservedCode; }
}
#endregion
#region Methods
public void Save(CGenerator cGenerator)
{
CFile cFile = new CFile();
cFile.AddElement(new Comment("Generated by LwipMibCompiler"));
cFile.AddElement(EmptyLine.SingleLine);
cFile.AddElement(new PP_Include(LwipDefs.Incl_SnmpOpts));
CodeContainerBase e = cFile.AddElement(new PP_If(LwipDefs.Opt_SnmpEnabled)) as CodeContainerBase;
e.AddElement(EmptyLine.SingleLine);
// include header file
string file = cGenerator.FileName;
if (!String.IsNullOrWhiteSpace(file))
{
string ext = System.IO.Path.GetExtension(file);
string headerFile = !String.IsNullOrEmpty(ext) ? file.Substring(0, file.Length - ext.Length) : file;
headerFile += ".h";
e.AddElement(new PP_Include(headerFile));
}
// include common snmp files
e.AddElement(new PP_Include("lwip/apps/snmp.h"));
e.AddElement(new PP_Include("lwip/apps/snmp_core.h"));
e.AddElement(new PP_Include("lwip/apps/snmp_scalar.h"));
e.AddElement(new PP_Include("lwip/apps/snmp_table.h"));
if (this.includes.Count > 0)
{
e.AddElement(EmptyLine.SingleLine);
e.AddElements(this.includes);
}
if (this.defines.Count > 0)
{
e.AddElement(EmptyLine.SingleLine);
e.AddElements(this.defines);
}
if (this.declarations.Count > 0)
{
e.AddElement(EmptyLine.TwoLines);
e.AddElements(this.declarations);
}
if (this.implementation.Count > 0)
{
e.AddElement(EmptyLine.TwoLines);
e.AddElements(this.implementation);
}
if (this.preservedCode.Count > 0)
{
e.AddElement(EmptyLine.TwoLines);
e.AddElement(new Comment(PreservedSectionHeader));
e.AddElement(EmptyLine.SingleLine);
e.AddElements(this.preservedCode);
}
cFile.Save(cGenerator);
}
public static string GetPreservedCode(string file)
{
if (File.Exists(file))
{
using (StreamReader fileStream = new StreamReader(file))
{
while (!fileStream.EndOfStream)
{
string line = fileStream.ReadLine();
if (line == PreservedSectionMarker)
{
break;
}
}
if (!fileStream.EndOfStream)
{
// skip the rest of the comment + spacer line
fileStream.ReadLine(); // "Code below is preserved...
fileStream.ReadLine(); // "+++++++++++++++++++++++...
fileStream.ReadLine(); // */
fileStream.ReadLine(); //
string preservedCode = fileStream.ReadToEnd();
int lastEndif = preservedCode.LastIndexOf("#endif", StringComparison.Ordinal);
preservedCode = preservedCode.Remove(lastEndif);
return preservedCode;
}
}
}
return null;
}
#endregion
}
}

View File

@ -0,0 +1,129 @@
/*
* Copyright (c) 2001-2004 Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
*
* This file is part of the lwIP TCP/IP stack.
*
* Author: Martin Hentschel <info@cl-soft.de>
*
*/
using System.Collections.Generic;
using System.Text.RegularExpressions;
using CCodeGeneration;
namespace LwipSnmpCodeGeneration
{
public class MibHeaderFile
{
#region Fields
private readonly List<CodeElement> defines = new List<CodeElement>();
private readonly List<CodeElement> includes = new List<CodeElement>();
private readonly List<CodeElement> functionDeclarations = new List<CodeElement>();
private readonly List<CodeElement> variableDeclarations = new List<CodeElement>();
#endregion
public MibHeaderFile()
{
}
#region Accessors
public List<CodeElement> Defines
{
get { return this.defines; }
}
public List<CodeElement> Includes
{
get { return this.includes; }
}
public List<CodeElement> FunctionDeclarations
{
get { return this.functionDeclarations; }
}
public List<CodeElement> VariableDeclarations
{
get { return this.variableDeclarations; }
}
#endregion
#region Methods
public void Save(CGenerator cGenerator)
{
CFile cFile = new CFile();
cFile.AddElement(new Comment("Generated by LwipMibCompiler"));
cFile.AddElement(EmptyLine.SingleLine);
string headerDefine = cGenerator.FileName;
headerDefine = new Regex("[^a-zA-Z0-9]").Replace(headerDefine, "_");
headerDefine = headerDefine.ToUpperInvariant();
CodeContainerBase e = cFile.AddElement(new PP_Ifdef(headerDefine, inverted: true)) as CodeContainerBase;
e.AddElement(new PP_Macro(headerDefine, headerDefine));
e.AddElement(EmptyLine.SingleLine);
e.AddElement(new PP_Include(LwipDefs.Incl_SnmpOpts));
e = e.AddElement(new PP_If(LwipDefs.Opt_SnmpEnabled)) as CodeContainerBase;
e.AddElement(EmptyLine.SingleLine);
CodeContainerBase cplusplusopen = e.AddElement(new PP_Ifdef("__cplusplus")) as CodeContainerBase;
cplusplusopen.AddElement(new Code("extern \"C\" {"));
e.AddElement(EmptyLine.SingleLine);
if (this.includes.Count > 0)
{
e.AddElements(this.includes);
e.AddElement(EmptyLine.SingleLine);
}
if (this.defines.Count > 0)
{
e.AddElements(this.defines);
e.AddElement(EmptyLine.SingleLine);
}
e.AddElements(this.functionDeclarations, EmptyLine.SingleLine);
e.AddElements(this.variableDeclarations, EmptyLine.SingleLine);
e.AddElement(EmptyLine.SingleLine);
CodeContainerBase cplusplusclose = e.AddElement(new PP_Ifdef("__cplusplus")) as CodeContainerBase;
cplusplusclose.AddElement(new Code("}"));
e.AddElement(EmptyLine.SingleLine);
cFile.Save(cGenerator);
}
#endregion
}
}

View File

@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// Allgemeine Informationen über eine Assembly werden über die folgenden
// Attribute gesteuert. Ändern Sie diese Attributwerte, um die Informationen zu ändern,
// die mit einer Assembly verknüpft sind.
[assembly: AssemblyTitle("LwipSnmpCodeGeneration")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("LwipSnmpCodeGeneration")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Durch Festlegen von ComVisible auf "false" werden die Typen in dieser Assembly unsichtbar
// für COM-Komponenten. Wenn Sie auf einen Typ in dieser Assembly von
// COM zugreifen müssen, legen Sie das ComVisible-Attribut für diesen Typ auf "true" fest.
[assembly: ComVisible(false)]
// Die folgende GUID bestimmt die ID der Typbibliothek, wenn dieses Projekt für COM verfügbar gemacht wird
[assembly: Guid("8cfbbb8b-dfbb-4dd5-80c9-e07845dd58c9")]
// Versionsinformationen für eine Assembly bestehen aus den folgenden vier Werten:
//
// Hauptversion
// Nebenversion
// Buildnummer
// Revision
//
// Sie können alle Werte angeben oder die standardmäßigen Build- und Revisionsnummern
// übernehmen, indem Sie "*" eingeben:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

View File

@ -0,0 +1,97 @@
/*
* Copyright (c) 2001-2004 Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
*
* This file is part of the lwIP TCP/IP stack.
*
* Author: Martin Hentschel <info@cl-soft.de>
*
*/
using System;
using System.Text;
using CCodeGeneration;
namespace LwipSnmpCodeGeneration
{
public class SnmpMib : SnmpTreeNode
{
public int[] BaseOid { get; set; }
public SnmpMib()
: base(null)
{
}
public SnmpMib(int[] baseOid)
: base(null)
{
this.BaseOid = baseOid;
}
public override string FullNodeName
{
get { return this.Name + "_root"; }
}
public override void GenerateCode(MibCFile mibFile)
{
base.GenerateCode(mibFile);
System.Diagnostics.Debug.Assert((this.BaseOid != null) && (this.BaseOid.Length > 0));
// create and add BaseOID declarations
StringBuilder boidInitialization = new StringBuilder("{");
foreach (int t in this.BaseOid)
{
boidInitialization.Append(t);
boidInitialization.Append(",");
}
boidInitialization.Length -= 1;
boidInitialization.Append("}");
VariableDeclaration boidDecl = new VariableDeclaration(
new VariableType(this.Name + "_base_oid", LwipDefs.Vt_U32, null, ConstType.Value, String.Empty),
boidInitialization.ToString(), true);
mibFile.Declarations.Add(boidDecl);
mibFile.Declarations.Add(GetExportDeclaration());
}
public override void GenerateHeaderCode(MibHeaderFile mibHeaderFile)
{
mibHeaderFile.Includes.Add(new PP_Include("lwip/apps/snmp_core.h"));
mibHeaderFile.VariableDeclarations.Add(VariablePrototype.FromVariableDeclaration(GetExportDeclaration()));
}
VariableDeclaration GetExportDeclaration()
{
return new VariableDeclaration(
new VariableType(this.Name, LwipDefs.Vt_StMib, null, ConstType.Value),
String.Format("{{{0}_base_oid, LWIP_ARRAYSIZE({0}_base_oid), &{1}.node}}", this.Name, this.FullNodeName));
}
}
}

View File

@ -0,0 +1,119 @@
/*
* Copyright (c) 2001-2004 Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
*
* This file is part of the lwIP TCP/IP stack.
*
* Author: Martin Hentschel <info@cl-soft.de>
*
*/
using System;
using System.Text.RegularExpressions;
using CCodeGeneration;
namespace LwipSnmpCodeGeneration
{
public abstract class SnmpNode
{
public static readonly Regex NameValidationRegex = new Regex(@"^\w+$");
private string name;
private readonly SnmpTreeNode parentNode;
protected SnmpNode(SnmpTreeNode parentNode)
{
this.parentNode = parentNode;
}
public SnmpTreeNode ParentNode
{
get { return this.parentNode; }
}
public virtual uint Oid { get; set; }
public abstract string FullNodeName
{
get;
}
public virtual string Name
{
get { return this.name; }
set
{
if (value != this.name)
{
// check for valid name
if (!NameValidationRegex.IsMatch(value))
{
throw new ArgumentOutOfRangeException("Name");
}
this.name = value;
}
}
}
public virtual void Generate(MibCFile generatedFile, MibHeaderFile generatedHeaderFile)
{
int declCount = generatedFile.Declarations.Count;
int implCount = generatedFile.Implementation.Count;
this.GenerateHeaderCode(generatedHeaderFile);
this.GenerateCode(generatedFile);
if (generatedFile.Declarations.Count != declCount)
{
generatedFile.Declarations.Add(EmptyLine.SingleLine);
}
if (generatedFile.Implementation.Count != implCount)
{
generatedFile.Implementation.Add(EmptyLine.SingleLine);
}
}
public abstract void GenerateCode(MibCFile mibFile);
public virtual void GenerateHeaderCode(MibHeaderFile mibHeaderFile)
{
}
/// <summary>
/// Called after node structure creation is completed and before code is created.
/// Offers the possibility to perform operations depending on properties/subnodes.
/// If the node shall be transformed to another node(-type) than the own instance
/// may be replaced on parent node by the transformed instance.
/// Calling sequence is always from leafs up to root. So a tree node can assume
/// that the analyze method was already called on all child nodes.
/// E.g. a tree node only has scalar sub nodes -> it transforms itself to a scalar array node
/// </summary>
/// <returns>The transformed node or null if nothing shall be changed in parent structure.</returns>
public virtual void Analyze()
{
}
}
}

View File

@ -0,0 +1,293 @@
/*
* Copyright (c) 2001-2004 Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
*
* This file is part of the lwIP TCP/IP stack.
*
* Author: Martin Hentschel <info@cl-soft.de>
*
*/
using System.Collections.Generic;
using System.Globalization;
using CCodeGeneration;
namespace LwipSnmpCodeGeneration
{
public abstract class SnmpScalarAggregationNode: SnmpNode
{
private bool getMethodRequired = false;
private bool testMethodRequired = false;
private bool setMethodRequired = false;
protected SnmpScalarAggregationNode(SnmpTreeNode parentNode)
: base(parentNode)
{
}
protected virtual string GetMethodName
{
get { return this.FullNodeName + LwipDefs.FnctSuffix_GetValue; }
}
protected bool GetMethodRequired
{
get { return this.getMethodRequired; }
}
protected virtual string TestMethodName
{
get { return this.FullNodeName + LwipDefs.FnctSuffix_SetTest; }
}
protected bool TestMethodRequired
{
get { return this.testMethodRequired; }
}
protected virtual string SetMethodName
{
get { return this.FullNodeName + LwipDefs.FnctSuffix_SetValue; }
}
protected bool SetMethodRequired
{
get { return this.setMethodRequired; }
}
protected abstract IEnumerable<SnmpScalarNode> AggregatedScalarNodes
{
get;
}
public override void Analyze()
{
base.Analyze();
this.getMethodRequired = false;
this.testMethodRequired = false;
this.setMethodRequired = false;
foreach (SnmpScalarNode scalarNode in this.AggregatedScalarNodes)
{
if ((scalarNode.AccessMode == SnmpAccessMode.ReadOnly) || (scalarNode.AccessMode == SnmpAccessMode.ReadWrite))
{
this.getMethodRequired = true;
}
if ((scalarNode.AccessMode == SnmpAccessMode.WriteOnly) || (scalarNode.AccessMode == SnmpAccessMode.ReadWrite))
{
this.testMethodRequired = true;
this.setMethodRequired = true;
}
if (this.getMethodRequired && this.setMethodRequired)
{
break;
}
}
}
protected void GenerateAggregatedCode(MibCFile mibFile, VariableType instanceType, string switchSelector, bool generateDeclarations = true, bool generateImplementations = true)
{
if (this.getMethodRequired)
{
FunctionDeclaration getMethodDecl = new FunctionDeclaration(this.GetMethodName, isStatic: true);
getMethodDecl.Parameter.Add(instanceType);
getMethodDecl.Parameter.Add(new VariableType("value", VariableType.VoidString, "*"));
getMethodDecl.ReturnType = new VariableType(null, LwipDefs.Vt_U16);
if (generateDeclarations)
{
mibFile.Declarations.Add(getMethodDecl);
}
if (generateImplementations)
{
Function getMethod = Function.FromDeclaration(getMethodDecl);
GenerateGetMethodCode(getMethod, switchSelector);
mibFile.Implementation.Add(getMethod);
}
}
if (this.testMethodRequired)
{
FunctionDeclaration testMethodDecl = new FunctionDeclaration(this.TestMethodName, isStatic: true);
testMethodDecl.Parameter.Add(instanceType);
testMethodDecl.Parameter.Add(new VariableType("len", LwipDefs.Vt_U16));
testMethodDecl.Parameter.Add(new VariableType("value", VariableType.VoidString, "*"));
testMethodDecl.ReturnType = new VariableType(null, LwipDefs.Vt_Snmp_err);
if (generateDeclarations)
{
mibFile.Declarations.Add(testMethodDecl);
}
if (generateImplementations)
{
Function testMethod = Function.FromDeclaration(testMethodDecl);
GenerateTestMethodCode(testMethod, switchSelector);
mibFile.Implementation.Add(testMethod);
}
}
if (this.setMethodRequired)
{
FunctionDeclaration setMethodDecl = new FunctionDeclaration(this.SetMethodName, isStatic: true);
setMethodDecl.Parameter.Add(instanceType);
setMethodDecl.Parameter.Add(new VariableType("len", LwipDefs.Vt_U16));
setMethodDecl.Parameter.Add(new VariableType("value", VariableType.VoidString, "*"));
setMethodDecl.ReturnType = new VariableType(null, LwipDefs.Vt_Snmp_err);
if (generateDeclarations)
{
mibFile.Declarations.Add(setMethodDecl);
}
if (generateImplementations)
{
Function setMethod = Function.FromDeclaration(setMethodDecl);
GenerateSetMethodCode(setMethod, switchSelector);
mibFile.Implementation.Add(setMethod);
}
}
}
protected virtual void GenerateGetMethodCode(Function getMethod, string switchSelector)
{
VariableDeclaration returnValue = new VariableDeclaration((VariableType)getMethod.ReturnType.Clone());
returnValue.Type.Name = "value_len";
getMethod.Declarations.Add(returnValue);
Switch sw = new Switch(switchSelector);
bool valueVarUsed = false;
foreach (SnmpScalarNode scalarNode in this.AggregatedScalarNodes)
{
if ((scalarNode.AccessMode == SnmpAccessMode.ReadOnly) || (scalarNode.AccessMode == SnmpAccessMode.ReadWrite))
{
SwitchCase sc = new SwitchCase(scalarNode.Oid.ToString(CultureInfo.InvariantCulture));
sc.Declarations.Add(new Comment(scalarNode.Name, singleLine: true));
scalarNode.GenerateGetMethodCode(sc, getMethod.Parameter[1].Name, ref valueVarUsed, returnValue.Type.Name);
sw.Switches.Add(sc);
}
}
SwitchCase scd = SwitchCase.GenerateDefault();
scd.AddCodeFormat("LWIP_DEBUGF(SNMP_MIB_DEBUG,(\"{0}(): unknown id: %\"S32_F\"\\n\", {1}));", getMethod.Name, switchSelector);
scd.AddCodeFormat("{0} = 0;", returnValue.Type.Name);
sw.Switches.Add(scd);
if (!valueVarUsed)
{
getMethod.AddCodeFormat("LWIP_UNUSED_ARG({0});", getMethod.Parameter[1].Name);
}
getMethod.AddElement(sw);
getMethod.AddCodeFormat("return {0};", returnValue.Type.Name);
}
protected virtual void GenerateTestMethodCode(Function testMethod, string switchSelector)
{
VariableDeclaration returnValue = new VariableDeclaration((VariableType)testMethod.ReturnType.Clone(), LwipDefs.Def_ErrorCode_WrongValue);
returnValue.Type.Name = "err";
testMethod.Declarations.Add(returnValue);
Switch sw = new Switch(switchSelector);
bool valueVarUsed = false;
bool lenVarUsed = false;
foreach (SnmpScalarNode scalarNode in this.AggregatedScalarNodes)
{
if ((scalarNode.AccessMode == SnmpAccessMode.WriteOnly) || (scalarNode.AccessMode == SnmpAccessMode.ReadWrite))
{
SwitchCase sc = new SwitchCase(scalarNode.Oid.ToString(CultureInfo.InvariantCulture));
sc.Declarations.Add(new Comment(scalarNode.Name, singleLine: true));
scalarNode.GenerateTestMethodCode(sc, testMethod.Parameter[2].Name, ref valueVarUsed, testMethod.Parameter[1].Name, ref lenVarUsed, returnValue.Type.Name);
sw.Switches.Add(sc);
}
}
SwitchCase scd = SwitchCase.GenerateDefault();
scd.AddCodeFormat("LWIP_DEBUGF(SNMP_MIB_DEBUG,(\"{0}(): unknown id: %\"S32_F\"\\n\", {1}));", testMethod.Name, switchSelector);
sw.Switches.Add(scd);
if (!valueVarUsed)
{
testMethod.AddCodeFormat("LWIP_UNUSED_ARG({0});", testMethod.Parameter[2].Name);
}
if (!lenVarUsed)
{
testMethod.AddCodeFormat("LWIP_UNUSED_ARG({0});", testMethod.Parameter[1].Name);
}
testMethod.AddElement(sw);
testMethod.AddCodeFormat("return {0};", returnValue.Type.Name);
}
protected virtual void GenerateSetMethodCode(Function setMethod, string switchSelector)
{
VariableDeclaration returnValue = new VariableDeclaration((VariableType)setMethod.ReturnType.Clone(), LwipDefs.Def_ErrorCode_Ok);
returnValue.Type.Name = "err";
setMethod.Declarations.Add(returnValue);
Switch sw = new Switch(switchSelector);
bool valueVarUsed = false;
bool lenVarUsed = false;
foreach (SnmpScalarNode scalarNode in this.AggregatedScalarNodes)
{
if ((scalarNode.AccessMode == SnmpAccessMode.WriteOnly) || (scalarNode.AccessMode == SnmpAccessMode.ReadWrite))
{
SwitchCase sc = new SwitchCase(scalarNode.Oid.ToString(CultureInfo.InvariantCulture));
sc.Declarations.Add(new Comment(scalarNode.Name, singleLine: true));
scalarNode.GenerateSetMethodCode(sc, setMethod.Parameter[2].Name, ref valueVarUsed, setMethod.Parameter[1].Name, ref lenVarUsed, returnValue.Type.Name);
sw.Switches.Add(sc);
}
}
SwitchCase scd = SwitchCase.GenerateDefault();
scd.AddCodeFormat("LWIP_DEBUGF(SNMP_MIB_DEBUG,(\"{0}(): unknown id: %\"S32_F\"\\n\", {1}));", setMethod.Name, switchSelector);
sw.Switches.Add(scd);
if (!valueVarUsed)
{
setMethod.AddCodeFormat("LWIP_UNUSED_ARG({0});", setMethod.Parameter[2].Name);
}
if (!lenVarUsed)
{
setMethod.AddCodeFormat("LWIP_UNUSED_ARG({0});", setMethod.Parameter[1].Name);
}
setMethod.AddElement(sw);
setMethod.AddCodeFormat("return {0};", returnValue.Type.Name);
}
}
}

View File

@ -0,0 +1,105 @@
/*
* Copyright (c) 2001-2004 Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
*
* This file is part of the lwIP TCP/IP stack.
*
* Author: Martin Hentschel <info@cl-soft.de>
*
*/
using System;
using System.Collections.Generic;
using System.Text;
using CCodeGeneration;
namespace LwipSnmpCodeGeneration
{
public class SnmpScalarArrayNode : SnmpScalarAggregationNode
{
private readonly List<SnmpScalarNode> scalarNodes;
public SnmpScalarArrayNode(List<SnmpScalarNode> scalarNodes, SnmpTreeNode parentNode)
: base(parentNode)
{
this.scalarNodes = scalarNodes;
}
public override string FullNodeName
{
get { return this.Name + "_scalars"; }
}
protected override IEnumerable<SnmpScalarNode> AggregatedScalarNodes
{
get { return this.scalarNodes; }
}
public override void GenerateCode(MibCFile mibFile)
{
VariableType instanceType = new VariableType("node", LwipDefs.Vt_StScalarArrayNodeDef, "*", ConstType.Value);
GenerateAggregatedCode(
mibFile,
instanceType,
instanceType.Name + "->oid");
// create and add node definitions
StringBuilder nodeDefs = new StringBuilder();
foreach (SnmpScalarNode scalarNode in this.scalarNodes)
{
nodeDefs.AppendFormat(" {{{0}, {1}, {2}}}, /* {3} */ \n",
scalarNode.Oid,
LwipDefs.GetAsn1DefForSnmpDataType(scalarNode.DataType),
LwipDefs.GetLwipDefForSnmpAccessMode(scalarNode.AccessMode),
scalarNode.Name);
}
if (nodeDefs.Length > 0)
nodeDefs.Length--;
VariableDeclaration nodeDefsDecl = new VariableDeclaration(
new VariableType(this.FullNodeName + "_nodes", LwipDefs.Vt_StScalarArrayNodeDef, null, ConstType.Value, String.Empty),
"{\n" + nodeDefs + "\n}" ,
isStatic: true);
mibFile.Declarations.Add(nodeDefsDecl);
// create and add node declaration
string nodeInitialization = String.Format("SNMP_SCALAR_CREATE_ARRAY_NODE({0}, {1}, {2}, {3}, {4})",
this.Oid,
nodeDefsDecl.Type.Name,
(this.GetMethodRequired) ? this.GetMethodName : LwipDefs.Null,
(this.TestMethodRequired) ? this.TestMethodName : LwipDefs.Null,
(this.SetMethodRequired) ? this.SetMethodName : LwipDefs.Null
);
mibFile.Declarations.Add(new VariableDeclaration(
new VariableType(this.FullNodeName, LwipDefs.Vt_StScalarArrayNode, null, ConstType.Value),
nodeInitialization,
isStatic: true));
}
}
}

View File

@ -0,0 +1,395 @@
/*
* Copyright (c) 2001-2004 Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
*
* This file is part of the lwIP TCP/IP stack.
*
* Author: Martin Hentschel <info@cl-soft.de>
*
*/
using System;
using System.Collections.Generic;
using CCodeGeneration;
namespace LwipSnmpCodeGeneration
{
public class SnmpScalarNode: SnmpNode
{
protected const string LocalValueName = "v"; // name of (casted) local value variable
private SnmpDataType dataType;
private SnmpAccessMode accessMode;
private readonly List<IRestriction> restrictions = new List<IRestriction>();
private bool useExternalMethods = false;
private string externalGetMethod;
private string externalTestMethod;
private string externalSetMethod;
public SnmpScalarNode(SnmpTreeNode parentNode)
: base(parentNode)
{
}
public override string FullNodeName
{
get { return this.Name + "_scalar"; }
}
public SnmpDataType DataType
{
get { return this.dataType; }
set { this.dataType = value; }
}
public List<IRestriction> Restrictions
{
get { return this.restrictions; }
}
public SnmpAccessMode AccessMode
{
get { return this.accessMode; }
set { this.accessMode = value; }
}
public virtual string FixedValueLength
{
get { return null; }
}
/// <summary>
/// If scalar is used as a table index its value becomes part of the OID. This value returns how many OID parts are required to represent this value.
/// </summary>
public virtual int OidRepresentationLen
{
get { return -1; }
}
public bool UseExternalMethods
{
get { return this.useExternalMethods; }
set { this.useExternalMethods = value; }
}
public string ExternalGetMethod
{
get { return this.externalGetMethod; }
set { this.externalGetMethod = value; }
}
public string ExternalTestMethod
{
get { return this.externalTestMethod; }
set { this.externalTestMethod = value; }
}
public string ExternalSetMethod
{
get { return this.externalSetMethod; }
set { this.externalSetMethod = value; }
}
public override void GenerateCode(MibCFile mibFile)
{
string getMethodName;
string testMethodName;
string setMethodName;
if (this.useExternalMethods)
{
getMethodName = this.externalGetMethod;
testMethodName = this.externalTestMethod;
setMethodName = this.externalSetMethod;
}
else
{
getMethodName = LwipDefs.Null;
testMethodName = LwipDefs.Null;
setMethodName = LwipDefs.Null;
if ((this.accessMode == SnmpAccessMode.ReadWrite) || (this.accessMode == SnmpAccessMode.ReadOnly))
{
FunctionDeclaration getMethodDecl = new FunctionDeclaration(this.Name + LwipDefs.FnctSuffix_GetValue, isStatic: true);
getMethodDecl.Parameter.Add(new VariableType("instance", LwipDefs.Vt_StNodeInstance, "*"));
getMethodDecl.Parameter.Add(new VariableType("value", VariableType.VoidString, "*"));
getMethodDecl.ReturnType = new VariableType(null, LwipDefs.Vt_U16);
mibFile.Declarations.Add(getMethodDecl);
Function getMethod = Function.FromDeclaration(getMethodDecl);
getMethodName = getMethod.Name;
VariableDeclaration returnValue = new VariableDeclaration((VariableType)getMethod.ReturnType.Clone());
returnValue.Type.Name = "value_len";
getMethod.Declarations.Add(returnValue);
getMethod.AddCodeFormat("LWIP_UNUSED_ARG({0});", getMethod.Parameter[0].Name);
bool valueVarUsed = false;
GenerateGetMethodCode(getMethod, getMethod.Parameter[1].Name, ref valueVarUsed, returnValue.Type.Name);
if (!valueVarUsed)
{
getMethod.AddCodeFormat("LWIP_UNUSED_ARG({0});", getMethod.Parameter[1].Name);
}
getMethod.AddCodeFormat("return {0};", returnValue.Type.Name);
mibFile.Implementation.Add(getMethod);
}
if ((this.accessMode == SnmpAccessMode.ReadWrite) || (this.accessMode == SnmpAccessMode.WriteOnly))
{
bool valueVarUsed;
bool lenVarUsed;
VariableDeclaration returnValue;
if (this.restrictions.Count > 0)
{
FunctionDeclaration testMethodDecl = new FunctionDeclaration(this.Name + LwipDefs.FnctSuffix_SetTest, isStatic: true);
testMethodDecl.Parameter.Add(new VariableType("instance", LwipDefs.Vt_StNodeInstance, "*"));
testMethodDecl.Parameter.Add(new VariableType("len", LwipDefs.Vt_U16));
testMethodDecl.Parameter.Add(new VariableType("value", VariableType.VoidString, "*"));
testMethodDecl.ReturnType = new VariableType(null, LwipDefs.Vt_Snmp_err);
mibFile.Declarations.Add(testMethodDecl);
Function testMethod = Function.FromDeclaration(testMethodDecl);
testMethodName = testMethod.Name;
returnValue = new VariableDeclaration((VariableType)testMethod.ReturnType.Clone(), LwipDefs.Def_ErrorCode_WrongValue);
returnValue.Type.Name = "err";
testMethod.Declarations.Add(returnValue);
testMethod.AddCodeFormat("LWIP_UNUSED_ARG({0});", testMethod.Parameter[0].Name);
valueVarUsed = false;
lenVarUsed = false;
GenerateTestMethodCode(testMethod, testMethod.Parameter[2].Name, ref valueVarUsed, testMethod.Parameter[1].Name, ref lenVarUsed, returnValue.Type.Name);
if (!valueVarUsed)
{
testMethod.AddCodeFormat("LWIP_UNUSED_ARG({0});", testMethod.Parameter[2].Name);
}
if (!lenVarUsed)
{
testMethod.AddCodeFormat("LWIP_UNUSED_ARG({0});", testMethod.Parameter[1].Name);
}
testMethod.AddCodeFormat("return {0};", returnValue.Type.Name);
mibFile.Implementation.Add(testMethod);
}
else
{
testMethodName = LwipDefs.FnctName_SetTest_Ok;
}
FunctionDeclaration setMethodDecl = null;
setMethodDecl = new FunctionDeclaration(this.Name + LwipDefs.FnctSuffix_SetValue, isStatic: true);
setMethodDecl.Parameter.Add(new VariableType("instance", LwipDefs.Vt_StNodeInstance, "*"));
setMethodDecl.Parameter.Add(new VariableType("len", LwipDefs.Vt_U16));
setMethodDecl.Parameter.Add(new VariableType("value", VariableType.VoidString, "*"));
setMethodDecl.ReturnType = new VariableType(null, LwipDefs.Vt_Snmp_err);
mibFile.Declarations.Add(setMethodDecl);
Function setMethod = Function.FromDeclaration(setMethodDecl);
setMethodName = setMethod.Name;
returnValue = new VariableDeclaration((VariableType)setMethod.ReturnType.Clone(), LwipDefs.Def_ErrorCode_Ok);
returnValue.Type.Name = "err";
setMethod.Declarations.Add(returnValue);
setMethod.AddCodeFormat("LWIP_UNUSED_ARG({0});", setMethod.Parameter[0].Name);
valueVarUsed = false;
lenVarUsed = false;
GenerateSetMethodCode(setMethod, setMethod.Parameter[2].Name, ref valueVarUsed, setMethod.Parameter[1].Name, ref lenVarUsed, returnValue.Type.Name);
if (!valueVarUsed)
{
setMethod.AddCodeFormat("LWIP_UNUSED_ARG({0});", setMethod.Parameter[2].Name);
}
if (!lenVarUsed)
{
setMethod.AddCodeFormat("LWIP_UNUSED_ARG({0});", setMethod.Parameter[1].Name);
}
setMethod.AddCodeFormat("return {0};", returnValue.Type.Name);
mibFile.Implementation.Add(setMethod);
}
}
// create and add node declaration
string nodeInitialization;
if (this.accessMode == SnmpAccessMode.ReadOnly)
{
nodeInitialization = String.Format("SNMP_SCALAR_CREATE_NODE_READONLY({0}, {1}, {2})",
this.Oid,
LwipDefs.GetAsn1DefForSnmpDataType(this.dataType),
getMethodName);
}
else
{
nodeInitialization = String.Format("SNMP_SCALAR_CREATE_NODE({0}, {1}, {2}, {3}, {4}, {5})",
this.Oid,
LwipDefs.GetLwipDefForSnmpAccessMode(this.accessMode),
LwipDefs.GetAsn1DefForSnmpDataType(this.dataType),
getMethodName,
testMethodName,
setMethodName);
}
mibFile.Declarations.Add(new VariableDeclaration(
new VariableType(this.FullNodeName, LwipDefs.Vt_StScalarNode, null, ConstType.Value),
nodeInitialization, isStatic: true));
}
public virtual void GenerateGetMethodCode(CodeContainerBase container, string valueVarName, ref bool valueVarUsed, string retLenVarName)
{
bool localValueVarUsed;
if (GenerateValueDeclaration(container, LocalValueName, valueVarName))
{
valueVarUsed = true;
localValueVarUsed = false;
}
else
{
localValueVarUsed = true; // do not generate UNUSED_ARG code
}
if (this.FixedValueLength == null)
{
// check that value with variable length fits into buffer
container.AddElement(new Comment(String.Format("TODO: take care that value with variable length fits into buffer: ({0} <= SNMP_MAX_VALUE_SIZE)", retLenVarName), singleLine: true));
}
GenerateGetMethodCodeCore(container, LocalValueName, ref localValueVarUsed, retLenVarName);
if (!localValueVarUsed)
{
container.AddCode(String.Format("LWIP_UNUSED_ARG({0});", LocalValueName));
}
}
protected virtual void GenerateGetMethodCodeCore(CodeContainerBase container, string localValueVarName, ref bool localValueVarUsed, string retLenVarName)
{
container.AddElement(new Comment(String.Format("TODO: put requested value to '*{0}' here", localValueVarName), singleLine: true));
container.AddCodeFormat("{0} = {1};",
retLenVarName,
(!String.IsNullOrWhiteSpace(this.FixedValueLength)) ? this.FixedValueLength : "0");
}
public virtual void GenerateTestMethodCode(CodeContainerBase container, string valueVarName, ref bool valueVarUsed, string lenVarName, ref bool lenVarUsed, string retErrVarName)
{
if (this.Restrictions.Count > 0)
{
bool localVarUsed;
if (GenerateValueDeclaration(container, LocalValueName, valueVarName))
{
valueVarUsed = true;
localVarUsed = false;
}
else
{
localVarUsed = true; // do not generate UNUSED_ARG code
}
if (!String.IsNullOrWhiteSpace(this.FixedValueLength))
{
// check for fixed value
container.AddCodeFormat("LWIP_ASSERT(\"Invalid length for datatype\", ({0} == {1}));", lenVarName, this.FixedValueLength);
lenVarUsed = true;
}
GenerateTestMethodCodeCore(container, LocalValueName, ref localVarUsed, lenVarName, ref lenVarUsed, retErrVarName);
if (!localVarUsed)
{
container.AddCode(String.Format("LWIP_UNUSED_ARG({0});", LocalValueName));
}
}
else
{
container.AddCodeFormat("{0} == {1};", retErrVarName, LwipDefs.Def_ErrorCode_Ok);
}
}
protected virtual void GenerateTestMethodCodeCore(CodeContainerBase container, string localValueVarName, ref bool localValueVarUsed, string lenVarName, ref bool lenVarUsed, string retErrVarName)
{
container.AddElement(new Comment(String.Format("TODO: test new value here:\nif (*{0} == ) {1} = {2};", localValueVarName, retErrVarName, LwipDefs.Def_ErrorCode_Ok)));
}
public virtual void GenerateSetMethodCode(CodeContainerBase container, string valueVarName, ref bool valueVarUsed, string lenVarName, ref bool lenVarUsed, string retErrVarName)
{
bool localVarUsed;
if (GenerateValueDeclaration(container, LocalValueName, valueVarName))
{
valueVarUsed = true;
localVarUsed = false;
}
else
{
localVarUsed = true; // do not generate UNUSED_ARG code
}
GenerateSetMethodCodeCore(container, LocalValueName, ref localVarUsed, lenVarName, ref lenVarUsed, retErrVarName);
if (!localVarUsed)
{
container.AddCode(String.Format("LWIP_UNUSED_ARG({0});", LocalValueName));
}
}
protected virtual void GenerateSetMethodCodeCore(CodeContainerBase container, string localValueVarName, ref bool localValueVarUsed, string lenVarName, ref bool lenVarUsed, string retErrVarName)
{
container.AddElement(new Comment(String.Format("TODO: store new value contained in '*{0}' here", localValueVarName), singleLine: true));
}
protected virtual bool GenerateValueDeclaration(CodeContainerBase container, string variableName, string sourceName)
{
container.AddDeclaration(new VariableDeclaration(
new VariableType(variableName, LwipDefs.Vt_U8, "*"),
"(" + new VariableType(null, LwipDefs.Vt_U8, "*") + ")" + sourceName));
return true;
}
public static SnmpScalarNode CreateFromDatatype(SnmpDataType dataType, SnmpTreeNode parentNode)
{
switch (dataType)
{
case SnmpDataType.Integer:
return new SnmpScalarNodeInt(parentNode);
case SnmpDataType.Gauge:
case SnmpDataType.Counter:
case SnmpDataType.TimeTicks:
return new SnmpScalarNodeUint(dataType, parentNode);
}
return new SnmpScalarNode(parentNode);
}
}
}

View File

@ -0,0 +1,121 @@
/*
* Copyright (c) 2001-2004 Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
*
* This file is part of the lwIP TCP/IP stack.
*
* Author: Martin Hentschel <info@cl-soft.de>
*
*/
using System;
using System.Text;
using CCodeGeneration;
namespace LwipSnmpCodeGeneration
{
public class SnmpScalarNodeBits : SnmpScalarNode
{
private readonly uint bitCount;
public SnmpScalarNodeBits(SnmpTreeNode parentNode, uint bitCount)
: base(parentNode)
{
this.DataType = SnmpDataType.Bits;
this.bitCount = bitCount;
}
public override void GenerateGetMethodCode(CodeContainerBase container, string valueVarName, ref bool valueVarUsed, string retLenVarName)
{
container.AddCode(String.Format(
"{0} = snmp_encode_bits(({1} *){2}, SNMP_MAX_VALUE_SIZE, 0 /* TODO: pass real value here */, {3});",
retLenVarName,
LwipDefs.Vt_U8,
valueVarName,
this.bitCount));
valueVarUsed = true;
}
public override void GenerateTestMethodCode(CodeContainerBase container, string valueVarName, ref bool valueVarUsed, string lenVarName, ref bool lenVarUsed, string retErrVarName)
{
if (this.Restrictions.Count > 0)
{
const string bitVarName = "bits";
container.Declarations.Add(new VariableDeclaration(new VariableType(bitVarName, LwipDefs.Vt_U32)));
IfThenElse ite = new IfThenElse(String.Format(
"snmp_decode_bits(({0} *){1}, {2}, &{3}) == ERR_OK",
LwipDefs.Vt_U8,
valueVarName,
lenVarName,
bitVarName));
valueVarUsed = true;
lenVarUsed = true;
StringBuilder innerIfCond = new StringBuilder();
foreach (IRestriction restriction in this.Restrictions)
{
innerIfCond.Append(restriction.GetCheckCodeValid(bitVarName));
innerIfCond.Append(" || ");
}
innerIfCond.Length -= 4;
IfThenElse innerIte = new IfThenElse(innerIfCond.ToString());
innerIte.AddCode(String.Format("{0} = {1};", retErrVarName, LwipDefs.Def_ErrorCode_Ok));
ite.AddElement(innerIte);
container.AddElement(ite);
}
else
{
base.GenerateTestMethodCode(container, valueVarName, ref valueVarUsed, lenVarName, ref lenVarUsed, retErrVarName);
}
}
public override void GenerateSetMethodCode(CodeContainerBase container, string valueVarName, ref bool valueVarUsed, string lenVarName, ref bool lenVarUsed, string retErrVarName)
{
const string bitVarName = "bits";
container.Declarations.Add(new VariableDeclaration(new VariableType(bitVarName, LwipDefs.Vt_U32)));
IfThenElse ite = new IfThenElse(String.Format(
"snmp_decode_bits(({0} *){1}, {2}, &{3}) == ERR_OK",
LwipDefs.Vt_U8,
valueVarName,
lenVarName,
bitVarName));
valueVarUsed = true;
lenVarUsed = true;
ite.AddElement(new Comment(String.Format("TODO: store new value contained in '{0}' here", bitVarName), singleLine: true));
container.AddElement(ite);
}
}
}

View File

@ -0,0 +1,72 @@
/*
* Copyright (c) 2001-2004 Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
*
* This file is part of the lwIP TCP/IP stack.
*
* Author: Martin Hentschel <info@cl-soft.de>
*
*/
using System;
using System.Text;
using CCodeGeneration;
namespace LwipSnmpCodeGeneration
{
public class SnmpScalarNodeCounter64 : SnmpScalarNode
{
public SnmpScalarNodeCounter64(SnmpTreeNode parentNode)
: base(parentNode)
{
this.DataType = SnmpDataType.Counter64;
}
protected override bool GenerateValueDeclaration(CodeContainerBase container, string variableName, string sourceName)
{
container.AddDeclaration(new VariableDeclaration(
new VariableType(variableName + "_high", LwipDefs.Vt_U32, "*"),
"(" + new VariableType(null, LwipDefs.Vt_U32, "*").ToString() + ")" + sourceName));
container.AddDeclaration(new VariableDeclaration(
new VariableType(variableName + "_low", LwipDefs.Vt_U32, "*"),
variableName + "_high + 1"));
container.AddCode(String.Format("LWIP_UNUSED_ARG({0}_high);", variableName));
container.AddCode(String.Format("LWIP_UNUSED_ARG({0}_low);", variableName));
return false;
}
public override string FixedValueLength
{
get { return String.Format("(2 * sizeof({0}))", LwipDefs.Vt_U32); }
}
public override int OidRepresentationLen
{
get { return 1; }
}
}
}

View File

@ -0,0 +1,86 @@
/*
* Copyright (c) 2001-2004 Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
*
* This file is part of the lwIP TCP/IP stack.
*
* Author: Martin Hentschel <info@cl-soft.de>
*
*/
using System;
using System.Text;
using CCodeGeneration;
namespace LwipSnmpCodeGeneration
{
public class SnmpScalarNodeInt : SnmpScalarNode
{
public SnmpScalarNodeInt(SnmpTreeNode parentNode)
: base(parentNode)
{
this.DataType = SnmpDataType.Integer;
}
protected override void GenerateTestMethodCodeCore(CodeContainerBase container, string localValueVarName, ref bool localValueVarUsed, string lenVarName, ref bool lenVarUsed, string retErrVarName)
{
System.Diagnostics.Trace.Assert(this.Restrictions.Count > 0);
StringBuilder ifCond = new StringBuilder();
foreach (IRestriction restriction in this.Restrictions)
{
ifCond.Append(restriction.GetCheckCodeValid("*" + localValueVarName));
ifCond.Append(" || ");
localValueVarUsed = true;
}
ifCond.Length -= 4;
IfThenElse ite = new IfThenElse(ifCond.ToString());
ite.AddCode(String.Format("{0} = {1};", retErrVarName, LwipDefs.Def_ErrorCode_Ok));
container.AddElement(ite);
}
protected override bool GenerateValueDeclaration(CodeContainerBase container, string variableName, string sourceName)
{
container.AddDeclaration(new VariableDeclaration(
new VariableType(variableName, LwipDefs.Vt_S32, "*"),
"(" + new VariableType(null, LwipDefs.Vt_S32, "*") + ")" + sourceName));
return true;
}
public override string FixedValueLength
{
get { return String.Format("sizeof({0})", LwipDefs.Vt_S32); }
}
public override int OidRepresentationLen
{
get { return 1; }
}
}
}

View File

@ -0,0 +1,90 @@
/*
* Copyright (c) 2001-2004 Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
*
* This file is part of the lwIP TCP/IP stack.
*
* Author: Martin Hentschel <info@cl-soft.de>
*
*/
using System;
using CCodeGeneration;
namespace LwipSnmpCodeGeneration
{
public class SnmpScalarNodeObjectIdentifier: SnmpScalarNode
{
public SnmpScalarNodeObjectIdentifier(SnmpTreeNode parentNode)
: base(parentNode)
{
this.DataType = SnmpDataType.ObjectIdentifier;
}
protected override bool GenerateValueDeclaration(CodeContainerBase container, string variableName, string sourceName)
{
container.AddDeclaration(new VariableDeclaration(
new VariableType(variableName, LwipDefs.Vt_U32, "*"),
"(" + new VariableType(null, LwipDefs.Vt_U32, "*") + ")" + sourceName));
return true;
}
protected override void GenerateGetMethodCodeCore(CodeContainerBase container, string localValueVarName, ref bool localValueVarUsed, string retLenVarName)
{
container.AddElement(new Comment(String.Format("TODO: put requested value to '*{0}' here. '{0}' has to be interpreted as {1}[]", localValueVarName, LwipDefs.Vt_U32), singleLine: true));
container.AddElement(EmptyLine.SingleLine);
container.AddCode(String.Format("{0} = 0; // TODO: return real value length here (should be 'numOfElements * sizeof({1})')", retLenVarName, LwipDefs.Vt_U32));
}
protected override void GenerateTestMethodCodeCore(CodeContainerBase container, string localValueVarName, ref bool localValueVarUsed, string lenVarName, ref bool lenVarUsed, string retErrVarName)
{
VariableDeclaration objIdLenVar = new VariableDeclaration(
new VariableType(localValueVarName + "_len", LwipDefs.Vt_U8),
String.Format("{0} / sizeof({1})", lenVarName, LwipDefs.Vt_U32));
lenVarUsed = true;
container.Declarations.Add(objIdLenVar);
base.GenerateTestMethodCodeCore(container, localValueVarName, ref localValueVarUsed, lenVarName, ref lenVarUsed, retErrVarName);
container.AddCode(String.Format("LWIP_UNUSED_ARG({0});", objIdLenVar.Type.Name));
}
protected override void GenerateSetMethodCodeCore(CodeContainerBase container, string localValueVarName, ref bool localValueVarUsed, string lenVarName, ref bool lenVarUsed, string retErrVarName)
{
VariableDeclaration objIdLenVar = new VariableDeclaration(
new VariableType(localValueVarName + "_len", LwipDefs.Vt_U8),
String.Format("{0} / sizeof({1})", lenVarName, LwipDefs.Vt_U32));
lenVarUsed = true;
container.Declarations.Add(objIdLenVar);
base.GenerateSetMethodCodeCore(container, localValueVarName, ref localValueVarUsed, lenVarName, ref lenVarUsed, retErrVarName);
container.AddCode(String.Format("LWIP_UNUSED_ARG({0});", objIdLenVar.Type.Name));
}
}
}

View File

@ -0,0 +1,118 @@
/*
* Copyright (c) 2001-2004 Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
*
* This file is part of the lwIP TCP/IP stack.
*
* Author: Martin Hentschel <info@cl-soft.de>
*
*/
using System;
using System.Text;
using CCodeGeneration;
namespace LwipSnmpCodeGeneration
{
public class SnmpScalarNodeOctetString : SnmpScalarNode
{
public SnmpScalarNodeOctetString(SnmpDataType dataType, SnmpTreeNode parentNode)
: base(parentNode)
{
System.Diagnostics.Debug.Assert(
(dataType == SnmpDataType.OctetString) ||
(dataType == SnmpDataType.Opaque) ||
(dataType == SnmpDataType.IpAddress));
this.DataType = dataType;
}
protected override void GenerateGetMethodCodeCore(CodeContainerBase container, string localValueVarName, ref bool localValueVarUsed, string retLenVarName)
{
if (this.Restrictions.Count > 0)
{
StringBuilder ifCond = new StringBuilder();
foreach (IRestriction restriction in this.Restrictions)
{
ifCond.Append(restriction.GetCheckCodeValid(retLenVarName));
ifCond.Append(" || ");
}
ifCond.Length -= 4;
container.AddElement(new Comment("TODO: take care of len restrictions defined in MIB: " + ifCond, singleLine: true));
}
base.GenerateGetMethodCodeCore(container, localValueVarName, ref localValueVarUsed, retLenVarName);
}
protected override void GenerateTestMethodCodeCore(CodeContainerBase container, string localValueVarName, ref bool localValueVarUsed, string lenVarName, ref bool lenVarUsed, string retErrVarName)
{
System.Diagnostics.Trace.Assert(this.Restrictions.Count > 0);
// checks refer to length of octet string
StringBuilder ifCond = new StringBuilder();
foreach (IRestriction restriction in this.Restrictions)
{
ifCond.Append(restriction.GetCheckCodeValid(lenVarName));
ifCond.Append(" || ");
lenVarUsed = true;
}
ifCond.Length -= 4;
IfThenElse ite = new IfThenElse(ifCond.ToString());
ite.AddCode(String.Format("{0} = {1};", retErrVarName, LwipDefs.Def_ErrorCode_Ok));
container.AddElement(ite);
}
public override int OidRepresentationLen
{
get
{
// check restrictions if we are set to one fixed length
if ((this.Restrictions != null) && (this.Restrictions.Count > 0))
{
foreach (IRestriction restriction in this.Restrictions)
{
if (restriction is IsInRangeRestriction)
{
if ((restriction as IsInRangeRestriction).RangeStart == (restriction as IsInRangeRestriction).RangeEnd)
{
return (int)(restriction as IsInRangeRestriction).RangeStart;
}
}
else if (restriction is IsEqualRestriction)
{
return (int)(restriction as IsEqualRestriction).Value;
}
}
}
return -1; // variable length
}
}
}
}

View File

@ -0,0 +1,66 @@
/*
* Copyright (c) 2001-2004 Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
*
* This file is part of the lwIP TCP/IP stack.
*
* Author: Martin Hentschel <info@cl-soft.de>
*
*/
using System;
using CCodeGeneration;
namespace LwipSnmpCodeGeneration
{
public class SnmpScalarNodeTruthValue : SnmpScalarNodeInt
{
public SnmpScalarNodeTruthValue(SnmpTreeNode parentNode)
: base(parentNode)
{
}
protected override void GenerateGetMethodCodeCore(CodeContainerBase container, string localValueVarName, ref bool localValueVarUsed, string retLenVarName)
{
container.AddCodeFormat("snmp_encode_truthvalue({0}, /* TODO: put requested bool value here */ 0);", localValueVarName);
localValueVarUsed = true;
container.AddCode(String.Format("{0} = {1};",
retLenVarName,
(!String.IsNullOrWhiteSpace(this.FixedValueLength)) ? this.FixedValueLength : "0"));
}
protected override void GenerateSetMethodCodeCore(CodeContainerBase container, string localValueVarName, ref bool localValueVarUsed, string lenVarName, ref bool lenVarUsed, string retErrVarName)
{
VariableType truthVar = new VariableType("bool_value", LwipDefs.Vt_U8);
container.Declarations.Add(new VariableDeclaration(truthVar));
container.AddCodeFormat("snmp_decode_truthvalue({0}, &{1});", localValueVarName, truthVar.Name);
localValueVarUsed = true;
container.AddElement(new Comment(String.Format("TODO: store new value contained in '{0}' here", truthVar.Name), singleLine: true));
}
}
}

View File

@ -0,0 +1,91 @@
/*
* Copyright (c) 2001-2004 Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
*
* This file is part of the lwIP TCP/IP stack.
*
* Author: Martin Hentschel <info@cl-soft.de>
*
*/
using System;
using System.Text;
using CCodeGeneration;
namespace LwipSnmpCodeGeneration
{
public class SnmpScalarNodeUint : SnmpScalarNode
{
public SnmpScalarNodeUint(SnmpDataType dataType, SnmpTreeNode parentNode)
: base(parentNode)
{
System.Diagnostics.Debug.Assert(
(dataType == SnmpDataType.Counter) ||
(dataType == SnmpDataType.Gauge) ||
(dataType == SnmpDataType.TimeTicks));
this.DataType = dataType;
}
protected override void GenerateTestMethodCodeCore(CodeContainerBase container, string localValueVarName, ref bool localValueVarUsed, string lenVarName, ref bool lenVarUsed, string retErrVarName)
{
System.Diagnostics.Trace.Assert(this.Restrictions.Count > 0);
StringBuilder ifCond = new StringBuilder();
foreach (IRestriction restriction in this.Restrictions)
{
ifCond.Append(restriction.GetCheckCodeValid("*" + localValueVarName));
ifCond.Append(" || ");
localValueVarUsed = true;
}
ifCond.Length -= 4;
IfThenElse ite = new IfThenElse(ifCond.ToString());
ite.AddCode(String.Format("{0} = {1};", retErrVarName, LwipDefs.Def_ErrorCode_Ok));
container.AddElement(ite);
}
protected override bool GenerateValueDeclaration(CodeContainerBase container, string variableName, string sourceName)
{
container.AddDeclaration(new VariableDeclaration(
new VariableType(variableName, LwipDefs.Vt_U32, "*"),
"(" + new VariableType(null, LwipDefs.Vt_U32, "*") + ")" + sourceName));
return true;
}
public override string FixedValueLength
{
get { return String.Format("sizeof({0})", LwipDefs.Vt_U32); }
}
public override int OidRepresentationLen
{
get { return 1; }
}
}
}

View File

@ -0,0 +1,332 @@
/*
* Copyright (c) 2001-2004 Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
*
* This file is part of the lwIP TCP/IP stack.
*
* Author: Martin Hentschel <info@cl-soft.de>
*
*/
using System;
using System.Collections.Generic;
using System.Text;
using CCodeGeneration;
namespace LwipSnmpCodeGeneration
{
public class SnmpTableNode: SnmpScalarAggregationNode
{
private readonly List<SnmpScalarNode> cellNodes = new List<SnmpScalarNode>();
private readonly List<SnmpScalarNode> indexNodes = new List<SnmpScalarNode>();
private string augmentedTableRow = null;
public SnmpTableNode(SnmpTreeNode parentNode)
: base(parentNode)
{
}
public List<SnmpScalarNode> CellNodes
{
get { return cellNodes; }
}
public List<SnmpScalarNode> IndexNodes
{
get { return indexNodes; }
}
public string AugmentedTableRow
{
get { return this.augmentedTableRow; }
set { this.augmentedTableRow = value; }
}
public override string FullNodeName
{
get
{
string result = this.Name.ToLowerInvariant();
if (!result.Contains("table"))
{
result += "_table";
}
return result;
}
}
protected override IEnumerable<SnmpScalarNode> AggregatedScalarNodes
{
get { return this.cellNodes; }
}
public override void GenerateCode(MibCFile mibFile)
{
FunctionDeclaration getInstanceMethodDecl = new FunctionDeclaration(this.FullNodeName + LwipDefs.FnctSuffix_GetInstance, isStatic: true);
getInstanceMethodDecl.Parameter.Add(new VariableType("column", LwipDefs.Vt_U32, "*", ConstType.Value));
getInstanceMethodDecl.Parameter.Add(new VariableType("row_oid", LwipDefs.Vt_U32, "*", ConstType.Value));
getInstanceMethodDecl.Parameter.Add(new VariableType("row_oid_len", LwipDefs.Vt_U8, ""));
getInstanceMethodDecl.Parameter.Add(new VariableType("cell_instance", LwipDefs.Vt_StNodeInstance, "*"));
getInstanceMethodDecl.ReturnType = new VariableType(null, LwipDefs.Vt_Snmp_err);
mibFile.Declarations.Add(getInstanceMethodDecl);
Function getInstanceMethod = Function.FromDeclaration(getInstanceMethodDecl);
GenerateGetInstanceMethodCode(getInstanceMethod);
mibFile.Implementation.Add(getInstanceMethod);
FunctionDeclaration getNextInstanceMethodDecl = new FunctionDeclaration(this.FullNodeName + LwipDefs.FnctSuffix_GetNextInstance, isStatic: true);
getNextInstanceMethodDecl.Parameter.Add(new VariableType("column", LwipDefs.Vt_U32, "*", ConstType.Value));
getNextInstanceMethodDecl.Parameter.Add(new VariableType("row_oid", LwipDefs.Vt_StObjectId, "*"));
getNextInstanceMethodDecl.Parameter.Add(new VariableType("cell_instance", LwipDefs.Vt_StNodeInstance, "*"));
getNextInstanceMethodDecl.ReturnType = new VariableType(null, LwipDefs.Vt_Snmp_err);
mibFile.Declarations.Add(getNextInstanceMethodDecl);
Function getNextInstanceMethod = Function.FromDeclaration(getNextInstanceMethodDecl);
GenerateGetNextInstanceMethodCode(getNextInstanceMethod);
mibFile.Implementation.Add(getNextInstanceMethod);
VariableType instanceType = new VariableType("cell_instance", LwipDefs.Vt_StNodeInstance, "*");
GenerateAggregatedCode(
mibFile,
instanceType,
String.Format("SNMP_TABLE_GET_COLUMN_FROM_OID({0}->instance_oid.id)", instanceType.Name));
#region create and add column/table definitions
StringBuilder colDefs = new StringBuilder();
foreach (SnmpScalarNode colNode in this.cellNodes)
{
colDefs.AppendFormat(" {{{0}, {1}, {2}}}, /* {3} */ \n",
colNode.Oid,
LwipDefs.GetAsn1DefForSnmpDataType(colNode.DataType),
LwipDefs.GetLwipDefForSnmpAccessMode(colNode.AccessMode),
colNode.Name);
}
if (colDefs.Length > 0)
{
colDefs.Length--;
}
VariableDeclaration colDefsDecl = new VariableDeclaration(
new VariableType(this.FullNodeName + "_columns", LwipDefs.Vt_StTableColumnDef, null, ConstType.Value, String.Empty),
"{\n" + colDefs + "\n}",
isStatic: true);
mibFile.Declarations.Add(colDefsDecl);
string nodeInitialization = String.Format("SNMP_TABLE_CREATE({0}, {1}, {2}, {3}, {4}, {5}, {6})",
this.Oid,
colDefsDecl.Type.Name,
getInstanceMethodDecl.Name, getNextInstanceMethodDecl.Name,
(this.GetMethodRequired) ? this.GetMethodName : LwipDefs.Null,
(this.TestMethodRequired) ? this.TestMethodName : LwipDefs.Null,
(this.SetMethodRequired) ? this.SetMethodName : LwipDefs.Null
);
mibFile.Declarations.Add(new VariableDeclaration(
new VariableType(this.FullNodeName, LwipDefs.Vt_StTableNode, null, ConstType.Value),
nodeInitialization,
isStatic: true));
#endregion
}
protected virtual void GenerateGetInstanceMethodCode(Function getInstanceMethod)
{
VariableDeclaration returnValue = new VariableDeclaration((VariableType)getInstanceMethod.ReturnType.Clone(), LwipDefs.Def_ErrorCode_NoSuchInstance);
returnValue.Type.Name = "err";
getInstanceMethod.Declarations.Add(returnValue);
int instanceOidLength = 0;
StringBuilder indexColumns = new StringBuilder();
foreach (SnmpScalarNode indexNode in this.indexNodes)
{
if (instanceOidLength >= 0)
{
if (indexNode.OidRepresentationLen >= 0)
{
instanceOidLength += indexNode.OidRepresentationLen;
}
else
{
// at least one index column has a variable length -> we cannot perform a static check
instanceOidLength = -1;
}
}
indexColumns.AppendFormat(
" {0} ({1}, OID length = {2})\n",
indexNode.Name,
indexNode.DataType,
(indexNode.OidRepresentationLen >= 0) ? indexNode.OidRepresentationLen.ToString() : "variable");
}
if (indexColumns.Length > 0)
{
indexColumns.Length--;
getInstanceMethod.Declarations.Insert(0, new Comment(String.Format(
"The instance OID of this table consists of following (index) column(s):\n{0}",
indexColumns)));
}
string augmentsHint = "";
if (!String.IsNullOrWhiteSpace(this.augmentedTableRow))
{
augmentsHint = String.Format(
"This table augments table '{0}'! Index columns therefore belong to table '{0}'!\n" +
"You may simply call the '*{1}' method of this table.\n\n",
(this.augmentedTableRow.ToLowerInvariant().EndsWith("entry")) ? this.augmentedTableRow.Substring(0, this.augmentedTableRow.Length-5) : this.augmentedTableRow,
LwipDefs.FnctSuffix_GetInstance);
}
CodeContainerBase ccb = getInstanceMethod;
if (instanceOidLength > 0)
{
IfThenElse ite = new IfThenElse(String.Format("{0} == {1}", getInstanceMethod.Parameter[2].Name, instanceOidLength));
getInstanceMethod.AddElement(ite);
ccb = ite;
}
ccb.AddCodeFormat("LWIP_UNUSED_ARG({0});", getInstanceMethod.Parameter[0].Name);
ccb.AddCodeFormat("LWIP_UNUSED_ARG({0});", getInstanceMethod.Parameter[1].Name);
if (instanceOidLength <= 0)
{
ccb.AddCodeFormat("LWIP_UNUSED_ARG({0});", getInstanceMethod.Parameter[2].Name);
}
ccb.AddCodeFormat("LWIP_UNUSED_ARG({0});", getInstanceMethod.Parameter[3].Name);
ccb.AddElement(new Comment(String.Format(
"TODO: check if '{0}'/'{1}' params contain a valid instance oid for a row\n" +
"If so, set '{2} = {3};'\n\n" +
"snmp_oid_* methods may be used for easier processing of oid\n\n" +
"{4}" +
"In order to avoid decoding OID a second time in subsequent get_value/set_test/set_value methods,\n" +
"you may store an arbitrary value (like a pointer to target value object) in '{5}->reference'/'{5}->reference_len'.\n" +
"But be aware that not always a subsequent method is called -> Do NOT allocate memory here and try to release it in subsequent methods!\n\n" +
"You also may replace function pointers in '{5}' param for get/test/set methods which contain the default values from table definition,\n" +
"in order to provide special methods, for the currently processed cell. Changed pointers are only valid for current request.",
getInstanceMethod.Parameter[1].Name,
getInstanceMethod.Parameter[2].Name,
returnValue.Type.Name,
LwipDefs.Def_ErrorCode_Ok,
augmentsHint,
getInstanceMethod.Parameter[3].Name
)));
getInstanceMethod.AddCodeFormat("return {0};", returnValue.Type.Name);
}
protected virtual void GenerateGetNextInstanceMethodCode(Function getNextInstanceMethod)
{
getNextInstanceMethod.AddCodeFormat("LWIP_UNUSED_ARG({0});", getNextInstanceMethod.Parameter[0].Name);
getNextInstanceMethod.AddCodeFormat("LWIP_UNUSED_ARG({0});", getNextInstanceMethod.Parameter[1].Name);
getNextInstanceMethod.AddCodeFormat("LWIP_UNUSED_ARG({0});", getNextInstanceMethod.Parameter[2].Name);
VariableDeclaration returnValue = new VariableDeclaration((VariableType)getNextInstanceMethod.ReturnType.Clone(), LwipDefs.Def_ErrorCode_NoSuchInstance);
returnValue.Type.Name = "err";
getNextInstanceMethod.Declarations.Add(returnValue);
StringBuilder indexColumns = new StringBuilder();
foreach (SnmpScalarNode indexNode in this.indexNodes)
{
indexColumns.AppendFormat(
" {0} ({1}, OID length = {2})\n",
indexNode.Name,
indexNode.DataType,
(indexNode.OidRepresentationLen >= 0) ? indexNode.OidRepresentationLen.ToString() : "variable");
}
if (indexColumns.Length > 0)
{
indexColumns.Length--;
getNextInstanceMethod.Declarations.Insert(0, new Comment(String.Format(
"The instance OID of this table consists of following (index) column(s):\n{0}",
indexColumns)));
}
string augmentsHint = "";
if (!String.IsNullOrWhiteSpace(this.augmentedTableRow))
{
augmentsHint = String.Format(
"This table augments table '{0}'! Index columns therefore belong to table '{0}'!\n" +
"You may simply call the '*{1}' method of this table.\n\n",
(this.augmentedTableRow.ToLowerInvariant().EndsWith("entry")) ? this.augmentedTableRow.Substring(0, this.augmentedTableRow.Length-5) : this.augmentedTableRow,
LwipDefs.FnctSuffix_GetNextInstance);
}
getNextInstanceMethod.AddElement(new Comment(String.Format(
"TODO: analyze '{0}->id'/'{0}->len' and return the subsequent row instance\n" +
"Be aware that '{0}->id'/'{0}->len' must not point to a valid instance or have correct instance length.\n" +
"If '{0}->len' is 0, return the first instance. If '{0}->len' is longer than expected, cut superfluous OID parts.\n" +
"If a valid next instance is found, store it in '{0}->id'/'{0}->len' and set '{1} = {2};'\n\n" +
"snmp_oid_* methods may be used for easier processing of oid\n\n" +
"{3}" +
"In order to avoid decoding OID a second time in subsequent get_value/set_test/set_value methods,\n" +
"you may store an arbitrary value (like a pointer to target value object) in '{4}->reference'/'{4}->reference_len'.\n" +
"But be aware that not always a subsequent method is called -> Do NOT allocate memory here and try to release it in subsequent methods!\n\n" +
"You also may replace function pointers in '{4}' param for get/test/set methods which contain the default values from table definition,\n" +
"in order to provide special methods, for the currently processed cell. Changed pointers are only valid for current request.",
getNextInstanceMethod.Parameter[1].Name,
returnValue.Type.Name,
LwipDefs.Def_ErrorCode_Ok,
augmentsHint,
getNextInstanceMethod.Parameter[2].Name
)));
getNextInstanceMethod.AddElement(new Comment(String.Format(
"For easier processing and getting the next instance, you may use the 'snmp_next_oid_*' enumerator.\n" +
"Simply pass all known instance OID's to it and it returns the next valid one:\n\n" +
"{0} state;\n" +
"{1} result_buf;\n" +
"snmp_next_oid_init(&state, {2}->id, {2}->len, result_buf, LWIP_SNMP_OBJ_ID_LEN);\n" +
"while ({{not all instances passed}}) {{\n" +
" {1} test_oid;\n" +
" {{fill test_oid to create instance oid for next instance}}\n" +
" snmp_next_oid_check(&state, test_oid->id, test_oid->len, {{target_data_ptr}});\n" +
"}}\n" +
"if(state.status == SNMP_NEXT_OID_STATUS_SUCCESS) {{\n" +
" snmp_oid_assign(row_oid, result_buf->oid, result_buf->len);\n" +
" {3}->reference.ptr = state.reference; //==target_data_ptr, for usage in subsequent get/test/set\n" +
" {4} = {5};\n" +
"}}"
,
LwipDefs.Vt_StNextOidState,
LwipDefs.Vt_StObjectId,
getNextInstanceMethod.Parameter[1].Name,
getNextInstanceMethod.Parameter[2].Name,
returnValue.Type.Name,
LwipDefs.Def_ErrorCode_Ok
)));
getNextInstanceMethod.AddCodeFormat("return {0};", returnValue.Type.Name);
}
}
}

View File

@ -0,0 +1,241 @@
/*
* Copyright (c) 2001-2004 Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
*
* This file is part of the lwIP TCP/IP stack.
*
* Author: Martin Hentschel <info@cl-soft.de>
*
*/
using System;
using System.Collections.Generic;
using System.Text;
using CCodeGeneration;
namespace LwipSnmpCodeGeneration
{
public class SnmpTreeNode: SnmpScalarAggregationNode
{
private readonly List<SnmpNode> childNodes = new List<SnmpNode>();
private readonly List<SnmpScalarNode> childScalarNodes = new List<SnmpScalarNode>();
private string fullOid = "";
public SnmpTreeNode(SnmpTreeNode parentNode)
: base(parentNode)
{
}
public override string FullNodeName
{
get { return this.Name + "_treenode"; }
}
public string FullOid
{
get { return this.fullOid; }
set { this.fullOid = value; }
}
public List<SnmpNode> ChildNodes
{
get { return this.childNodes; }
}
protected override IEnumerable<SnmpScalarNode> AggregatedScalarNodes
{
get { return this.childScalarNodes; }
}
private void GenerateAggregatedCode(MibCFile mibFile, bool generateDeclarations, bool generateImplementations)
{
VariableType instanceType = new VariableType("instance", LwipDefs.Vt_StNodeInstance, "*");
base.GenerateAggregatedCode(
mibFile,
instanceType,
String.Format("{0}->node->oid", instanceType.Name),
generateDeclarations,
generateImplementations);
}
private void GenerateAggregateMethodDeclarations(MibCFile mibFile)
{
if (LwipOpts.GenerateSingleAccessMethodsForTreeNodeScalars && (this.childScalarNodes.Count > 1))
{
GenerateAggregatedCode(mibFile, true, false);
}
}
public override void GenerateCode(MibCFile mibFile)
{
string nodeInitialization;
if (LwipOpts.GenerateSingleAccessMethodsForTreeNodeScalars && (this.childScalarNodes.Count > 1))
{
GenerateAggregatedCode(mibFile, false, true);
}
// create and add node declaration
if (this.childNodes.Count > 0)
{
StringBuilder subnodeArrayInitialization = new StringBuilder();
for (int i=0; i<this.childNodes.Count; i++)
{
subnodeArrayInitialization.Append(" &");
subnodeArrayInitialization.Append(this.childNodes[i].FullNodeName);
subnodeArrayInitialization.Append(".node");
if (!(this.childNodes[i] is SnmpTreeNode))
{
subnodeArrayInitialization.Append(".node");
}
if (i < (this.childNodes.Count - 1))
{
subnodeArrayInitialization.Append(",\n");
}
}
VariableDeclaration subnodeArray = new VariableDeclaration(
new VariableType(this.Name + "_subnodes", LwipDefs.Vt_StNode, "*", ConstType.Value, String.Empty),
"{\n" + subnodeArrayInitialization + "\n}",
isStatic: true);
mibFile.Declarations.Add(subnodeArray);
nodeInitialization = String.Format("SNMP_CREATE_TREE_NODE({0}, {1})", this.Oid, subnodeArray.Type.Name);
}
else
{
nodeInitialization = String.Format("SNMP_CREATE_EMPTY_TREE_NODE({0})", this.Oid);
}
mibFile.Declarations.Add(new VariableDeclaration(
new VariableType(this.FullNodeName, LwipDefs.Vt_StTreeNode, null, ConstType.Value),
nodeInitialization,
isStatic: true));
}
public override void Analyze()
{
this.childScalarNodes.Clear();
// delegate analyze (don't use enumerator because the child node may change our child collection by e.g. removing or replacing itself)
for (int i=this.ChildNodes.Count-1; i>=0; i--)
{
this.ChildNodes[i].Analyze();
}
// collect scalar nodes
foreach (SnmpNode childNode in this.childNodes)
{
SnmpScalarNode scalarNode = childNode as SnmpScalarNode;
if (scalarNode != null)
{
this.childScalarNodes.Add(scalarNode);
}
}
base.Analyze();
// check if we can merge this node to a scalar array node (all childs need to be scalars)
if (this.childNodes.Count > 0)
{
if (LwipOpts.GenerateScalarArrays && (this.childScalarNodes.Count == this.childNodes.Count))
{
SnmpScalarArrayNode scalarArrayNode = new SnmpScalarArrayNode(this.childScalarNodes, this.ParentNode);
scalarArrayNode.Oid = this.Oid;
scalarArrayNode.Name = this.Name;
for (int i=0; i<this.ParentNode.ChildNodes.Count; i++)
{
if (this.ParentNode.ChildNodes[i] == this)
{
this.ParentNode.ChildNodes.RemoveAt(i);
this.ParentNode.ChildNodes.Insert(i, scalarArrayNode);
break;
}
}
}
else if (LwipOpts.GenerateSingleAccessMethodsForTreeNodeScalars && (this.childScalarNodes.Count > 1))
{
foreach (SnmpScalarNode scalarNode in this.childScalarNodes)
{
scalarNode.UseExternalMethods = true;
scalarNode.ExternalGetMethod = this.GetMethodName;
scalarNode.ExternalTestMethod = this.TestMethodName;
scalarNode.ExternalSetMethod = this.SetMethodName;
}
}
}
else // if (this.childNodes.Count == 0)
{
if (!LwipOpts.GenerateEmptyFolders && (this.ParentNode != null))
{
// do not generate this empty folder because it only waste (static) memory
for (int i=0; i<this.ParentNode.ChildNodes.Count; i++)
{
if (this.ParentNode.ChildNodes[i] == this)
{
this.ParentNode.ChildNodes.RemoveAt(i);
break;
}
}
}
}
}
public override void Generate(MibCFile generatedFile, MibHeaderFile generatedHeaderFile)
{
// generate code of child nodes
foreach (SnmpNode childNode in this.childNodes)
{
if (childNode is SnmpTreeNode)
{
childNode.Generate(generatedFile, generatedHeaderFile);
}
}
Comment dividerComment = new Comment(
String.Format("--- {0} {1} -----------------------------------------------------", this.Name, this.fullOid),
singleLine: true);
generatedFile.Declarations.Add(dividerComment);
generatedFile.Implementation.Add(dividerComment);
this.GenerateAggregateMethodDeclarations(generatedFile);
foreach (SnmpNode childNode in this.childNodes)
{
if (!(childNode is SnmpTreeNode))
{
childNode.Generate(generatedFile, generatedHeaderFile);
}
}
base.Generate(generatedFile, generatedHeaderFile);
}
}
}

View File

@ -0,0 +1,84 @@
using System;
using System.Collections.Generic;
using System.Collections;
namespace Lextm.SharpSnmpLib.Mib
{
public class DisplayHint
{
private enum NumType {
dec,
hex,
oct,
bin,
str
}
private string _str;
private NumType _type;
private int _decimalPoints = 0;
public DisplayHint(string str)
{
_str = str;
if (str.StartsWith("d"))
{
_type = NumType.dec;
if (str.StartsWith("d-"))
{
_decimalPoints = Convert.ToInt32(str.Substring(2));
}
}
else if (str.StartsWith("o"))
{
_type = NumType.oct;
}
else if (str.StartsWith("h"))
{
_type = NumType.hex;
}
else if (str.StartsWith("b"))
{
_type = NumType.bin;
}
else
{
_type = NumType.str;
foreach (char c in str)
{
}
}
}
public override string ToString()
{
return _str;
}
internal object Decode(int i)
{
switch (_type)
{
case NumType.dec:
if (_decimalPoints == 0)
{
return i;
}
else
{
return i / Math.Pow(10.0, _decimalPoints);
}
case NumType.hex:
return System.Convert.ToString(i, 16);
case NumType.oct:
return System.Convert.ToString(i, 8);
case NumType.bin:
return System.Convert.ToString(i, 2);
default:
return null;
}
}
}
}

View File

@ -0,0 +1,29 @@
/*
* Created by SharpDevelop.
* User: lextm
* Date: 2008/5/31
* Time: 13:18
*
* To change this template use Tools | Options | Coding | Edit Standard Headers.
*/
namespace Lextm.SharpSnmpLib.Mib.Elements.Entities
{
/// <summary>
/// The AGENT-CAPABILITIES construct is used to specify implementation characteristics of an SNMP agent sub-system with respect to object types and events.
/// </summary>
public sealed class AgentCapabilities : EntityBase
{
/// <summary>
/// Creates an <see cref="AgentCapabilities"/> instance.
/// </summary>
/// <param name="module"></param>
/// <param name="header"></param>
/// <param name="lexer"></param>
public AgentCapabilities(IModule module, SymbolList preAssignSymbols, ISymbolEnumerator symbols)
: base(module, preAssignSymbols, symbols)
{
}
}
}

View File

@ -0,0 +1,46 @@
using System;
namespace Lextm.SharpSnmpLib.Mib.Elements.Entities
{
public abstract class EntityBase: IEntity
{
private readonly IModule _module;
private string _parent;
private readonly uint _value;
private readonly string _name;
public EntityBase(IModule module, SymbolList preAssignSymbols, ISymbolEnumerator symbols)
{
_module = module;
_name = preAssignSymbols[0].ToString();
Lexer.ParseOidValue(symbols, out _parent, out _value);
}
public IModule Module
{
get { return _module; }
}
public string Parent
{
get { return _parent; }
set { _parent = value; }
}
public uint Value
{
get { return _value; }
}
public string Name
{
get { return _name; }
}
public virtual string Description
{
get { return string.Empty; }
}
}
}

View File

@ -0,0 +1,62 @@
// Entity interface.
// Copyright (C) 2008-2010 Malcolm Crowe, Lex Li, and other contributors.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
/*
* Created by SharpDevelop.
* User: lextm
* Date: 2008/5/19
* Time: 20:10
*
* To change this template use Tools | Options | Coding | Edit Standard Headers.
*/
using System;
namespace Lextm.SharpSnmpLib.Mib.Elements.Entities
{
/// <summary>
/// Basic interface for all elements building up the MIB tree, thus having an OID as value.
/// </summary>
public interface IEntity : IDeclaration
{
/// <summary>
/// Parent name.
/// </summary>
string Parent
{
get;
set;
}
/// <summary>
/// Value.
/// </summary>
uint Value
{
get;
}
/// <summary>
/// Gets the description.
/// </summary>
/// <value>The description.</value>
string Description
{
get;
}
}
}

View File

@ -0,0 +1,23 @@
/*
* Created by SharpDevelop.
* User: lextm
* Date: 2008/5/21
* Time: 19:35
*
* To change this template use Tools | Options | Coding | Edit Standard Headers.
*/
namespace Lextm.SharpSnmpLib.Mib.Elements.Entities
{
/// <summary>
/// Description of ModuleComplianceNode.
/// </summary>
public sealed class ModuleCompliance : EntityBase
{
public ModuleCompliance(IModule module, SymbolList preAssignSymbols, ISymbolEnumerator symbols)
: base(module, preAssignSymbols, symbols)
{
}
}
}

View File

@ -0,0 +1,10 @@
namespace Lextm.SharpSnmpLib.Mib.Elements.Entities
{
public sealed class ModuleIdentity : EntityBase
{
public ModuleIdentity(IModule module, SymbolList preAssignSymbols, ISymbolEnumerator symbols)
: base(module, preAssignSymbols, symbols)
{
}
}
}

View File

@ -0,0 +1,22 @@
/*
* Created by SharpDevelop.
* User: lextm
* Date: 2008/5/21
* Time: 19:34
*
* To change this template use Tools | Options | Coding | Edit Standard Headers.
*/
namespace Lextm.SharpSnmpLib.Mib.Elements.Entities
{
/// <summary>
/// Description of NotificationGroupNode.
/// </summary>
public sealed class NotificationGroup : EntityBase
{
public NotificationGroup(IModule module, SymbolList preAssignSymbols, ISymbolEnumerator symbols)
: base(module, preAssignSymbols, symbols)
{
}
}
}

View File

@ -0,0 +1,11 @@
namespace Lextm.SharpSnmpLib.Mib.Elements.Entities
{
public sealed class NotificationType : EntityBase
{
public NotificationType(IModule module, SymbolList preAssignSymbols, ISymbolEnumerator symbols)
: base(module, preAssignSymbols, symbols)
{
}
}
}

View File

@ -0,0 +1,22 @@
/*
* Created by SharpDevelop.
* User: lextm
* Date: 2008/5/21
* Time: 19:27
*
* To change this template use Tools | Options | Coding | Edit Standard Headers.
*/
namespace Lextm.SharpSnmpLib.Mib.Elements.Entities
{
/// <summary>
/// Description of ObjectGroupNode.
/// </summary>
public sealed class ObjectGroup : EntityBase
{
public ObjectGroup(IModule module, SymbolList preAssignSymbols, ISymbolEnumerator symbols)
: base(module, preAssignSymbols, symbols)
{
}
}
}

View File

@ -0,0 +1,21 @@
namespace Lextm.SharpSnmpLib.Mib.Elements.Entities
{
/// <summary>
/// Object identifier node.
/// </summary>
public sealed class ObjectIdentity : EntityBase
{
/// <summary>
/// Creates a <see cref="ObjectIdentity"/>.
/// </summary>
/// <param name="module">Module name</param>
/// <param name="header">Header</param>
/// <param name="lexer">Lexer</param>
public ObjectIdentity(IModule module, SymbolList preAssignSymbols, ISymbolEnumerator symbols)
: base(module, preAssignSymbols, symbols)
{
}
}
}

View File

@ -0,0 +1,336 @@
using System;
using System.Collections.Generic;
using Lextm.SharpSnmpLib.Mib.Elements.Types;
namespace Lextm.SharpSnmpLib.Mib.Elements.Entities
{
public sealed class ObjectType : EntityBase, ITypeReferrer
{
private ITypeAssignment _syntax;
private string _units;
private MaxAccess _access;
private Status _status;
private string _description;
private string _reference;
private IList<string> _indices;
private string _augments;
private string _defVal;
public ObjectType(IModule module, SymbolList preAssignSymbols, ISymbolEnumerator symbols)
: base(module, preAssignSymbols, symbols)
{
ParseProperties(preAssignSymbols);
}
private void ParseProperties(SymbolList header)
{
ISymbolEnumerator headerSymbols = header.GetSymbolEnumerator();
Symbol temp = headerSymbols.NextNonEOLSymbol();
// Skip name
temp = headerSymbols.NextNonEOLSymbol();
temp.Expect(Symbol.ObjectType);
_syntax = ParseSyntax (Module, headerSymbols);
_units = ParseUnits (headerSymbols);
_access = ParseAccess (headerSymbols);
_status = ParseStatus (headerSymbols);
_description = ParseDescription (headerSymbols);
_reference = ParseReference (headerSymbols);
_indices = ParseIndices (headerSymbols);
_augments = ParseAugments (headerSymbols);
_defVal = ParseDefVal (headerSymbols);
}
private static string ParseAugments(ISymbolEnumerator symbols)
{
Symbol current = symbols.NextNonEOLSymbol();
if (current == Symbol.Augments)
{
string augment = null;
current = symbols.NextNonEOLSymbol();
current.Expect(Symbol.OpenBracket);
current = symbols.NextNonEOLSymbol();
augment = current.ToString();
current = symbols.NextNonEOLSymbol();
current.Expect(Symbol.CloseBracket);
return augment;
}
else if (current != null)
{
symbols.PutBack(current);
}
return null;
}
private static string ParseDefVal(ISymbolEnumerator symbols)
{
Symbol current = symbols.NextNonEOLSymbol();
if (current == Symbol.DefVal)
{
current = symbols.NextNonEOLSymbol();
current.Expect(Symbol.OpenBracket);
string defVal = null;
current = symbols.NextNonEOLSymbol();
if (current == Symbol.OpenBracket)
{
int depth = 1;
// TODO: decode this.
while (depth > 0)
{
current = symbols.NextNonEOLSymbol();
if (current == Symbol.OpenBracket)
{
depth++;
}
else if (current == Symbol.CloseBracket)
{
depth--;
}
}
}
else
{
defVal = current.ToString();
current = symbols.NextNonEOLSymbol();
current.Expect(Symbol.CloseBracket);
}
return defVal;
}
else if (current != null)
{
symbols.PutBack(current);
}
return null;
}
private static IList<string> ParseIndices(ISymbolEnumerator symbols)
{
Symbol current = symbols.NextNonEOLSymbol();
if (current == Symbol.Index)
{
current = symbols.NextNonEOLSymbol();
current.Expect(Symbol.OpenBracket);
List<string> indices = new List<string>();
while (current != Symbol.CloseBracket)
{
current = symbols.NextNonEOLSymbol();
bool lastIndex = false;
if (current == Symbol.Implied)
{
current = symbols.NextNonEOLSymbol();
lastIndex = true; // 'IMPLIED' may only be used for last index
}
current.Assert((current != Symbol.Comma) && (current != Symbol.CloseBracket), "Expected index name but found symbol!");
indices.Add(current.ToString());
current = symbols.NextNonEOLSymbol();
if (lastIndex)
{
current.Expect(Symbol.CloseBracket);
}
else
{
current.Expect(Symbol.Comma, Symbol.CloseBracket);
}
}
return indices;
}
else if (current != null)
{
symbols.PutBack(current);
}
return null;
}
private static string ParseReference(ISymbolEnumerator symbols)
{
Symbol current = symbols.NextNonEOLSymbol();
if (current == Symbol.Reference)
{
return symbols.NextNonEOLSymbol().ToString();
}
else if (current != null)
{
symbols.PutBack(current);
}
return null;
}
private static string ParseDescription(ISymbolEnumerator symbols)
{
Symbol current = symbols.NextNonEOLSymbol();
if (current == Symbol.Description)
{
return symbols.NextNonEOLSymbol().ToString().Trim(new char[] { '"' });
}
else if (current != null)
{
symbols.PutBack(current);
}
return null;
}
private static Status ParseStatus(ISymbolEnumerator symbols)
{
Status status = Status.obsolete;
Symbol current = symbols.NextNonEOLSymbol();
current.Expect(Symbol.Status);
current = symbols.NextNonEOLSymbol();
try
{
status = (Status)Enum.Parse(typeof(Status), current.ToString());
}
catch (ArgumentException)
{
current.Assert(false, "Invalid/Unknown status");
}
return status;
}
private static MaxAccess ParseAccess(ISymbolEnumerator symbols)
{
MaxAccess access = MaxAccess.notAccessible;
Symbol current = symbols.NextNonEOLSymbol();
current.Expect(Symbol.MaxAccess, Symbol.Access);
current = symbols.NextNonEOLSymbol();
switch (current.ToString())
{
case "not-accessible":
access = MaxAccess.notAccessible;
break;
case "accessible-for-notify":
access = MaxAccess.accessibleForNotify;
break;
case "read-only":
access = MaxAccess.readOnly;
break;
case "read-write":
access = MaxAccess.readWrite;
break;
case "read-create":
access = MaxAccess.readCreate;
break;
case "write-only":
access = MaxAccess.readWrite;
break;
default:
current.Assert(false, "Invalid/Unknown access");
break;
}
return access;
}
private static string ParseUnits(ISymbolEnumerator symbols)
{
Symbol current = symbols.NextNonEOLSymbol();
if (current == Symbol.Units)
{
return symbols.NextNonEOLSymbol().ToString();
}
else if (current != null)
{
symbols.PutBack(current);
}
return null;
}
private static ITypeAssignment ParseSyntax(IModule module, ISymbolEnumerator symbols)
{
Symbol current = symbols.NextNonEOLSymbol();
current.Expect(Symbol.Syntax);
return Lexer.ParseBasicTypeDef(module, String.Empty, symbols, isMacroSyntax: true);
}
private static bool IsProperty(Symbol sym)
{
string s = sym.ToString();
return s == "SYNTAX" || s == "MAX-ACCESS" || s == "STATUS" || s == "DESCRIPTION";
}
public ITypeAssignment Syntax
{
get { return _syntax; }
internal set { _syntax = value; }
}
public override string Description
{
get { return _description; }
}
public MaxAccess Access
{
get { return _access; }
}
public IList<string> Indices
{
get { return _indices; }
}
public string Augments
{
get { return _augments; }
}
#region ITypeReferrer Member
public ITypeAssignment ReferredType
{
get { return _syntax; }
set { _syntax = value; }
}
public ITypeAssignment BaseType
{
get
{
ITypeReferrer tr = this;
ITypeAssignment result = null;
while ((tr != null) && (tr.ReferredType != null))
{
result = tr.ReferredType;
tr = tr.ReferredType as ITypeReferrer;
}
return result;
}
}
#endregion
}
}

View File

@ -0,0 +1,30 @@
/*
* Created by SharpDevelop.
* User: lextm
* Date: 2008/5/17
* Time: 20:49
*
* To change this template use Tools | Options | Coding | Edit Standard Headers.
*/
using System;
namespace Lextm.SharpSnmpLib.Mib.Elements.Entities
{
/// <summary>
/// Object identifier node.
/// </summary>
public sealed class OidValueAssignment : EntityBase
{
/// <summary>
/// Creates a <see cref="OidValueAssignment"/>.
/// </summary>
/// <param name="module">Module</param>
/// <param name="name">Name</param>
/// <param name="lexer">Lexer</param>
public OidValueAssignment(IModule module, SymbolList preAssignSymbols, ISymbolEnumerator symbols)
: base(module, preAssignSymbols, symbols)
{
}
}
}

View File

@ -0,0 +1,56 @@
/*
* Created by SharpDevelop.
* User: lextm
* Date: 2008/6/7
* Time: 17:34
*
* To change this template use Tools | Options | Coding | Edit Standard Headers.
*/
using System.Collections.Generic;
namespace Lextm.SharpSnmpLib.Mib.Elements
{
/// <summary>
/// Description of Exports.
/// </summary>
public sealed class Exports: IElement
{
private IModule _module;
private readonly IList<string> _types = new List<string>();
public Exports(IModule module, ISymbolEnumerator s)
{
_module = module;
Symbol previous = null;
Symbol current;
do
{
current = s.NextSymbol();
if (current == Symbol.EOL)
{
continue;
}
else if (((current == Symbol.Comma) || (current == Symbol.Semicolon)) && (previous != null))
{
previous.AssertIsValidIdentifier();
_types.Add(previous.ToString());
}
previous = current;
}
while (current != Symbol.Semicolon);
}
#region IElement Member
public IModule Module
{
get { return _module; }
}
#endregion
}
}

View File

@ -0,0 +1,18 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Lextm.SharpSnmpLib.Mib.Elements
{
public interface IDeclaration: IElement
{
/// <summary>
/// Name.
/// </summary>
string Name
{
get;
}
}
}

View File

@ -0,0 +1,35 @@
// Construct interface.
// Copyright (C) 2008-2010 Malcolm Crowe, Lex Li, and other contributors.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
namespace Lextm.SharpSnmpLib.Mib.Elements
{
/// <summary>
/// Construct interface.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1040:AvoidEmptyInterfaces")]
public interface IElement
{
/// <summary>
/// Containing module.
/// </summary>
IModule Module
{
get;
}
}
}

View File

@ -0,0 +1,10 @@
using Lextm.SharpSnmpLib.Mib.Elements.Types;
namespace Lextm.SharpSnmpLib.Mib.Elements
{
public interface ITypeReferrer
{
ITypeAssignment ReferredType { get; set; }
ITypeAssignment BaseType { get; }
}
}

View File

@ -0,0 +1,81 @@
/*
* Created by SharpDevelop.
* User: lextm
* Date: 2008/5/31
* Time: 12:07
*
* To change this template use Tools | Options | Coding | Edit Standard Headers.
*/
using System.Collections.Generic;
namespace Lextm.SharpSnmpLib.Mib.Elements
{
/// <summary>
/// The IMPORTS construct is used to specify items used in the current MIB module which are defined in another MIB module or ASN.1 module.
/// </summary>
public sealed class Imports : List<ImportsFrom>, IElement
{
private IModule _module;
/// <summary>
/// Creates an <see cref="Imports"/> instance.
/// </summary>
/// <param name="lexer"></param>
public Imports(IModule module, ISymbolEnumerator symbols)
{
_module = module;
Symbol current;
while ((current = symbols.NextSymbol()) != Symbol.Semicolon)
{
if (current == Symbol.EOL)
{
continue;
}
ImportsFrom imports = new ImportsFrom(current, symbols);
this.Add(imports);
}
}
public IList<string> Dependents
{
get
{
List<string> result = new List<string>();
foreach (ImportsFrom import in this)
{
result.Add(import.Module);
}
return result;
}
}
public ImportsFrom GetImportFromType(string type)
{
foreach (ImportsFrom import in this)
{
if (import.Types.Contains(type))
{
return import;
}
}
return null;
}
#region IElement Member
public IModule Module
{
get { return _module; }
}
#endregion
}
}

View File

@ -0,0 +1,60 @@
/*
* Created by SharpDevelop.
* User: lextm
* Date: 2008/5/31
* Time: 12:07
*
* To change this template use Tools | Options | Coding | Edit Standard Headers.
*/
using System.Collections.Generic;
namespace Lextm.SharpSnmpLib.Mib.Elements
{
public sealed class ImportsFrom
{
private readonly string _module;
private readonly List<string> _types = new List<string>();
public ImportsFrom(Symbol last, ISymbolEnumerator symbols)
{
Symbol previous = last;
Symbol current;
while ((current = symbols.NextSymbol()) != Symbol.From)
{
if (current == Symbol.EOL)
{
continue;
}
if (current == Symbol.Comma)
{
previous.AssertIsValidIdentifier();
_types.Add(previous.ToString());
}
previous = current;
}
previous.AssertIsValidIdentifier();
_types.Add(previous.ToString());
_module = symbols.NextSymbol().ToString().ToUpperInvariant(); // module names are uppercase
}
public string Module
{
get { return _module; }
}
public IList<string> Types
{
get { return _types; }
}
public override string ToString()
{
return string.Join(", ", _types.ToArray()) + " FROM " + _module;
}
}
}

View File

@ -0,0 +1,48 @@
/*
* Created by SharpDevelop.
* User: lextm
* Date: 2008/5/31
* Time: 12:20
*
* To change this template use Tools | Options | Coding | Edit Standard Headers.
*/
namespace Lextm.SharpSnmpLib.Mib.Elements
{
public sealed class TrapType : IDeclaration
{
private readonly IModule _module;
private readonly string _name;
private readonly int _value;
public TrapType(IModule module, SymbolList preAssignSymbols, ISymbolEnumerator symbols)
{
_module = module;
_name = preAssignSymbols[0].ToString();
Symbol valueSymbol = symbols.NextNonEOLSymbol();
bool succeeded = int.TryParse(valueSymbol.ToString(), out _value);
valueSymbol.Assert(succeeded, "not a decimal");
}
public int Value
{
get { return _value; }
}
#region IDeclaration Member
public IModule Module
{
get { return _module; }
}
public string Name
{
get { return _name; }
}
#endregion
}
}

View File

@ -0,0 +1,54 @@

namespace Lextm.SharpSnmpLib.Mib.Elements.Types
{
public abstract class BaseType : ITypeAssignment
{
private IModule _module;
private string _name;
protected BaseType(IModule module, string name)
{
_module = module;
_name = name;
}
public virtual IModule Module
{
// differentiate between:
// FddiTimeNano ::= INTEGER (0..2147483647)
// which is an IntegerType which appears under Types in a MibModule and therefore has a name and module
// and
// SYNTAX INTEGER (0..2147483647)
// which is also an IntegerType but not defined as a separate type and therefore has NO name and NO module
get
{
if (!string.IsNullOrEmpty(_name))
{
return _module;
}
else
{
return null;
}
}
protected set { _module = value; }
}
public virtual string Name
{
get
{
if (!string.IsNullOrEmpty(_name))
{
return _name;
}
else
{
return "{ Implicit Base Type }";
}
}
protected set { _name = value; }
}
}
}

View File

@ -0,0 +1,26 @@
using System;
using System.Collections.Generic;
namespace Lextm.SharpSnmpLib.Mib.Elements.Types
{
public class BitsType : BaseType
{
private ValueMap _map;
public BitsType(IModule module, string name, ISymbolEnumerator symbols)
: base(module, name)
{
_map = Lexer.DecodeEnumerations(symbols);
}
public ValueMap Map
{
get { return _map; }
}
public string this[int value]
{
get { return _map[value]; }
}
}
}

View File

@ -0,0 +1,35 @@
/*
* Created by SharpDevelop.
* User: lextm
* Date: 2008/5/31
* Time: 11:39
*
* To change this template use Tools | Options | Coding | Edit Standard Headers.
*/
namespace Lextm.SharpSnmpLib.Mib.Elements.Types
{
/// <summary>
/// The CHOICE type represents a list of alternatives..
/// </summary>
public sealed class Choice : BaseType
{
/// <summary>
/// Creates a <see cref="Choice"/> instance.
/// </summary>
/// <param name="module"></param>
/// <param name="name"></param>
/// <param name="lexer"></param>
public Choice(IModule module, string name, ISymbolEnumerator symbols)
: base(module, name)
{
while (symbols.NextNonEOLSymbol() != Symbol.OpenBracket)
{
}
while (symbols.NextNonEOLSymbol() != Symbol.CloseBracket)
{
}
}
}
}

View File

@ -0,0 +1,6 @@
namespace Lextm.SharpSnmpLib.Mib.Elements.Types
{
public interface ITypeAssignment : IDeclaration
{
}
}

View File

@ -0,0 +1,117 @@
/*
* Created by SharpDevelop.
* User: lextm
* Date: 2008/7/25
* Time: 20:41
*
* To change this template use Tools | Options | Coding | Edit Standard Headers.
*/
using System;
using System.Collections.Generic;
namespace Lextm.SharpSnmpLib.Mib.Elements.Types
{
/// <summary>
/// The INTEGER type represents a list of alternatives, or a range of numbers..
/// Includes Integer32 as it's indistinguishable from INTEGER.
/// </summary>
/**
* As this type is used for Integer32 as well as INTEGER it incorrectly
* allows enumeration sub-typing of Integer32. This is ok as currently we
* do not care about detecting incorrect MIBs and this doesn't block the
* decoding of correct MIBs.
*/
public sealed class IntegerType : BaseType
{
public enum Types
{
Integer,
Integer32
}
private Types _type;
private bool _isEnumeration;
private ValueMap _map;
private ValueRanges _ranges;
/// <summary>
/// Creates an <see cref="IntegerType"/> instance.
/// </summary>
/// <param name="module"></param>
/// <param name="name"></param>
/// <param name="enumerator"></param>
public IntegerType(IModule module, string name, Symbol type, ISymbolEnumerator symbols)
: base (module, name)
{
Types? t = GetExactType(type);
type.Assert(t.HasValue, "Unknown symbol for unsigned type!");
_type = t.Value;
_isEnumeration = false;
Symbol current = symbols.NextNonEOLSymbol();
if (current == Symbol.OpenBracket)
{
_isEnumeration = true;
symbols.PutBack(current);
_map = Lexer.DecodeEnumerations(symbols);
}
else if (current == Symbol.OpenParentheses)
{
symbols.PutBack(current);
_ranges = Lexer.DecodeRanges(symbols);
current.Assert(!_ranges.IsSizeDeclaration, "SIZE keyword is not allowed for ranges of integer types!");
}
else
{
symbols.PutBack(current);
}
}
public Types Type
{
get { return _type; }
}
public ValueRanges Ranges
{
get { return _ranges; }
}
public bool IsEnumeration
{
get
{
return _isEnumeration;
}
}
public ValueMap Enumeration
{
get { return _isEnumeration ? _map : null; }
}
internal static Types? GetExactType(Symbol symbol)
{
if (symbol == Symbol.Integer)
{
// represents the ASN.1 builtin INTEGER type:
// may be represent any arbitrary (signed/unsigned) integer (in theory may have any size)
return Types.Integer;
}
else if (symbol == Symbol.Integer32)
{
// Integer32 ::= INTEGER (-2147483648..2147483647) // from SNMPv2-SMI
return Types.Integer32;
}
return null;
}
internal static bool IsIntegerType(Symbol symbol)
{
return GetExactType(symbol).HasValue;
}
}
}

View File

@ -0,0 +1,21 @@

namespace Lextm.SharpSnmpLib.Mib.Elements.Types
{
public class IpAddressType : OctetStringType
{
public IpAddressType(IModule module, string name, ISymbolEnumerator symbols)
: base(module, name, symbols)
{
if (this.Size.Count != 0)
{
throw new MibException("Size definition not allowed for IpAddress type!");
}
// IpAddress type is defined as:
// IpAddress ::=
// [APPLICATION 0]
// IMPLICIT OCTET STRING (SIZE (4))
this.Size.Add(new ValueRange(4, null));
}
}
}

View File

@ -0,0 +1,34 @@

namespace Lextm.SharpSnmpLib.Mib.Elements.Types
{
public sealed class Macro : ITypeAssignment
{
private IModule _module;
private string _name;
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1804:RemoveUnusedLocals", MessageId = "temp")]
public Macro(IModule module, SymbolList preAssignSymbols, ISymbolEnumerator symbols)
{
_module = module;
_name = preAssignSymbols[0].ToString();
while (symbols.NextNonEOLSymbol() != Symbol.Begin)
{
}
while (symbols.NextNonEOLSymbol() != Symbol.End)
{
}
}
public IModule Module
{
get { return _module; }
}
public string Name
{
get { return _name; }
}
}
}

View File

@ -0,0 +1,11 @@

namespace Lextm.SharpSnmpLib.Mib.Elements.Types
{
public class ObjectIdentifierType : BaseType
{
public ObjectIdentifierType(IModule module, string name, ISymbolEnumerator symbols)
: base(module, name)
{
}
}
}

View File

@ -0,0 +1,31 @@
using System.Collections.Generic;
namespace Lextm.SharpSnmpLib.Mib.Elements.Types
{
public class OctetStringType : BaseType
{
private ValueRanges _size;
public OctetStringType(IModule module, string name, ISymbolEnumerator symbols)
: base(module, name)
{
Symbol current = symbols.NextNonEOLSymbol();
if (current == Symbol.OpenParentheses)
{
symbols.PutBack(current);
_size = Lexer.DecodeRanges(symbols);
current.Assert(_size.IsSizeDeclaration, "SIZE keyword is required for ranges of octet string!");
}
else
{
symbols.PutBack(current);
_size = new ValueRanges(isSizeDecl: true);
}
}
public ValueRanges Size
{
get { return _size; }
}
}
}

View File

@ -0,0 +1,11 @@

namespace Lextm.SharpSnmpLib.Mib.Elements.Types
{
public class OpaqueType : OctetStringType
{
public OpaqueType(IModule module, string name, ISymbolEnumerator symbols)
: base(module, name, symbols)
{
}
}
}

View File

@ -0,0 +1,46 @@
/*
* Created by SharpDevelop.
* User: lextm
* Date: 2008/5/21
* Time: 19:43
*
* To change this template use Tools | Options | Coding | Edit Standard Headers.
*/
namespace Lextm.SharpSnmpLib.Mib.Elements.Types
{
/// <summary>
/// The SEQUENCE type represents a set of specified types. This is roughtly analogous to a <code>struct</code> in C.
/// </summary>
public sealed class Sequence : BaseType
{
/// <summary>
/// Creates a <see cref="Sequence" /> instance.
/// </summary>
/// <param name="module">The module.</param>
/// <param name="name">The name.</param>
/// <param name="symbols">The enumerator.</param>
public Sequence(IModule module, string name, ISymbolEnumerator symbols)
: base(module, name)
{
// parse between ( )
Symbol temp = symbols.NextNonEOLSymbol();
int bracketSection = 0;
temp.Expect(Symbol.OpenBracket);
bracketSection++;
while (bracketSection > 0)
{
temp = symbols.NextNonEOLSymbol();
if (temp == Symbol.OpenBracket)
{
bracketSection++;
}
else if (temp == Symbol.CloseBracket)
{
bracketSection--;
}
}
}
}
}

View File

@ -0,0 +1,23 @@
using System.Collections.Generic;
namespace Lextm.SharpSnmpLib.Mib.Elements.Types
{
/// <summary>
/// The SEQUENCE OF type represents a list of data sets..
/// </summary>
public sealed class SequenceOf : BaseType
{
private string _type;
public SequenceOf(IModule module, string name, ISymbolEnumerator sym)
: base(module, name)
{
_type = sym.NextNonEOLSymbol().ToString();
}
public string Type
{
get { return _type; }
}
}
}

View File

@ -0,0 +1,238 @@
using System;
namespace Lextm.SharpSnmpLib.Mib.Elements.Types
{
public sealed class TextualConvention : ITypeAssignment, ITypeReferrer
{
private IModule _module;
private string _name;
private DisplayHint _displayHint;
private Status _status;
private string _description;
private string _reference;
private ITypeAssignment _syntax;
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "module")]
public TextualConvention(IModule module, string name, ISymbolEnumerator symbols)
{
_module = module;
_name = name;
_displayHint = ParseDisplayHint(symbols);
_status = ParseStatus(symbols);
_description = ParseDescription(symbols);
_reference = ParseReference(symbols);
_syntax = ParseSyntax(module, symbols);
}
private static DisplayHint ParseDisplayHint(ISymbolEnumerator symbols)
{
Symbol current = symbols.NextNonEOLSymbol();
if (current == Symbol.DisplayHint)
{
return new DisplayHint(symbols.NextNonEOLSymbol().ToString().Trim(new char[] { '"' }));
}
symbols.PutBack(current);
return null;
}
private static Status ParseStatus(ISymbolEnumerator symbols)
{
Symbol current = symbols.NextNonEOLSymbol();
current.Expect(Symbol.Status);
try
{
return (Status)Enum.Parse(typeof(Status), symbols.NextNonEOLSymbol().ToString());
}
catch (ArgumentException)
{
current.Assert(false, "Invalid/Unknown status");
}
return Status.current;
}
private static string ParseDescription(ISymbolEnumerator symbols)
{
Symbol current = symbols.NextNonEOLSymbol();
current.Expect(Symbol.Description);
return symbols.NextNonEOLSymbol().ToString().Trim(new char[] { '"' });
}
private static string ParseReference(ISymbolEnumerator symbols)
{
Symbol current = symbols.NextNonEOLSymbol();
if (current == Symbol.Reference)
{
string reference = symbols.NextNonEOLSymbol().ToString();
if ((reference.Length >= 2) && reference.StartsWith("\"") && reference.EndsWith("\""))
{
return reference.Substring(1, reference.Length-2);
}
return reference;
}
symbols.PutBack(current);
return null;
}
private static ITypeAssignment ParseSyntax(IModule module, ISymbolEnumerator symbols)
{
Symbol current = symbols.NextNonEOLSymbol();
current.Expect(Symbol.Syntax);
/*
* RFC2579 definition:
* Syntax ::= -- Must be one of the following:
* -- a base type (or its refinement), or
* -- a BITS pseudo-type
* type
* | "BITS" "{" NamedBits "}"
*
* From section 3.5:
* The data structure must be one of the alternatives defined
* in the ObjectSyntax CHOICE or the BITS construct. Note
* that this means that the SYNTAX clause of a Textual
* Convention can not refer to a previously defined Textual
* Convention.
*
* The SYNTAX clause of a TEXTUAL CONVENTION macro may be
* sub-typed in the same way as the SYNTAX clause of an
* OBJECT-TYPE macro.
*
* Therefore the possible values are (grouped by underlying type):
* INTEGER, Integer32
* OCTET STRING, Opaque
* OBJECT IDENTIFIER
* IpAddress
* Counter64
* Unsigned32, Counter32, Gauge32, TimeTicks
* BITS
* With appropriate sub-typing.
*/
return Lexer.ParseBasicTypeDef(module, String.Empty, symbols, isMacroSyntax: true);
}
public IModule Module
{
get { return _module; }
}
public string Name
{
get { return _name; }
}
public string DisplayHint
{
get { return _displayHint == null ? null : _displayHint.ToString(); }
}
public Status Status
{
get { return _status; }
}
public string Description
{
get { return _description; }
}
public string Reference
{
get { return _reference; }
}
public ITypeAssignment Syntax
{
get { return _syntax; }
}
//internal object Decode(Variable v)
//{
// if (_syntax is IntegerType)
// {
// Integer32 i = v.Data as Integer32;
// if (i == null || (_syntax as IntegerType).IsEnumeration)
// {
// return null;
// }
// else if (_displayHint != null)
// {
// return _displayHint.Decode(i.ToInt32());
// }
// else
// {
// return i.ToInt32();
// }
// }
// else if (_syntax is UnsignedType)
// {
// Integer32 i = v.Data as Integer32;
// if (i == null)
// {
// return null;
// }
// else if (_displayHint != null)
// {
// return _displayHint.Decode(i.ToInt32());
// }
// else
// {
// return i.ToInt32();
// }
// }
// else if (_syntax is OctetStringType)
// {
// OctetString o = v.Data as OctetString;
// if (o == null)
// {
// return null;
// }
// else
// {
// // TODO: Follow the format specifier for octet strings.
// return null;
// }
// }
// else
// {
// return null;
// }
//}
#region ITypeReferrer Member
public ITypeAssignment ReferredType
{
get { return _syntax; }
set { _syntax = value; }
}
public ITypeAssignment BaseType
{
get
{
ITypeReferrer tr = this;
ITypeAssignment result = this;
while ((tr != null) && (tr.ReferredType != null))
{
result = tr.ReferredType;
tr = tr.ReferredType as ITypeReferrer;
}
return result;
}
}
#endregion
}
}

View File

@ -0,0 +1,147 @@
/*
* Created by SharpDevelop.
* User: lextm
* Date: 2008/5/18
* Time: 13:24
*
* To change this template use Tools | Options | Coding | Edit Standard Headers.
*/
using System;
using System.Collections.Generic;
namespace Lextm.SharpSnmpLib.Mib.Elements.Types
{
/* Please be aware of the following possible constructs:
*
* isnsRegEntityIndex OBJECT-TYPE
* SYNTAX IsnsEntityIndexIdOrZero
* ( 1 .. 4294967295 )
* MAX-ACCESS not-accessible
*
*
*/
/// <summary/>
/// </summary>
public sealed class TypeAssignment : ITypeAssignment
{
private IModule _module;
private string _name;
private string _type;
private ValueRanges _ranges;
private ValueMap _map;
/// <summary>
/// Creates an <see cref="TypeAssignment" />.
/// </summary>
/// <param name="module">The module.</param>
/// <param name="name">The name.</param>
/// <param name="type">The type.</param>
/// <param name="symbols">The symbols.</param>
/// <param name="isMacroSyntax">if set to <c>true</c> indicates that the syntax clause of a macro is parsed (e.g. OBJECT-TYPE, TEXTUAL-CONVENTION).</param>
public TypeAssignment(IModule module, string name, Symbol type, ISymbolEnumerator symbols, bool isMacroSyntax)
{
_module = module;
_name = name;
SymbolList typeSymbols = new SymbolList();
typeSymbols.Add(type);
Symbol current = symbols.NextSymbol();
while (current != Symbol.EOL)
{
if (current == Symbol.OpenParentheses)
{
// parse range of unknown type
symbols.PutBack(current);
_ranges = Lexer.DecodeRanges(symbols);
break;
}
else if (current == Symbol.OpenBracket)
{
symbols.PutBack(current);
_map = Lexer.DecodeEnumerations(symbols);
break;
}
typeSymbols.Add(current);
current = symbols.NextSymbol();
}
_type = typeSymbols.Join(" ");
if ((_ranges == null) && (_map == null))
{
current = symbols.NextNonEOLSymbol();
if (current == Symbol.OpenParentheses)
{
// parse range of unknown type
symbols.PutBack(current);
_ranges = Lexer.DecodeRanges(symbols);
}
else if (current == Symbol.OpenBracket)
{
symbols.PutBack(current);
_map = Lexer.DecodeEnumerations(symbols);
}
else if (current != null)
{
symbols.PutBack(current);
}
}
if (isMacroSyntax)
{
// inside a macro the syntax is limited to one line, except there are brackets used for ranges/enums
return;
}
// outside macro Syntax clause we wait for two consecutive linebreaks with a following valid identifier as end condition
Symbol previous = current;
Symbol veryPrevious = null;
while ((current = symbols.NextSymbol()) != null)
{
if ((veryPrevious == Symbol.EOL) && (previous == Symbol.EOL) && current.IsValidIdentifier())
{
symbols.PutBack(current);
return;
}
veryPrevious = previous;
previous = current;
}
previous.Assert(false, "end of file reached");
}
public string Type
{
get { return _type; }
}
public ValueRanges Ranges
{
get { return _ranges; }
}
public IDictionary<long, string> Map
{
get { return _map; }
}
#region ITypeAssignment Member
public IModule Module
{
get { return _module; }
}
public string Name
{
get { return _name; }
}
#endregion
}
}

View File

@ -0,0 +1,103 @@
using System.Collections.Generic;
namespace Lextm.SharpSnmpLib.Mib.Elements.Types
{
/**
* As this type is used for Counter32 and TimeTicks as well as Unsigned32
* and Gauge32 it incorrectly allows range restrictions of Counter32 and
* TimeTicks. This is ok as currently we do not care about detecting
* incorrect MIBs and this doesn't block the decoding of correct MIBs.
*/
public class UnsignedType : BaseType
{
public enum Types
{
Unsigned32,
Gauge32,
Counter32,
TimeTicks,
Counter64,
}
private Types _type;
private ValueRanges _ranges;
public UnsignedType(IModule module, string name, Symbol type, ISymbolEnumerator symbols)
: base(module, name)
{
Types? t = GetExactType(type);
type.Assert(t.HasValue, "Unknown symbol for unsigned type!");
_type = t.Value;
Symbol current = symbols.NextNonEOLSymbol();
if (current == Symbol.OpenParentheses)
{
current.Assert((_type != Types.Counter64), "Ranges are not supported for Counter64 type!"); // our internal struct can only hold int64 values
symbols.PutBack(current);
_ranges = Lexer.DecodeRanges(symbols);
current.Assert(!_ranges.IsSizeDeclaration, "SIZE keyword is not allowed for ranges of unsigned types!");
}
else
{
symbols.PutBack(current);
}
}
public Types Type
{
get { return _type; }
}
public ValueRanges Ranges
{
get { return _ranges; }
}
internal static Types? GetExactType(Symbol symbol)
{
if (symbol == Symbol.Unsigned32)
{
// [APPLICATION 2] IMPLICIT INTEGER (0..4294967295) // from SNMPv2-SMI
return Types.Unsigned32;
}
else if (symbol == Symbol.Gauge32)
{
// [APPLICATION 2] IMPLICIT INTEGER (0..4294967295) // from SNMPv2-SMI
return Types.Gauge32;
}
else if (symbol == Symbol.Counter32)
{
// [APPLICATION 1] IMPLICIT INTEGER (0..4294967295) // from SNMPv2-SMI
return Types.Counter32;
}
else if (symbol == Symbol.TimeTicks)
{
// [APPLICATION 3] IMPLICIT INTEGER (0..4294967295) // from SNMPv2-SMI + RFC1155-SMI
return Types.TimeTicks;
}
else if (symbol == Symbol.Gauge)
{
// [APPLICATION 2] IMPLICIT INTEGER (0..4294967295) // from RFC1155-SMI
return Types.Gauge32;
}
else if (symbol == Symbol.Counter)
{
// [APPLICATION 1] IMPLICIT INTEGER (0..4294967295) // from RFC1155-SMI
return Types.Counter32;
}
else if (symbol == Symbol.Counter64)
{
// [APPLICATION 6] IMPLICIT INTEGER (0..18446744073709551615) // from SNMPv2-SMI
return Types.Counter64;
}
return null;
}
internal static bool IsUnsignedType(Symbol symbol)
{
return GetExactType(symbol).HasValue;
}
}
}

View File

@ -0,0 +1,81 @@
// Module interface.
// Copyright (C) 2008-2010 Malcolm Crowe, Lex Li, and other contributors.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
/*
* Created by SharpDevelop.
* User: lextm
* Date: 5/1/2009
* Time: 10:40 AM
*
* To change this template use Tools | Options | Coding | Edit Standard Headers.
*/
using System.Collections.Generic;
using Lextm.SharpSnmpLib.Mib.Elements.Entities;
using Lextm.SharpSnmpLib.Mib.Elements.Types;
using Lextm.SharpSnmpLib.Mib.Elements;
namespace Lextm.SharpSnmpLib.Mib
{
/// <summary>
/// MIB Module interface.
/// </summary>
public interface IModule
{
/// <summary>
/// Module name.
/// </summary>
string Name
{
get;
}
Exports Exports
{
get;
}
Imports Imports
{
get;
}
/// <summary>
/// Entities + Types + all other elements implementing IDeclaration
/// </summary>
IList<IDeclaration> Declarations
{
get;
}
/// <summary>
/// Entities.
/// </summary>
IList<IEntity> Entities
{
get;
}
/// <summary>
/// Known types.
/// </summary>
IList<ITypeAssignment> Types
{
get;
}
}
}

View File

@ -0,0 +1,9 @@
using System.Collections.Generic;
namespace Lextm.SharpSnmpLib.Mib
{
public interface ISymbolEnumerator: IEnumerator<Symbol>
{
bool PutBack(Symbol item);
}
}

View File

@ -0,0 +1,581 @@
/*
* Created by SharpDevelop.
* User: lextm
* Date: 2008/5/17
* Time: 16:50
*
* To change this template use Tools | Options | Coding | Edit Standard Headers.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using Lextm.SharpSnmpLib.Mib.Elements.Types;
namespace Lextm.SharpSnmpLib.Mib
{
/// <summary>
/// Lexer class that parses MIB files into symbol list.
/// </summary>
public sealed class Lexer
{
private readonly SymbolList _symbols = new SymbolList();
public Lexer(string file)
: this(file, new StreamReader(file))
{
}
public Lexer(string file, TextReader stream)
{
this.Parse(file, stream);
}
public ISymbolEnumerator GetEnumerator()
{
return _symbols.GetSymbolEnumerator();
}
#region Parsing of MIB File
private class ParseParams
{
public string File;
public StringBuilder Temp = new StringBuilder();
public bool StringSection = false;
public bool AssignSection = false;
public bool AssignAhead = false;
public bool DotSection = false;
}
/// <summary>
/// Parses MIB file to symbol list.
/// </summary>
/// <param name="file">File</param>
/// <param name="stream">File stream</param>
private void Parse(string file, TextReader stream)
{
if (stream == null)
{
throw new ArgumentNullException("stream");
}
ParseParams pp = new ParseParams();
pp.File = file;
string line;
int row = 0;
while ((line = stream.ReadLine()) != null)
{
if (!pp.StringSection && line.TrimStart().StartsWith("--", StringComparison.Ordinal))
{
row++;
continue; // commented line
}
ParseLine(pp, line, row);
row++;
}
}
private void ParseLine(ParseParams pp, string line, int row)
{
line = line + "\n";
int count = line.Length;
for (int i = 0; i < count; i++)
{
char current = line[i];
bool moveNext = Parse(pp, current, row, i);
if (moveNext)
{
break;
}
}
}
private bool Parse(ParseParams pp, char current, int row, int column)
{
switch (current)
{
case '\n':
case '{':
case '}':
case '(':
case ')':
case '[':
case ']':
case ';':
case ',':
case '|':
if (!pp.StringSection)
{
bool moveNext = ParseLastSymbol(pp, row, column);
if (moveNext)
{
_symbols.Add(CreateSpecialSymbol(pp.File, '\n', row, column));
return true;
}
_symbols.Add(CreateSpecialSymbol(pp.File, current, row, column));
return false;
}
break;
case '"':
pp.StringSection = !pp.StringSection;
break;
case '\r':
return false;
default:
if ((int)current == 0x1A)
{
// IMPORTANT: ignore invisible characters such as SUB.
return false;
}
if (Char.IsWhiteSpace(current) && !pp.AssignSection && !pp.StringSection)
{
bool moveNext = ParseLastSymbol(pp, row, column);
if (moveNext)
{
_symbols.Add(CreateSpecialSymbol(pp.File, '\n', row, column));
return true;
}
return false;
}
if (pp.AssignAhead)
{
pp.AssignAhead = false;
ParseLastSymbol(pp, row, column);
break;
}
if (pp.DotSection && current != '.')
{
ParseLastSymbol(pp, row, column);
pp.DotSection = false;
}
if (current == '.' && !pp.StringSection)
{
if (!pp.DotSection)
{
ParseLastSymbol(pp, row, column);
pp.DotSection = true;
}
}
if (current == ':' && !pp.StringSection)
{
if (!pp.AssignSection)
{
ParseLastSymbol(pp, row, column);
}
pp.AssignSection = true;
}
if (current == '=' && !pp.StringSection)
{
pp.AssignSection = false;
pp.AssignAhead = true;
}
break;
}
pp.Temp.Append(current);
return false;
}
private bool ParseLastSymbol(ParseParams pp, int row, int column)
{
if (pp.Temp.Length > 0)
{
Symbol s = new Symbol(pp.File, pp.Temp.ToString(), row, column);
pp.Temp.Length = 0;
if (s.ToString().StartsWith(Symbol.Comment.ToString()))
{
// ignore the rest symbols on this line because they are in comment.
return true;
}
_symbols.Add(s);
}
return false;
}
private static Symbol CreateSpecialSymbol(string file, char value, int row, int column)
{
string str;
switch (value)
{
case '\n':
str = Environment.NewLine;
break;
case '{':
str = "{";
break;
case '}':
str = "}";
break;
case '(':
str = "(";
break;
case ')':
str = ")";
break;
case '[':
str = "[";
break;
case ']':
str = "]";
break;
case ';':
str = ";";
break;
case ',':
str = ",";
break;
case '|':
str = "|";
break;
default:
throw new ArgumentException("value is not a special character");
}
return new Symbol(file, str, row, column);
}
#endregion
#region Static Parse Helper
public static ITypeAssignment ParseBasicTypeDef(IModule module, string name, ISymbolEnumerator symbols, bool isMacroSyntax = false)
{
Symbol current = symbols.NextNonEOLSymbol();
if (current == Symbol.Bits)
{
return new BitsType(module, name, symbols);
}
if (IntegerType.IsIntegerType(current))
{
return new IntegerType(module, name, current, symbols);
}
if (UnsignedType.IsUnsignedType(current))
{
return new UnsignedType(module, name, current, symbols);
}
if (current == Symbol.Opaque)
{
return new OpaqueType(module, name, symbols);
}
if (current == Symbol.IpAddress)
{
return new IpAddressType(module, name, symbols);
}
if (current == Symbol.TextualConvention)
{
return new TextualConvention(module, name, symbols);
}
if (current == Symbol.Octet)
{
Symbol next = symbols.NextNonEOLSymbol();
if (next == Symbol.String)
{
return new OctetStringType(module, name, symbols);
}
symbols.PutBack(next);
}
if (current == Symbol.Object)
{
Symbol next = symbols.NextNonEOLSymbol();
if (next == Symbol.Identifier)
{
return new ObjectIdentifierType(module, name, symbols);
}
symbols.PutBack(next);
}
if (current == Symbol.Sequence)
{
Symbol next = symbols.NextNonEOLSymbol();
if (next == Symbol.Of)
{
return new SequenceOf(module, name, symbols);
}
else
{
symbols.PutBack(next);
return new Sequence(module, name, symbols);
}
}
if (current == Symbol.Choice)
{
return new Choice(module, name, symbols);
}
return new TypeAssignment(module, name, current, symbols, isMacroSyntax);
}
public static void ParseOidValue(ISymbolEnumerator symbols, out string parent, out uint value)
{
parent = null;
value = 0;
Symbol current = symbols.NextNonEOLSymbol();
current.Expect(Symbol.OpenBracket);
Symbol previous = null;
StringBuilder longParent = new StringBuilder();
current = symbols.NextNonEOLSymbol();
longParent.Append(current);
while ((current = symbols.NextNonEOLSymbol()) != null)
{
bool succeeded;
if (current == Symbol.OpenParentheses)
{
longParent.Append(current);
current = symbols.NextNonEOLSymbol();
succeeded = UInt32.TryParse(current.ToString(), out value);
current.Assert(succeeded, "not a decimal");
longParent.Append(current);
current = symbols.NextNonEOLSymbol();
current.Expect(Symbol.CloseParentheses);
longParent.Append(current);
continue;
}
if (current == Symbol.CloseBracket)
{
parent = longParent.ToString();
return;
}
succeeded = UInt32.TryParse(current.ToString(), out value);
if (succeeded)
{
// numerical way
while ((current = symbols.NextNonEOLSymbol()) != Symbol.CloseBracket)
{
longParent.Append(".").Append(value);
succeeded = UInt32.TryParse(current.ToString(), out value);
current.Assert(succeeded, "not a decimal");
}
current.Expect(Symbol.CloseBracket);
parent = longParent.ToString();
return;
}
longParent.Append(".");
longParent.Append(current);
current = symbols.NextNonEOLSymbol();
current.Expect(Symbol.OpenParentheses);
longParent.Append(current);
current = symbols.NextNonEOLSymbol();
succeeded = UInt32.TryParse(current.ToString(), out value);
current.Assert(succeeded, "not a decimal");
longParent.Append(current);
current = symbols.NextNonEOLSymbol();
current.Expect(Symbol.CloseParentheses);
longParent.Append(current);
previous = current;
}
throw MibException.Create("end of file reached", previous);
}
public static ValueRanges DecodeRanges(ISymbolEnumerator symbols)
{
ValueRanges result = new ValueRanges();
Symbol startSymbol = symbols.NextNonEOLSymbol();
Symbol current = startSymbol;
current.Expect(Symbol.OpenParentheses);
while (current != Symbol.CloseParentheses)
{
Symbol value1Symbol = symbols.NextNonEOLSymbol();
if ((value1Symbol == Symbol.Size) && !result.IsSizeDeclaration)
{
result.IsSizeDeclaration = true;
symbols.NextNonEOLSymbol().Expect(Symbol.OpenParentheses);
continue;
}
// check for valid number
Int64? value1 = DecodeNumber(value1Symbol);
if (!value1.HasValue)
{
value1Symbol.Assert(false, "Invalid range declaration!");
}
// process next symbol
ValueRange range;
current = symbols.NextNonEOLSymbol();
if (current == Symbol.DoubleDot)
{
// its a continous range
Symbol value2Symbol = symbols.NextNonEOLSymbol();
Int64? value2 = DecodeNumber(value2Symbol);
value2Symbol.Assert(value2.HasValue && (value2.Value >= value1.Value), "Invalid range declaration!");
if (value2.Value == value1.Value)
{
range = new ValueRange(value1.Value, null);
}
else
{
range = new ValueRange(value1.Value, value2.Value);
}
current = symbols.NextNonEOLSymbol();
}
else
{
// its a single number
range = new ValueRange(value1.Value, null);
}
// validate range
if (result.IsSizeDeclaration)
{
value1Symbol.Assert(range.Start >= 0, "Invalid range declaration! Size must be greater than 0");
}
result.Add(range);
// check next symbol
current.Expect(Symbol.Pipe, Symbol.CloseParentheses);
}
if (result.IsSizeDeclaration)
{
current = symbols.NextNonEOLSymbol();
current.Expect(Symbol.CloseParentheses);
}
// validate ranges in between
for (int i=0; i<result.Count; i++)
{
for (int k=i+1; k<result.Count; k++)
{
startSymbol.Assert(!result[i].IntersectsWith(result[k]), "Invalid range declaration! Overlapping of ranges!");
}
}
return result;
}
public static Int64? DecodeNumber(Symbol number)
{
Int64 result;
string numString = (number != null) ? number.ToString() : null;
if (!String.IsNullOrEmpty(numString))
{
if (numString.StartsWith("'") && (numString.Length > 3))
{
// search second apostrophe
int end = numString.IndexOf('\'', 1);
if (end == (numString.Length - 2))
{
try
{
switch (numString[numString.Length - 1])
{
case 'b':
case 'B':
result = Convert.ToInt64(numString.Substring(1, numString.Length - 3), 2);
return result;
case 'h':
case 'H':
result = Convert.ToInt64(numString.Substring(1, numString.Length - 3), 16);
return result;
}
}
catch
{
}
}
}
else if (Int64.TryParse(numString, out result))
{
return result;
}
}
return null;
}
public static ValueMap DecodeEnumerations(ISymbolEnumerator symbols)
{
Symbol current = symbols.NextNonEOLSymbol();
current.Expect(Symbol.OpenBracket);
ValueMap map = new ValueMap();
do
{
current = symbols.NextNonEOLSymbol();
string identifier = current.ToString();
current = symbols.NextNonEOLSymbol();
current.Expect(Symbol.OpenParentheses);
current = symbols.NextNonEOLSymbol();
Int64 enumValue;
if (Int64.TryParse(current.ToString(), out enumValue))
{
try
{
// Have to include the number as it seems repeated identifiers are allowed ??
map.Add(enumValue, String.Format("{0}({1})", identifier, enumValue));
}
catch (ArgumentException ex)
{
current.Assert(false, ex.Message);
}
}
else
{
// Need to get "DefinedValue".
}
current = symbols.NextNonEOLSymbol();
current.Expect(Symbol.CloseParentheses);
current = symbols.NextNonEOLSymbol();
} while (current == Symbol.Comma);
current.Expect(Symbol.CloseBracket);
return map;
}
#endregion
}
}

View File

@ -0,0 +1,17 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Lextm.SharpSnmpLib.Mib
{
public enum MaxAccess
{
notAccessible,
accessibleForNotify,
readOnly,
readWrite,
readCreate
}
}

View File

@ -0,0 +1,57 @@
/*
* Created by SharpDevelop.
* User: lextm
* Date: 2008/5/17
* Time: 17:38
*
* To change this template use Tools | Options | Coding | Edit Standard Headers.
*/
using System.Collections.Generic;
namespace Lextm.SharpSnmpLib.Mib
{
/// <summary>
/// MIB document.
/// </summary>
public sealed class MibDocument
{
private readonly List<IModule> _modules = new List<IModule>();
/// <summary>
/// Initializes a new instance of the <see cref="MibDocument" /> class.
/// </summary>
/// <param name="file">The file.</param>
public MibDocument(string file)
: this(new Lexer(file))
{
}
/// <summary>
/// Initializes a new instance of the <see cref="MibDocument"/> class.
/// </summary>
/// <param name="lexer">The lexer.</param>
public MibDocument(Lexer lexer)
{
ISymbolEnumerator symbols = lexer.GetEnumerator();
Symbol current;
while ((current = symbols.NextNonEOLSymbol()) != null)
{
symbols.PutBack(current);
_modules.Add(new MibModule(symbols));
}
}
/// <summary>
/// <see cref="MibModule"/> containing in this document.
/// </summary>
public IList<IModule> Modules
{
get
{
return _modules;
}
}
}
}

View File

@ -0,0 +1,113 @@
/*
* Created by SharpDevelop.
* User: lextm
* Date: 2008/5/17
* Time: 16:33
*
* To change this template use Tools | Options | Coding | Edit Standard Headers.
*/
using System;
using System.Globalization;
#if (!SILVERLIGHT)
using System.Runtime.Serialization;
using System.Security.Permissions;
#endif
namespace Lextm.SharpSnmpLib.Mib
{
/// <summary>
/// Description of MibException.
/// </summary>
[Serializable]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Mib")]
public sealed class MibException : Exception
{
/// <summary>
/// Symbol.
/// </summary>
public Symbol Symbol { get; private set; }
/// <summary>
/// Creates a <see cref="MibException"/>.
/// </summary>
public MibException()
{
}
/// <summary>
/// Creates a <see cref="SnmpException"/> instance with a specific <see cref="string"/>.
/// </summary>
/// <param name="message">Message</param>
public MibException(string message) : base(message)
{
}
/// <summary>
/// Creates a <see cref="MibException"/> instance with a specific <see cref="string"/> and an <see cref="Exception"/>.
/// </summary>
/// <param name="message">Message</param>
/// <param name="inner">Inner exception</param>
public MibException(string message, Exception inner)
: base(message, inner)
{
}
#if (!SILVERLIGHT)
/// <summary>
/// Creates a <see cref="MibException"/> instance.
/// </summary>
/// <param name="info">Info</param>
/// <param name="context">Context</param>
private MibException(SerializationInfo info, StreamingContext context) : base(info, context)
{
if (info == null)
{
throw new ArgumentNullException("info");
}
Symbol = (Symbol)info.GetValue("Symbol", typeof(Symbol));
}
/// <summary>
/// Gets object data.
/// </summary>
/// <param name="info">Info</param>
/// <param name="context">Context</param>
[SecurityPermission(SecurityAction.Demand, SerializationFormatter = true)]
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
base.GetObjectData(info, context);
info.AddValue("Symbol", Symbol);
}
#endif
/// <summary>
/// Creates a <see cref="MibException"/> with a specific <see cref="Symbol"/>.
/// </summary>
/// <param name="message">Message</param>
/// <param name="symbol">Symbol</param>
/// <returns></returns>
public static MibException Create(string message, Symbol symbol)
{
if (symbol == null)
{
throw new ArgumentNullException("symbol");
}
if (String.IsNullOrEmpty(message))
{
message = "Unknown MIB Exception";
}
message = String.Format(
"{0} (file: \"{1}\"; row: {2}; column: {3})",
message,
symbol.File,
symbol.Row + 1,
symbol.Column + 1);
MibException ex = new MibException(message) { Symbol = symbol };
return ex;
}
}
}

View File

@ -0,0 +1,294 @@
/*
* Created by SharpDevelop.
* User: lextm
* Date: 2008/5/17
* Time: 17:38
*
* To change this template use Tools | Options | Coding | Edit Standard Headers.
*/
using System;
using System.Collections.Generic;
using Lextm.SharpSnmpLib.Mib.Elements;
using Lextm.SharpSnmpLib.Mib.Elements.Entities;
using Lextm.SharpSnmpLib.Mib.Elements.Types;
namespace Lextm.SharpSnmpLib.Mib
{
/// <summary>
/// MIB module class.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Mib")]
public sealed class MibModule : IModule
{
private readonly string _name;
private readonly Imports _imports;
private readonly Exports _exports;
private readonly List<IElement> _tokens = new List<IElement>();
/// <summary>
/// Creates a <see cref="MibModule"/> with a specific <see cref="Lexer"/>.
/// </summary>
/// <param name="name">Module name</param>
/// <param name="symbols">Lexer</param>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "lexer")]
public MibModule(ISymbolEnumerator symbols)
{
if (symbols == null)
{
throw new ArgumentNullException("lexer");
}
Symbol temp = symbols.NextNonEOLSymbol();
temp.AssertIsValidIdentifier();
_name = temp.ToString().ToUpperInvariant(); // all module names are uppercase
temp = symbols.NextNonEOLSymbol();
temp.Expect(Symbol.Definitions);
temp = symbols.NextNonEOLSymbol();
temp.Expect(Symbol.Assign);
temp = symbols.NextSymbol();
temp.Expect(Symbol.Begin);
temp = symbols.NextNonEOLSymbol();
if (temp == Symbol.Imports)
{
_imports = ParseDependents(symbols);
}
else if (temp == Symbol.Exports)
{
_exports = ParseExports(symbols);
}
else
{
symbols.PutBack(temp);
}
ParseEntities(symbols);
}
#region Accessors
/// <summary>
/// Module name.
/// </summary>
public string Name
{
get { return _name; }
}
public Exports Exports
{
get { return _exports; }
}
public Imports Imports
{
get { return _imports; }
}
public List<IElement> Tokens
{
get { return this._tokens; }
}
/// <summary>
/// Entities + Types + all other elements implementing IDeclaration
/// </summary>
public IList<IDeclaration> Declarations
{
get
{
IList<IDeclaration> result = new List<IDeclaration>();
foreach (IElement e in _tokens)
{
IDeclaration decl = e as IDeclaration;
if (decl != null)
{
result.Add(decl);
}
}
return result;
}
}
/// <summary>
/// OID nodes.
/// </summary>
public IList<IEntity> Entities
{
get
{
IList<IEntity> result = new List<IEntity>();
foreach (IElement e in _tokens)
{
IEntity entity = e as IEntity;
if (entity != null)
{
result.Add(entity);
}
}
return result;
}
}
public IList<ITypeAssignment> Types
{
get
{
IList<ITypeAssignment> result = new List<ITypeAssignment>();
foreach (IElement e in _tokens)
{
ITypeAssignment type = e as ITypeAssignment;
if (type != null)
{
result.Add(type);
}
}
return result;
}
}
#endregion
#region Parsing of Symbols
private Exports ParseExports(ISymbolEnumerator symbols)
{
return new Exports(this, symbols);
}
private Imports ParseDependents(ISymbolEnumerator symbols)
{
return new Imports(this, symbols);
}
private void ParseEntities(ISymbolEnumerator symbols)
{
Symbol temp = symbols.NextNonEOLSymbol();
SymbolList buffer = new SymbolList();
while (temp != Symbol.End)
{
if (temp == Symbol.Assign)
{
ParseEntity(buffer, symbols);
buffer.Clear();
// skip linebreaks behind an entity
temp = symbols.NextNonEOLSymbol();
}
else
{
buffer.Add(temp);
temp = symbols.NextSymbol();
}
}
}
private void ParseEntity(SymbolList preAssignSymbols, ISymbolEnumerator symbols)
{
if ((preAssignSymbols == null) || (preAssignSymbols.Count == 0))
{
Symbol s = symbols.NextSymbol();
if (s != null)
{
s.Assert(false, "Invalid Entitiy declaration");
}
else
{
throw new MibException("Invalid Entitiy declaration");
}
}
// check for a valid identifier
preAssignSymbols[0].AssertIsValidIdentifier();
if (preAssignSymbols.Count == 1)
{
// its a typedef
_tokens.Add(Lexer.ParseBasicTypeDef(this, preAssignSymbols[0].ToString(), symbols, isMacroSyntax: false));
return;
}
ISymbolEnumerator preAssignSymbolsEnumerator = preAssignSymbols.GetSymbolEnumerator();
preAssignSymbolsEnumerator.NextNonEOLSymbol(); // returns identifier
Symbol type = preAssignSymbolsEnumerator.NextNonEOLSymbol();
// parse declarations
if (type == Symbol.Object)
{
Symbol next = preAssignSymbolsEnumerator.NextNonEOLSymbol();
if (next == Symbol.Identifier)
{
_tokens.Add(new OidValueAssignment(this, preAssignSymbols, symbols));
return;
}
else if (next != null)
{
preAssignSymbolsEnumerator.PutBack(next);
}
}
if (type == Symbol.ModuleIdentity)
{
_tokens.Add(new ModuleIdentity(this, preAssignSymbols, symbols));
return;
}
if (type == Symbol.ObjectType)
{
_tokens.Add(new ObjectType(this, preAssignSymbols, symbols));
return;
}
if (type == Symbol.ObjectGroup)
{
_tokens.Add(new ObjectGroup(this, preAssignSymbols, symbols));
return;
}
if (type == Symbol.NotificationGroup)
{
_tokens.Add(new NotificationGroup(this, preAssignSymbols, symbols));
return;
}
if (type == Symbol.ModuleCompliance)
{
_tokens.Add(new ModuleCompliance(this, preAssignSymbols, symbols));
return;
}
if (type == Symbol.NotificationType)
{
_tokens.Add(new NotificationType(this, preAssignSymbols, symbols));
return;
}
if (type == Symbol.ObjectIdentity)
{
_tokens.Add(new ObjectIdentity(this, preAssignSymbols, symbols));
return;
}
if (type == Symbol.Macro)
{
_tokens.Add(new Macro(this, preAssignSymbols, symbols));
return;
}
if (type == Symbol.TrapType)
{
_tokens.Add(new TrapType(this, preAssignSymbols, symbols));
return;
}
if (type == Symbol.AgentCapabilities)
{
_tokens.Add(new AgentCapabilities(this, preAssignSymbols, symbols));
return;
}
preAssignSymbols[1].Assert(false, "Unknown/Invalid declaration");
}
#endregion
}
}

View File

@ -0,0 +1,95 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Reflection;
namespace Lextm.SharpSnmpLib.Mib
{
public interface IMibResolver
{
IModule Resolve(string moduleName);
}
public class FileSystemMibResolver : IMibResolver
{
private string _path;
private bool _recursive;
public FileSystemMibResolver(string path, bool recursive)
{
_path = path;
_recursive = recursive;
}
#region IMibResolver Member
public IModule Resolve(string moduleName)
{
if (Directory.Exists(_path))
{
string[] matchedFiles = Directory.GetFiles(
_path,
moduleName + ".*",
(_recursive) ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly);
if ((matchedFiles != null) && (matchedFiles.Length >= 1))
{
foreach (string matchedFile in matchedFiles)
{
try
{
MibDocument md = new MibDocument(matchedFile);
if (md.Modules.Count > 0)
{
return md.Modules[0];
}
}
catch
{
}
}
}
}
return null;
}
#endregion
}
// earlier code for search of versioned MIBs:
//
//private const string Pattern = "-V[0-9]+$";
//public static bool AllDependentsAvailable(MibModule module, IDictionary<string, MibModule> modules)
//{
// foreach (string dependent in module.Dependents)
// {
// if (!DependentFound(dependent, modules))
// {
// return false;
// }
// }
// return true;
//}
//private static bool DependentFound(string dependent, IDictionary<string, MibModule> modules)
//{
// if (!Regex.IsMatch(dependent, Pattern))
// {
// return modules.ContainsKey(dependent);
// }
// if (modules.ContainsKey(dependent))
// {
// return true;
// }
// string dependentNonVersion = Regex.Replace(dependent, Pattern, string.Empty);
// return modules.ContainsKey(dependentNonVersion);
//}
}

View File

@ -0,0 +1,84 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Lextm.SharpSnmpLib.Mib.Elements.Entities;
namespace Lextm.SharpSnmpLib.Mib
{
/// <summary>
/// Builds up a tree from a single MIB
/// </summary>
public class MibTree
{
private MibTreeNode _root = null;
public MibTree(MibModule module)
{
IList<IEntity> entities = module.Entities;
if (entities.Count > 0)
{
// try to find module identity as root
foreach (IEntity element in entities)
{
ModuleIdentity mi = element as ModuleIdentity;
if (mi != null)
{
entities.Remove(element);
_root = new MibTreeNode(null, mi);
break;
}
}
if (_root == null)
{
//no module identity, assume first entity is root
_root = new MibTreeNode(null, entities[0]);
entities.RemoveAt(0);
}
BuildTree(_root, entities);
UpdateTreeNodeTypes(_root);
}
}
public MibTreeNode Root
{
get { return _root; }
}
private void BuildTree(MibTreeNode node, IList<IEntity> entities)
{
int i = 0;
while (i < entities.Count)
{
if (entities[i].Parent == node.Entity.Name)
{
node.AddChild(entities[i]);
entities.RemoveAt(i);
}
else
{
i++;
}
}
foreach (MibTreeNode childNode in node.ChildNodes)
{
BuildTree(childNode, entities);
}
}
private void UpdateTreeNodeTypes(MibTreeNode node)
{
node.UpdateNodeType();
foreach (MibTreeNode childNode in node.ChildNodes)
{
UpdateTreeNodeTypes(childNode);
}
}
}
}

Some files were not shown because too many files have changed in this diff Show More