Beispiel #1
0
        //public string DoWork(string value)
        //{
        //    ILockServiceCallback callback = OperationContext.Current.GetCallbackChannel<ILockServiceCallback>();
        //    new Thread(NewMethod).Start(callback);
        //    return "Welcome " + value;
        //}
        //private void NewMethod(object ooo)
        //{
        //    ILockServiceCallback callback = ooo as ILockServiceCallback;
        //    callback.LockIsAvailable(ObjectIdentifier.ERROR_OID);
        //}
        public TryLockResult TryLock(ObjectIdentifier objectId, bool tellWhenAvailable = false)
        {
            m_objectLock.EnterUpgradeableReadLock();
            try
            {
                Lock currentLock = null;
                if (m_object.TryGetValue(objectId, out currentLock))
                {
                    // если время блокировки закончилось, то блокируем
                }
                else
                {
                    m_subscribersLock.EnterWriteLock();
                    try
                    {
                        // установить блокировку
                    }
                    finally
                    {
                        m_subscribersLock.ExitWriteLock();
                    }
                }
            }
            finally
            {
                m_objectLock.ExitUpgradeableReadLock();
            }

            return new TryLockResult(true);
        }
 public void TestConstructor()
 {
     ObjectIdentifier oid = new ObjectIdentifier(new byte[] { 0x2B, 0x06, 0x99, 0x37 });
     Assert.AreEqual(new uint[] { 1, 3, 6, 3255 }, oid.ToNumerical());
     var o = ObjectIdentifier.Create(new uint[] {1, 3, 6}, 3255);
     Assert.AreEqual(oid, o);
 }
Beispiel #3
0
        public static void Main(string[] args)
        {
            if (args.Length != 1)
            {
                Console.WriteLine(@"This application takes one parameter.");
                return;
            }

            IObjectRegistry registry = new ReloadableObjectRegistry("modules");
            IObjectTree tree = registry.Tree;
            if (args[0].Contains("::"))
            {
                string name = args[0];
                var oid = registry.Translate(name);
                var id = new ObjectIdentifier(oid);
                Console.WriteLine(id);
            }
            else
            {
                string oid = args[0];
                var o = tree.Search(ObjectIdentifier.Convert(oid));
                string textual = o.AlternativeText;
                Console.WriteLine(textual);
                if (o.GetRemaining().Count == 0)
                {
                    Console.WriteLine(o.Definition.Type.ToString());
                }
            }
        }
Beispiel #4
0
 /// <summary>
 /// Constructor for load object from DB
 /// It must be used ONLY by EntityObjectFactory inherited class
 /// </summary>
 /// <param name="sessionId">Session identifier</param>
 /// <param name="objectId">Object identifier</param>
 public DomainObject(SessionIdentifier sessionId, ObjectIdentifier objectId)
 {
     // Save session identifier
     Session = sessionId;
     // Save object identifier
     ObjectId = objectId;
 }
Beispiel #5
0
        /// <summary>
        /// Initializes a new instance of the <see cref="SnmpTrapV2C"/> class.
        /// </summary>
        /// <param name="snmpDatagram">The snmp datagram.</param>
        public SnmpTrapV2C(SnmpDatagram snmpDatagram)
        {
            if(snmpDatagram.Header.Version != SnmpVersion.V2C || snmpDatagram.PduV2c.PduType == PduType.Trap)
            {
                throw new InvalidDataException("Not a Valid V2c Trap");
            }

            ObjectIdentifier trapOid = new ObjectIdentifier("1.3.6.1.6.3.1.1.4.1.0");
            ObjectIdentifier sysUpTimeOid = new ObjectIdentifier("1.3.6.1.2.1.1.3.0");

            PduV2c = snmpDatagram.PduV2c;
            Header = snmpDatagram.Header;
            TrapOid = default(ObjectIdentifier);
            SysUpTime = 0;
            VarBind varBind;
            if (PduV2c.VarBinds.SearchFirstSubOidWith(sysUpTimeOid, out varBind) && varBind.Asn1TypeInfo.Asn1SnmpTagType == Asn1SnmpTag.TimeTicks)
            {
                SysUpTime = (uint)varBind.Value;
            }

            if (PduV2c.VarBinds.SearchFirstSubOidWith(trapOid, out varBind) && varBind.Asn1TypeInfo.Asn1TagType == Asn1Tag.ObjectIdentifier)
            {
                TrapOid = (ObjectIdentifier)varBind.Value;
            }
        }
 public void Test()
 {
     var table = new SysORTable();
     Assert.AreEqual(null, table.MatchGet(new ObjectIdentifier("1.3.6")));
     var id = new ObjectIdentifier("1.3.6.1.2.1.1.9.1.1.1");
     Assert.AreEqual(id, table.MatchGet(id).Variable.Id);
     Assert.AreEqual(new ObjectIdentifier("1.3.6.1.2.1.1.9.1.1.2"), table.MatchGetNext(id).Variable.Id);
 }
Beispiel #7
0
        private object _version; //optimistic support: store timestamp info.

        #endregion Fields

        #region Constructors

        public PersistentObject()
        {
            _me = null;
            _oid = new OID();
            _version = null;
            _inUse = null;
            _references = new Dictionary<string, ObjectIdentifier>();
        }
Beispiel #8
0
 public PersistentObject(object persistableObj, ObjectIdentifier oid, object version, object inUse)
 {
     _me = persistableObj;
     _oid = oid;
     _version = version;
     _inUse = InUse;
     _references = new Dictionary<string, ObjectIdentifier>();
 }
 public void TestValidateTable()
 {
     ObjectIdentifier table = new ObjectIdentifier(new uint[] { 1, 3, 6, 1, 2, 1, 1, 9 });
     ObjectIdentifier entry = new ObjectIdentifier(new uint[] { 1, 3, 6, 1, 2, 1, 1, 9, 1 });
     ObjectIdentifier unknown = new ObjectIdentifier(new uint[] { 1, 3, 6, 8, 18579, 111111});
     Assert.IsTrue(DefaultObjectRegistry.Instance.ValidateTable(table));
     Assert.IsFalse(DefaultObjectRegistry.Instance.ValidateTable(entry));
     Assert.IsFalse(DefaultObjectRegistry.Instance.ValidateTable(unknown));
 }
 /// <summary>
 /// Validates if an <see cref="ObjectIdentifier"/> is a table.
 /// </summary>
 /// <param name="identifier">The object identifier.</param>
 /// <returns></returns>
 public bool ValidateTable(ObjectIdentifier identifier)
 {
     if (identifier == null)
     {
         throw new ArgumentNullException("identifier");
     }
         
     return IsTableId(identifier.ToNumerical());
 }
        public SnmpTrapAttribute(string objectIdentifier)
        {
            if (string.IsNullOrWhiteSpace(objectIdentifier))
            {
                throw new ArgumentNullException("objectIdentifier");
            }

            this.SnmpTrapOid = new ObjectIdentifier(objectIdentifier);
        }
Beispiel #12
0
 /// <summary>
 /// Returns a ResultSet containing the data with for the given identifier
 /// with the given parameters. For example a call for identifier
 /// Library and with a parameter called 'id' would return a
 /// MySqlDataReader with one row containing the data for the
 /// queried library.
 /// 
 /// You can find the necessary parameters for a query in the class
 /// corresponding to the identifier, as these classes are responsible
 /// to have the queries ready, that selects them from the database.
 /// </summary>
 /// <param name="ident">The identifier for the requested object class</param>
 /// <param name="parameters">The parameters for the query</param>
 /// <returns>A ResultSet containing the requested data</returns>
 public ResultSet GetResultSetFor(ObjectIdentifier ident, Dictionary<string, string> parameters)
 {
     if (this.Server != null)
     {
         return new ResultSet(this.Server.GetDataReaderFor(ident, parameters));
     } else
     {
         throw new NoServerConnectionException("Could not fetch result set because no server was set.");
     }
 }
Beispiel #13
0
        /// <summary>
        /// Creates a <see cref="Variable"/> instance with a specific object identifier and data.
        /// </summary>
        /// <param name="id">Object identifier</param>
        /// <param name="data">Data</param>
        /// <remarks>If you set <c>null</c> to <paramref name="data"/>, you get a <see cref="Variable"/> instance whose <see cref="Data"/> is a <see cref="Null"/> instance.</remarks>
        public Variable(ObjectIdentifier id, ISnmpData data)
        {
            if (id == null)
            {
                throw new ArgumentNullException("id");
            }

            Id = id;
            Data = data ?? new Null();
        }
Beispiel #14
0
 /// <summary>
 /// Gets all oids starting with.
 /// </summary>
 /// <param name="subOid">The sub oid.</param>
 ///  <param name="varBinds">The variable bind List.</param>
 /// <returns>IEnumerable of VarBind</returns>
 public static IEnumerable<VarBind> GetAllOidsStartingWith(this ReadOnlyCollection<VarBind> varBinds, ObjectIdentifier subOid)
 {
     for (int i = 0; i < varBinds.Count; i++)
     {
         if (varBinds[i].Oid.IsSubOid(subOid))
         {
             yield return varBinds[i];
         }
     }
 }
        internal void SetObjectIdentifier(ObjectIdentifier identifier)
        {
            if (identifier == null)
                throw new ArgumentNullException("identifier");

            VaultName = identifier.VaultName;
            Name = identifier.Name;
            Version = identifier.Version;
            Id = identifier.Id;
        }
 public TrapV2Pdu(int requestId, ObjectIdentifier enterprise, uint time, IList<Variable> variables)
 {
     Enterprise = enterprise;
     RequestId = new Integer32(requestId);
     _time = new TimeTicks(time);
     Variables = variables;
     IList<Variable> full = new List<Variable>(variables);
     full.Insert(0, new Variable(new uint[] { 1, 3, 6, 1, 2, 1, 1, 3, 0 }, _time));
     full.Insert(1, new Variable(new uint[] { 1, 3, 6, 1, 6, 3, 1, 1, 4, 1, 0 }, Enterprise));
     _varbindSection = Variable.Transform(full);
 }
 private static bool IsGuidFormat(string strTest)
 {
     try
     {
         var guidTest = new ObjectIdentifier(new Guid(strTest));
         return true;
     }
     catch
     {
         return false;
     }
 }
 public InformRequestPdu(int requestId, ObjectIdentifier enterprise, uint time, IList<Variable> variables)
 {
     Enterprise = enterprise;
     RequestId = new Integer32(requestId);
     _time = new TimeTicks(time);
     Variables = variables;
     IList<Variable> full = new List<Variable>(variables);
     full.Insert(0, new Variable(new uint[] { 1, 3, 6, 1, 2, 1, 1, 3, 0 }, _time));
     full.Insert(1, new Variable(new uint[] { 1, 3, 6, 1, 6, 3, 1, 1, 4, 1, 0 }, Enterprise));
     _varbindSection = Variable.Transform(full);
     ////_raw = ByteTool.ParseItems(_seq, new Integer32(0), new Integer32(0), _varbindSection);
 }        
Beispiel #19
0
        /// <summary>
        /// Initializes a new instance of the <see cref="SnmpTrapV1"/> class.
        /// </summary>
        /// <param name="snmpDatagram">The snmp datagram.</param>
        public SnmpTrapV1(SnmpDatagram snmpDatagram)
        {
            if (snmpDatagram.Header.Version != SnmpVersion.V1 && snmpDatagram.PduV1.PduType != PduType.Trap)
            {
                throw new InvalidDataException("Not a Valid V1 Trap");
            }

            PduV1 = snmpDatagram.PduV1;
            Header = snmpDatagram.Header;
            TrapOid = PduV1.Enterprise;
            SysUpTime = PduV1.TimeStamp;
        }
Beispiel #20
0
        public static LiteralType GetLiteralType(ObjectIdentifier name)
        {

            switch (name.GetName())
            {
                case "bigint":
                case "smallint":
                case "tinyint":
                case "int":
                case "bit":
                    return LiteralType.Integer;

                case "numeric":
                case "decimal":
                case "float":
                case "real":
                    return LiteralType.Numeric;


                case "money":
                case "smallmoney":
                    return LiteralType.Money;

                case "date":
                case "datetimeoffset":
                case "datetime2":
                case "smalldatetime":
                case "datetime":
                case "time":
                case "char":
                case "varchar":
                case "text":
                case "nchar":
                case "nvarchar":
                case "ntext":
                case "timestamp":
                case "uniqueidentifier":
                case "sql_variant":
                case "xml":

                    return LiteralType.String;

                case "binary":
                case "varbinary":
                case "image":
                    return LiteralType.Binary;

            }


            return LiteralType.String;
        }
Beispiel #21
0
        public static bool IsNText(ObjectIdentifier name)
        {
            switch (name.GetName())
            {
                case "nchar":
                case "nvarchar":
                case "ntext":
                case "xml":
                    return true;
            }

            return false;
        }
		/// <summary>
		/// Check the SNMP devices in the Devices.ini are available or not.
		/// If some devices are unavailable, the Devices.ini should be changed to give
		/// tester all available devices.
		/// </summary>
		/// <returns>list</returns>
		public static List<String> CheckSNMPDeviceAvailable(){			
			
		    List<string> notAvailable = new List<string>();
			int timeout = 3;
			VersionCode version = VersionCode.V1;
			IPEndPoint endpoint = new IPEndPoint(IPAddress.Parse("1.1.1.1"),161);
			OctetString community = new OctetString("public");
            
            ObjectIdentifier objectId = new ObjectIdentifier("1.3.6.1.2.1.11.1.0");
            Variable var = new Variable(objectId);   
            IList<Variable> varlist = new System.Collections.Generic.List<Variable>();
            varlist.Add(var);
            Variable data;
            IList<Variable> resultdata;
            IDictionary<string, string> AllDeviceInfo = new Dictionary<string, string> ();
            IDictionary<string, string> SNMPDeviceInfo = new Dictionary<string, string> ();
            
            AllDeviceInfo = AppConfigOper.mainOp.DevConfigs;

			foreach(string key in AllDeviceInfo.Keys)
			{
				if(key.ToUpper().StartsWith("SNMP"))
				{
					SNMPDeviceInfo.Add(key, AllDeviceInfo[key]);
				}
			}
			
			foreach (KeyValuePair<string, string>device in SNMPDeviceInfo)
			{ 
				Console.WriteLine("SNMPDeviceInfo: key={0},value={1}", device.Key, device.Value);
			}
			
            foreach(string deviceIp in SNMPDeviceInfo.Values)
            {
            	try
            	{
            		endpoint.Address = IPAddress.Parse(deviceIp);
	            	resultdata = Messenger.Get(version,endpoint,community,varlist,timeout);
	            	data = resultdata[0];
	            	Console.WriteLine("The device:" + deviceIp + "is availabe");
            	}
            	catch(Exception ex)
	            {
	            	notAvailable.Add(deviceIp);
	            	Console.WriteLine("There is no device in this ip address."+ deviceIp);
	            	string log = ex.ToString();
	            	continue;
	            }	
            }
            return notAvailable;
	   }
Beispiel #23
0
        public Info Build(string name, IEnumerable<TSqlColumn> fieldColumns)
        {
            var tableName = new ObjectIdentifier(new string[] { "dwh", name + "Info" });
            var identity = new IdentityFactory().Build(name + "Info" + "Id");

            var info = new Info()
            {
                Name = tableName,
                Identity = identity,
                Fields = new List<TSqlColumn>(fieldColumns)
            };

            return info;
        }
Beispiel #24
0
 internal PreviewRow(string objectCode, DataRow row)
 {
     m_data = row;
     try
     {
         object oidValue = m_data[OidField];
         long idValue = Convert.ToInt64(oidValue);
         OID = new ObjectIdentifier(objectCode, idValue);
     }
     catch (ArgumentException)
     {
         OID = ObjectIdentifier.ERROR_OID;
     }
 }
Beispiel #25
0
        /// <summary>
        /// Returns a MySqlDataReader containing the data for the given
        /// identifier and parameters. For example a call for identifier
        /// Library and with a parameter called 'id' would return a
        /// MySqlDataReader with one row containing the data for the
        /// queried library.
        /// 
        /// You can find the necessary parameters for a query in the class
        /// corresponding to the identifier, as these classes are responsible
        /// to have the queries ready, that selects them from the database.
        /// </summary>
        /// <param name="ident">The identifier for the object class</param>
        /// <param name="parameters">The parameters for the query</param>
        /// <returns>A MySqlDataReader with the requested data</returns>
        public MySqlDataReader GetDataReaderFor(ObjectIdentifier ident, Dictionary<string, string> parameters)
        {
            string sql = "";
            Dictionary<string, string> pars = new Dictionary<string, string>();

            switch (ident)
            {
                case ObjectIdentifier.Library:
                    if (parameters.ContainsKey("id"))
                    {
                        sql = Library.GetSelectQuery(true);
                        pars["id"] = parameters["id"];
                    }
                    else
                    {
                        sql = Library.GetSelectQuery(false);
                    }
                    break;

                case ObjectIdentifier.LibraryItem:
                    if (parameters.ContainsKey("id"))
                    {
                        sql = LibraryItem.GetSelectQuery(true);
                        pars["id"] = parameters["id"];
                    }
                    else
                    {
                        sql = LibraryItem.GetSelectQuery(false);
                    }
                    break;

                case ObjectIdentifier.User:
                    if (parameters.ContainsKey("id"))
                    {
                        sql = User.GetSelectQuery(true);
                        pars["id"] = parameters["id"];
                    }
                    else
                    {
                        sql = User.GetSelectQuery(false);
                    }
                    break;

                default:
                    throw new NotSupportedException("Given ObjectIdentifier is not supported.");
            }

            return this.Db.Query(sql, pars);
        }
Beispiel #26
0
        private void LockObject(SessionIdentifier session, ObjectIdentifier objectId)
        {
            LocalObjectLockInfo objectLock = null;
            if (lockedObjectStorage.TryGetValue(objectId, out objectLock))
            {
                if (session != objectLock.Session)
                {
                    throw new DomainException(String.Format("Объект c OID = {0} заблокирован в сессии {1} {2:HH.mm dd MMMM yyyy}", objectId, objectLock.Session, objectLock.BeginLockDate));
                }

                return;
            }

            lockedObjectStorage.Add(objectId, new LocalObjectLockInfo(session, objectId, DateTime.Now));
        }
Beispiel #27
0
        public void Asn1ObjectIdentifierTest()
        {
            var ObjectIdentifier1 = new ObjectIdentifier("1.3.6.1.2.1.1.3.0");
            var ObjectIdentifier2 = new ObjectIdentifier("1.3.6.1.2.1.1.1.1.1");
            var ObjectIdentifier3 = new ObjectIdentifier("1.3.6.1.2.1.1.3.0");

            Assert.IsTrue(ObjectIdentifier1.IsSubOid(ObjectIdentifier3));
            Assert.IsTrue(ObjectIdentifier1.IsSubOid(new ObjectIdentifier("1.3.6.1.2.1.1")));
            Assert.IsTrue(!ObjectIdentifier1.IsSubOid(ObjectIdentifier2));

            Assert.IsFalse(default(ObjectIdentifier).IsSubOid(ObjectIdentifier1));
            Assert.IsFalse(ObjectIdentifier1.IsSubOid(default(ObjectIdentifier)));

            Assert.IsTrue(default(ObjectIdentifier).IsSubOid(default(ObjectIdentifier)));
        }
        public override ScalarObject MatchGet(ObjectIdentifier id)
        {
            ScalarObject result = base.MatchGet(id);
            if (result == null && id.ToString().Contains(SNMPHelper.TestTreePath))
            {
                logger.InfoFormat("Create OID id: {0}", id);
                IOidUnit oidUnit = CreateOidUnit(id);
                oidUnit.ValueChanged +=
                    (sender, args) => { if (TestValueChanged != null) TestValueChanged.Invoke(sender, args); };

                result = (ScalarObject) oidUnit;
                _elements.Add(result);
            }
            return result;
        }
 public void ShouldGenerateUniqueId()
 {
     const int ObjectsNo = 100000;
     var identifier = new ObjectIdentifier();
     var objects = new object[ObjectsNo];
     for(var i = 0; i < objects.Length; i++)
     {
         objects[i] = new object();
     }
     var generated = new HashSet<int>();
     foreach(var obj in objects)
     {
         var id = identifier.GetId(obj);
         Assert.IsTrue(generated.Add(id), "Not unique ID was generated.");
     }
 }
Beispiel #30
0
 public InformRequestMessage(VersionCode version, int messageId, int requestId, OctetString userName, ObjectIdentifier enterprise, uint time, IList <Variable> variables, IPrivacyProvider privacy, int maxMessageSize, ISnmpMessage report)
     : this(version, messageId, requestId, userName, OctetString.Empty, enterprise, time, variables, privacy, maxMessageSize, report)
 {
 }
Beispiel #31
0
 //-----------------------------------
 private static void FillListeTables(
     CEasyQuerySource laBase,
     IDefinition definition,
     List <ITableDefinition> lstToFill,
     CEasyQuerySourceFolder folderRacine)
 {
     foreach (IDefinition children in definition.Children)
     {
         if (children.Type == DefinitionType.Table)
         {
             CTableDefinitionSNMP table = FromDefinition(laBase, children, folderRacine);
             if (table != null)
             {
                 lstToFill.Add(table);
                 laBase.AddTable(table);
             }
         }
         else if (children.Type == DefinitionType.OidValueAssignment || children.Type == DefinitionType.Scalar)
         {
             CEasyQuerySourceFolder folder = folderRacine.GetSubFolderWithCreate(children.Name);
             if (folder != null && children.GetNumericalForm().Length > 0)
             {
                 folder.SetExtendedProperty(c_strExtendedPropertyOID, ObjectIdentifier.Convert(children.GetNumericalForm()));
             }
             if (children.Type == DefinitionType.Scalar)
             {
                 folder.SetExtendedProperty(c_strExtendedPropertyValue, new CValeurExtendedProprieteFolderSnmpScalar(ObjectIdentifier.Convert(children.GetNumericalForm())));
                 folder.ImageKey = CValeurExtendedProprieteFolderSnmpScalar.c_strImageScalar;
             }
             FillListeTables(laBase, children, lstToFill, folder);
         }
     }
 }
Beispiel #32
0
        public static Variable[,] GetTable(VersionCode version, IPEndPoint endpoint, OctetString community, ObjectIdentifier table, int timeout, int maxRepetitions, IObjectRegistry registry)
        {
            if (version == VersionCode.V3)
            {
                throw new NotSupportedException("SNMP v3 is not supported");
            }

            bool canContinue = registry == null || registry.ValidateTable(table);

            if (!canContinue)
            {
                throw new ArgumentException("not a table OID: " + table);
            }

            IList <Variable> list = new List <Variable>();
            int rows = version == VersionCode.V1 ? Walk(version, endpoint, community, table, list, timeout, WalkMode.WithinSubtree) : BulkWalk(version, endpoint, community, table, list, timeout, maxRepetitions, WalkMode.WithinSubtree, null, null);

            if (rows == 0)
            {
                return(new Variable[0, 0]);
            }

            int cols = list.Count / rows;
            int k    = 0;

            Variable[,] result = new Variable[rows, cols];

            for (int j = 0; j < cols; j++)
            {
                for (int i = 0; i < rows; i++)
                {
                    result[i, j] = list[k];
                    k++;
                }
            }

            return(result);
        }
        public void TestConversion()
        {
            var o = new ObjectIdentifier(".1.3.6.1.2.1.1.1.0");

            Assert.AreEqual(".1.3.6.1.2.1.1.1.0", o.ToString());
        }
Beispiel #34
0
 public static void LabelObject(this GL gl, ObjectIdentifier objLabelIdent, uint glObject, string name)
 {
     gl.ObjectLabel(objLabelIdent, glObject, (uint)name.Length, name);
 }
Beispiel #35
0
        public InformRequestMessage(VersionCode version, int messageId, int requestId, OctetString userName, OctetString contextName, ObjectIdentifier enterprise, uint time, IList <Variable> variables, IPrivacyProvider privacy, int maxMessageSize, ISnmpMessage report)
        {
            if (userName == null)
            {
                throw new ArgumentNullException(nameof(userName));
            }

            if (variables == null)
            {
                throw new ArgumentNullException(nameof(variables));
            }

            if (version != VersionCode.V3)
            {
                throw new ArgumentException("Only v3 is supported.", nameof(version));
            }

            if (contextName == null)
            {
                throw new ArgumentNullException(nameof(contextName));
            }

            if (enterprise == null)
            {
                throw new ArgumentNullException(nameof(enterprise));
            }

            if (report == null)
            {
                throw new ArgumentNullException(nameof(report));
            }

            if (privacy == null)
            {
                throw new ArgumentNullException(nameof(privacy));
            }

            Version    = version;
            Privacy    = privacy;
            Enterprise = enterprise;
            TimeStamp  = time;

            Header = new Header(new Integer32(messageId), new Integer32(maxMessageSize), privacy.ToSecurityLevel() | Levels.Reportable);
            var parameters             = report.Parameters;
            var authenticationProvider = Privacy.AuthenticationProvider;

            Parameters = new SecurityParameters(
                parameters.EngineId,
                parameters.EngineBoots,
                parameters.EngineTime,
                userName,
                authenticationProvider.CleanDigest,
                Privacy.Salt);
            var pdu = new InformRequestPdu(
                requestId,
                enterprise,
                time,
                variables);
            var scope           = report.Scope;
            var contextEngineId = scope.ContextEngineId == OctetString.Empty ? parameters.EngineId : scope.ContextEngineId;

            Scope = new Scope(contextEngineId, contextName, pdu);

            Privacy.ComputeHash(Version, Header, Parameters, Scope);
            _bytes = this.PackMessage(null).ToBytes();
        }
Beispiel #36
0
		/// <summary>
		/// Matches the GET NEXT criteria.
		/// </summary>
		/// <param name="id">The ID in GET NEXT message.</param>
		/// <returns><c>null</c> if it does not match.</returns>
		public override ScalarObject MatchGetNext (ObjectIdentifier id)
			{
			return Objects.Select (o => o.MatchGetNext (id)).FirstOrDefault (result => result != null);
			}
 public override void write(ByteStream queue)
 {
     ObjectIdentifier.write(queue);
     AlarmState.write(queue);
     AcknowledgedTransitions.write(queue);
 }
Beispiel #38
0
        public TrapV2Message(VersionCode version, int messageId, int requestId, OctetString userName, ObjectIdentifier enterprise, uint time, IList <Variable> variables, IPrivacyProvider privacy, int maxMessageSize, OctetString engineId, int engineBoots, int engineTime)
        {
            if (userName == null)
            {
                throw new ArgumentNullException(nameof(userName));
            }

            if (variables == null)
            {
                throw new ArgumentNullException(nameof(variables));
            }

            if (version != VersionCode.V3)
            {
                throw new ArgumentException("Only v3 is supported.", nameof(version));
            }

            if (engineId == null)
            {
                throw new ArgumentNullException(nameof(engineId));
            }

            Version    = version;
            Privacy    = privacy ?? throw new ArgumentNullException(nameof(privacy));
            Enterprise = enterprise ?? throw new ArgumentNullException(nameof(enterprise));
            TimeStamp  = time;

            Header = new Header(new Integer32(messageId), new Integer32(maxMessageSize), privacy.ToSecurityLevel());
            var authenticationProvider = Privacy.AuthenticationProvider;

            Parameters = new SecurityParameters(
                engineId,
                new Integer32(engineBoots),
                new Integer32(engineTime),
                userName,
                authenticationProvider.CleanDigest,
                Privacy.Salt);
            var pdu = new TrapV2Pdu(
                requestId,
                enterprise,
                time,
                variables);

            // TODO: may expose engine ID in the future.
            Scope = new Scope(OctetString.Empty, OctetString.Empty, pdu);
            Privacy.ComputeHash(Version, Header, Parameters, Scope);
            _bytes = this.PackMessage(null).ToBytes();
        }
Beispiel #39
0
        public TrapV1Message(VersionCode version, IPAddress agent, OctetString community, ObjectIdentifier enterprise, GenericCode generic, int specific, uint time, IList <Variable> variables)
        {
            if (variables == null)
            {
                throw new ArgumentNullException("variables");
            }

            if (enterprise == null)
            {
                throw new ArgumentNullException("enterprise");
            }

            if (community == null)
            {
                throw new ArgumentNullException("community");
            }

            if (agent == null)
            {
                throw new ArgumentNullException("agent");
            }

            if (version != VersionCode.V1)
            {
                throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, "TRAP v1 is not supported in this SNMP version: {0}", version), "version");
            }

            Version      = version;
            AgentAddress = agent;
            Community    = community;
            Enterprise   = enterprise;
            Generic      = generic;
            Specific     = specific;
            TimeStamp    = time;
            var pdu = new TrapV1Pdu(
                Enterprise,
                new IP(AgentAddress),
                new Integer32((int)Generic),
                new Integer32(Specific),
                new TimeTicks(TimeStamp),
                variables);

            _pdu       = pdu;
            Parameters = SecurityParameters.Create(Community);

            _bytes = SnmpMessageExtension.PackMessage(Version, Community, pdu).ToBytes();
        }
Beispiel #40
0
 /// <summary>
 /// Gets the next object.
 /// </summary>
 /// <param name="id">The object id.</param>
 /// <returns></returns>
 public virtual ScalarObject GetNextObject(ObjectIdentifier id)
 {
     return(List.Select(o => o.MatchGetNext(id)).FirstOrDefault(result => result != null));
 }
Beispiel #41
0
        static void Main(string[] args)
        {
            string      community      = "public";
            bool        showHelp       = false;
            bool        showVersion    = false;
            VersionCode version        = VersionCode.V1;
            int         timeout        = 1000;
            int         retry          = 0;
            Levels      level          = Levels.Reportable;
            string      user           = string.Empty;
            string      authentication = string.Empty;
            string      authPhrase     = string.Empty;
            string      privacy        = string.Empty;
            string      privPhrase     = string.Empty;

            OptionSet p = new OptionSet()
                          .Add("c:", "Community name, (default is public)", delegate(string v) { if (v != null)
                                                                                                 {
                                                                                                     community = v;
                                                                                                 }
                               })
                          .Add("l:", "Security level, (default is noAuthNoPriv)", delegate(string v)
            {
                if (v.ToUpperInvariant() == "NOAUTHNOPRIV")
                {
                    level = Levels.Reportable;
                }
                else if (v.ToUpperInvariant() == "AUTHNOPRIV")
                {
                    level = Levels.Authentication | Levels.Reportable;
                }
                else if (v.ToUpperInvariant() == "AUTHPRIV")
                {
                    level = Levels.Authentication | Levels.Privacy | Levels.Reportable;
                }
                else
                {
                    throw new ArgumentException("no such security mode: " + v);
                }
            })
                          .Add("a:", "Authentication method (MD5 or SHA)", delegate(string v) { authentication = v; })
                          .Add("A:", "Authentication passphrase", delegate(string v) { authPhrase = v; })
                          .Add("x:", "Privacy method", delegate(string v) { privacy = v; })
                          .Add("X:", "Privacy passphrase", delegate(string v) { privPhrase = v; })
                          .Add("u:", "Security name", delegate(string v) { user = v; })
                          .Add("h|?|help", "Print this help information.", delegate(string v) { showHelp = v != null; })
                          .Add("V", "Display version number of this application.", delegate(string v) { showVersion = v != null; })
                          .Add("t:", "Timeout value (unit is second).", delegate(string v) { timeout = int.Parse(v) * 1000; })
                          .Add("r:", "Retry count (default is 0)", delegate(string v) { retry = int.Parse(v); })
                          .Add("v:", "SNMP version (1, 2, and 3 are currently supported)", delegate(string v)
            {
                switch (int.Parse(v))
                {
                case 1:
                    version = VersionCode.V1;
                    break;

                case 2:
                    version = VersionCode.V2;
                    break;

                case 3:
                    version = VersionCode.V3;
                    break;

                default:
                    throw new ArgumentException("no such version: " + v);
                }
            });

            if (args.Length == 0)
            {
                ShowHelp(p);
                return;
            }

            List <string> extra;

            try
            {
                extra = p.Parse(args);
            }
            catch (OptionException ex)
            {
                Console.WriteLine(ex.Message);
                return;
            }

            if (showHelp)
            {
                ShowHelp(p);
                return;
            }

            if ((extra.Count - 1) % 3 != 0)
            {
                Console.WriteLine("invalid variable number: " + extra.Count);
                return;
            }

            if (showVersion)
            {
                Console.WriteLine(System.Reflection.Assembly.GetExecutingAssembly().GetName().Version);
                return;
            }

            IPAddress ip;
            bool      parsed = IPAddress.TryParse(extra[0], out ip);

            if (!parsed)
            {
                foreach (IPAddress address in
                         Dns.GetHostAddresses(extra[0]).Where(address => address.AddressFamily == AddressFamily.InterNetwork))
                {
                    ip = address;
                    break;
                }

                if (ip == null)
                {
                    Console.WriteLine("invalid host or wrong IP address found: " + extra[0]);
                    return;
                }
            }

            try
            {
                List <Variable> vList = new List <Variable>();
                for (int i = 1; i < extra.Count; i = i + 3)
                {
                    string type = extra[i + 1];
                    if (type.Length != 1)
                    {
                        Console.WriteLine("invalid type string: " + type);
                        return;
                    }

                    ISnmpData data;

                    switch (type[0])
                    {
                    case 'i':
                        data = new Integer32(int.Parse(extra[i + 2]));
                        break;

                    case 'u':
                        data = new Gauge32(uint.Parse(extra[i + 2]));
                        break;

                    case 't':
                        data = new TimeTicks(uint.Parse(extra[i + 2]));
                        break;

                    case 'a':
                        data = new IP(IPAddress.Parse(extra[i + 2]));
                        break;

                    case 'o':
                        data = new ObjectIdentifier(extra[i + 2]);
                        break;

                    case 'x':
                        data = new OctetString(ByteTool.Convert(extra[i + 2]));
                        break;

                    case 's':
                        data = new OctetString(extra[i + 2]);
                        break;

                    case 'd':
                        data = new OctetString(ByteTool.ConvertDecimal(extra[i + 2]));
                        break;

                    case 'n':
                        data = new Null();
                        break;

                    default:
                        Console.WriteLine("unknown type string: " + type[0]);
                        return;
                    }

                    Variable test = new Variable(new ObjectIdentifier(extra[i]), data);
                    vList.Add(test);
                }

                IPEndPoint receiver = new IPEndPoint(ip, 161);
                if (version != VersionCode.V3)
                {
                    foreach (Variable variable in
                             Messenger.Set(version, receiver, new OctetString(community), vList, timeout))
                    {
                        Console.WriteLine(variable);
                    }

                    return;
                }

                if (string.IsNullOrEmpty(user))
                {
                    Console.WriteLine("User name need to be specified for v3.");
                    return;
                }

                IAuthenticationProvider auth = (level & Levels.Authentication) == Levels.Authentication
                                                   ? GetAuthenticationProviderByName(authentication, authPhrase)
                                                   : DefaultAuthenticationProvider.Instance;

                IPrivacyProvider priv;
                if ((level & Levels.Privacy) == Levels.Privacy)
                {
                    priv = new DESPrivacyProvider(new OctetString(privPhrase), auth);
                }
                else
                {
                    priv = new DefaultPrivacyProvider(auth);
                }

                Discovery     discovery = Messenger.NextDiscovery;
                ReportMessage report    = discovery.GetResponse(timeout, receiver);

                SetRequestMessage request = new SetRequestMessage(VersionCode.V3, Messenger.NextMessageId, Messenger.NextRequestId, new OctetString(user), vList, priv, Messenger.MaxMessageSize, report);

                ISnmpMessage response = request.GetResponse(timeout, receiver);
                if (response.Pdu().ErrorStatus.ToInt32() != 0) // != ErrorCode.NoError
                {
                    throw ErrorException.Create(
                              "error in response",
                              receiver.Address,
                              response);
                }

                foreach (Variable v in response.Pdu().Variables)
                {
                    Console.WriteLine(v);
                }
            }
            catch (SnmpException ex)
            {
                Console.WriteLine(ex);
            }
            catch (SocketException ex)
            {
                Console.WriteLine(ex);
            }
        }
Beispiel #42
0
 public abstract void ObjectLabel([Flow(FlowDirection.In)] ObjectIdentifier identifier, [Flow(FlowDirection.In)] uint name, [Flow(FlowDirection.In)] uint length, [Flow(FlowDirection.In)] string label);
 public static string GetSchemaObjectName(this ObjectIdentifier name)
 {
     return(string.Format("{0}.{1}", name.GetSchema(), name.GetName()));
 }
 public ContentInfo(ObjectIdentifier type, IAsn1Element content)
     : base(type, content)
 {
 }
 public static string GetName(this ObjectIdentifier name)
 {
     return(name.Parts.LastOrDefault());
 }
Beispiel #46
0
        public static void SendTrapV1(EndPoint receiver, IPAddress agent, OctetString community, ObjectIdentifier enterprise, GenericCode generic, int specific, uint timestamp, IList <Variable> variables)
        {
            TrapV1Message message = new TrapV1Message(VersionCode.V1, agent, community, enterprise, generic, specific, timestamp, variables);

            message.Send(receiver);
        }
Beispiel #47
0
 public Recipient(ObjectIdentifier device)
 {
     _choice = new Choice(0, device);
 }
Beispiel #48
0
        public static void SendTrapV2(int requestId, VersionCode version, EndPoint receiver, OctetString community, ObjectIdentifier enterprise, uint timestamp, IList <Variable> variables)
        {
            if (version == VersionCode.V1)
            {
                throw new ArgumentException("SNMP v1 is not support", "version");
            }

            TrapV2Message message = new TrapV2Message(requestId, version, community, enterprise, timestamp, variables);

            message.Send(receiver);
        }
Beispiel #49
0
 /// <summary>
 /// Matches the GET criteria.
 /// </summary>
 /// <param name="id">The ID in GET message.</param>
 /// <returns><c>null</c> if it does not match.</returns>
 public override ScalarObject MatchGet(ObjectIdentifier id)
 {
     return(Id == id ? this : null);
 }
        public void TestConstructor2()
        {
            ObjectIdentifier oid = new ObjectIdentifier(new byte[] { 0x2B, 0x06, 0x01, 0x04, 0x01, 0x90, 0x72, 0x87, 0x68, 0x02 });

            Assert.AreEqual(new uint[] { 1, 3, 6, 1, 4, 1, 2162, 1000, 2 }, oid.ToNumerical());
        }
 private static bool IsValidName(ObjectIdentifier name)
 {
     return(name.HasName && ValidationHelpers.IsFunction(name.Parts.Last()));
 }
Beispiel #52
0
        public void SetLabel(ObjectIdentifier ObjID, string Lbl)
        {
#if DEBUG
            Gl.ObjectLabel(ObjID, ID, Lbl.Length, Lbl);
#endif
        }
Beispiel #53
0
        public static void SendInform(int requestId, VersionCode version, IPEndPoint receiver, OctetString community, ObjectIdentifier enterprise, uint timestamp, IList <Variable> variables, int timeout, IPrivacyProvider privacy, ISnmpMessage report)
        {
            InformRequestMessage message = version == VersionCode.V3
                                    ? new InformRequestMessage(
                version,
                MessageCounter.NextId,
                requestId,
                community,
                enterprise,
                timestamp,
                variables,
                privacy,
                MaxMessageSize,
                report)
                                    : new InformRequestMessage(
                requestId,
                version,
                community,
                enterprise,
                timestamp,
                variables);

            ISnmpMessage response = message.GetResponse(timeout, receiver);

            if (response.Pdu.ErrorStatus.ToInt32() != 0)
            {
                throw ErrorException.Create(
                          "error in response",
                          receiver.Address,
                          response);
            }
        }
Beispiel #54
0
 /// <summary>
 /// Matches the GET criteria.
 /// </summary>
 /// <param name="id">The ID in GET message.</param>
 /// <returns><c>null</c> if it does not match.</returns>
 public abstract ScalarObject MatchGet(ObjectIdentifier id);
Beispiel #55
0
 protected ScalarObject(ObjectIdentifier id)
 {
     Id = id;
 }
Beispiel #56
0
        public static void Main(string[] args)
        {
            string      community      = "public";
            bool        showHelp       = false;
            bool        showVersion    = false;
            VersionCode version        = VersionCode.V1;
            int         timeout        = 1000;
            int         retry          = 0;
            int         maxRepetitions = 10;
            Levels      level          = Levels.Reportable;
            string      user           = string.Empty;
            string      authentication = string.Empty;
            string      authPhrase     = string.Empty;
            string      privacy        = string.Empty;
            string      privPhrase     = string.Empty;
            WalkMode    mode           = WalkMode.WithinSubtree;
            bool        dump           = false;

            OptionSet p = new OptionSet()
                          .Add("c:", "Community name, (default is public)", delegate(string v) { if (v != null)
                                                                                                 {
                                                                                                     community = v;
                                                                                                 }
                               })
                          .Add("l:", "Security level, (default is noAuthNoPriv)", delegate(string v)
            {
                if (v.ToUpperInvariant() == "NOAUTHNOPRIV")
                {
                    level = Levels.Reportable;
                }
                else if (v.ToUpperInvariant() == "AUTHNOPRIV")
                {
                    level = Levels.Authentication | Levels.Reportable;
                }
                else if (v.ToUpperInvariant() == "AUTHPRIV")
                {
                    level = Levels.Authentication | Levels.Privacy | Levels.Reportable;
                }
                else
                {
                    throw new ArgumentException("no such security mode: " + v);
                }
            })
                          .Add("a:", "Authentication method (MD5 or SHA)", delegate(string v) { authentication = v; })
                          .Add("A:", "Authentication passphrase", delegate(string v) { authPhrase = v; })
                          .Add("x:", "Privacy method", delegate(string v) { privacy = v; })
                          .Add("X:", "Privacy passphrase", delegate(string v) { privPhrase = v; })
                          .Add("u:", "Security name", delegate(string v) { user = v; })
                          .Add("h|?|help", "Print this help information.", delegate(string v) { showHelp = v != null; })
                          .Add("V", "Display version number of this application.", delegate(string v) { showVersion = v != null; })
                          .Add("d", "Display message dump", delegate(string v) { dump = true; })
                          .Add("t:", "Timeout value (unit is second).", delegate(string v) { timeout = int.Parse(v) * 1000; })
                          .Add("r:", "Retry count (default is 0)", delegate(string v) { retry = int.Parse(v); })
                          .Add("v|version:", "SNMP version (1, 2, and 3 are currently supported)", delegate(string v)
            {
                switch (int.Parse(v))
                {
                case 1:
                    version = VersionCode.V1;
                    break;

                case 2:
                    version = VersionCode.V2;
                    break;

                case 3:
                    version = VersionCode.V3;
                    break;

                default:
                    throw new ArgumentException("no such version: " + v);
                }
            })
                          .Add("m|mode:", "WALK mode (subtree, all are supported)", delegate(string v)
            {
                if (v == "subtree")
                {
                    mode = WalkMode.WithinSubtree;
                }
                else if (v == "all")
                {
                    mode = WalkMode.Default;
                }
                else
                {
                    throw new ArgumentException("unknown argument: " + v);
                }
            })
                          .Add("Cr:", "Max-repetitions (default is 10)", delegate(string v) { maxRepetitions = int.Parse(v); });

            if (args.Length == 0)
            {
                ShowHelp(p);
                return;
            }

            List <string> extra;

            try
            {
                extra = p.Parse(args);
            }
            catch (OptionException ex)
            {
                Console.WriteLine(ex.Message);
                return;
            }

            if (showHelp)
            {
                ShowHelp(p);
                return;
            }

            if (extra.Count < 1 || extra.Count > 2)
            {
                Console.WriteLine("invalid variable number: " + extra.Count);
                return;
            }

            if (showVersion)
            {
                Console.WriteLine(System.Reflection.Assembly.GetExecutingAssembly().GetName().Version);
                return;
            }

            IPAddress ip;
            bool      parsed = IPAddress.TryParse(extra[0], out ip);

            if (!parsed)
            {
                foreach (IPAddress address in
                         Dns.GetHostAddresses(extra[0]).Where(address => address.AddressFamily == AddressFamily.InterNetwork))
                {
                    ip = address;
                    break;
                }

                if (ip == null)
                {
                    Console.WriteLine("invalid host or wrong IP address found: " + extra[0]);
                    return;
                }
            }

            try
            {
                ObjectIdentifier test     = extra.Count == 1 ? new ObjectIdentifier("1.3.6.1.2.1") : new ObjectIdentifier(extra[1]);
                IList <Variable> result   = new List <Variable>();
                IPEndPoint       receiver = new IPEndPoint(ip, 161);
                if (version == VersionCode.V1)
                {
                    Messenger.Walk(version, receiver, new OctetString(community), test, result, timeout, mode);
                }
                else if (version == VersionCode.V2)
                {
                    Messenger.BulkWalk(version, receiver, new OctetString(community), test, result, timeout, maxRepetitions, mode, null, null);
                }
                else
                {
                    if (string.IsNullOrEmpty(user))
                    {
                        Console.WriteLine("User name need to be specified for v3.");
                        return;
                    }

                    IAuthenticationProvider auth = (level & Levels.Authentication) == Levels.Authentication
                        ? GetAuthenticationProviderByName(authentication, authPhrase)
                        : DefaultAuthenticationProvider.Instance;
                    IPrivacyProvider priv;
                    if ((level & Levels.Privacy) == Levels.Privacy)
                    {
                        priv = new DESPrivacyProvider(new OctetString(privPhrase), auth);
                    }
                    else
                    {
                        priv = new DefaultPrivacyProvider(auth);
                    }

                    Discovery     discovery = Messenger.GetNextDiscovery(SnmpType.GetBulkRequestPdu);
                    ReportMessage report    = discovery.GetResponse(timeout, receiver);
                    Messenger.BulkWalk(version, receiver, new OctetString(user), test, result, timeout, maxRepetitions, mode, priv, report);
                }

                foreach (Variable variable in result)
                {
                    Console.WriteLine(variable);
                }
            }
            catch (SnmpException ex)
            {
                Console.WriteLine(ex);
            }
            catch (SocketException ex)
            {
                Console.WriteLine(ex);
            }
        }
Beispiel #57
0
        public TrapV2Message(int requestId, VersionCode version, OctetString community, ObjectIdentifier enterprise, uint time, IList <Variable> variables)
        {
            if (variables == null)
            {
                throw new ArgumentNullException(nameof(variables));
            }

            if (community == null)
            {
                throw new ArgumentNullException(nameof(community));
            }

            if (version != VersionCode.V2)
            {
                throw new ArgumentException("Only v2c are supported.", nameof(version));
            }

            Version    = version;
            Enterprise = enterprise ?? throw new ArgumentNullException(nameof(enterprise));
            TimeStamp  = time;
            Header     = Header.Empty;
            Parameters = SecurityParameters.Create(community);
            var pdu = new TrapV2Pdu(
                requestId,
                enterprise,
                time,
                variables);

            Scope   = new Scope(pdu);
            Privacy = DefaultPrivacyProvider.DefaultPair;
            _bytes  = this.PackMessage(null).ToBytes();
        }
Beispiel #58
0
        /// <summary>
        /// Walks.
        /// </summary>
        /// <param name="version">Protocol version.</param>
        /// <param name="endpoint">Endpoint.</param>
        /// <param name="community">Community name.</param>
        /// <param name="table">OID.</param>
        /// <param name="list">A list to hold the results.</param>
        /// <param name="timeout">The time-out value, in milliseconds. The default value is 0, which indicates an infinite time-out period. Specifying -1 also indicates an infinite time-out period.</param>
        /// <param name="maxRepetitions">The max repetitions.</param>
        /// <param name="mode">Walk mode.</param>
        /// <param name="privacy">The privacy provider.</param>
        /// <param name="report">The report.</param>
        /// <returns></returns>
        public static int BulkWalk(VersionCode version, IPEndPoint endpoint, OctetString community, ObjectIdentifier table, IList <Variable> list, int timeout, int maxRepetitions, WalkMode mode, IPrivacyProvider privacy, ISnmpMessage report)
        {
            if (list == null)
            {
                throw new ArgumentNullException("list");
            }

            Variable         tableV = new Variable(table);
            Variable         seed   = tableV;
            IList <Variable> next;
            int          result  = 0;
            ISnmpMessage message = report;

            while (BulkHasNext(version, endpoint, community, seed, timeout, maxRepetitions, out next, privacy, ref message))
            {
                foreach (Variable v in next)
                {
                    string id = v.Id.ToString();
                    if (v.Data.TypeCode == SnmpType.EndOfMibView)
                    {
                        goto end;
                    }

                    if (mode == WalkMode.WithinSubtree &&
                        !id.StartsWith(table + ".", StringComparison.Ordinal))
                    {
                        // not in sub tree
                        goto end;
                    }

                    list.Add(v);

                    if (id.StartsWith(table + ".1.1.", StringComparison.Ordinal))
                    {
                        result++;
                    }
                }

                seed = next[next.Count - 1];
            }

end:
            return(result);
        }
 /// <inheritdoc />
 public virtual long SerializationIndexFromObjectIdentifier(ObjectIdentifier objectID)
 {
     return(Index++);
 }
Beispiel #60
-1
        //**********************************************************************
        /// <summary>
        /// Check the SNMP devices in the Devices.ini are available or not.
        /// If some devices are unavailable, the Devices.ini should be changed to give
        /// tester all available devices.
        /// Author: Sashimi.
        /// </summary>
        public static List<String> CheckSNMPDeviceAvailable(List<string> keyName)
        {
            List<string> notAvailable = new List<string>();
            // There are all devices in Device.ini.
            string groupName="SNMPDevices";
            //GXT_Ip_Port=10.146.88.10:163
            string keyName_IpPort = "SNMP_GXT_Ip_Port";
            string ipPort = myparseToValue(groupName,keyName_IpPort);
            string IP_Port = "";
            if(ipPort.IndexOf(":") != -1)
            {
                string[] spilt = ipPort.Split(':');
                IP_Port = spilt[0];
            }

            int timeout = 3;
            VersionCode version = VersionCode.V1;
            IPEndPoint endpoint = new IPEndPoint(IPAddress.Parse("1.1.1.1"),161);
            OctetString community = new OctetString("public");

            ObjectIdentifier objectId = new ObjectIdentifier("1.3.6.1.2.1.11.1.0");
            Variable var = new Variable(objectId);
            IList<Variable> varlist = new System.Collections.Generic.List<Variable>();
            varlist.Add(var);
            Variable data;
            IList<Variable> resultdata;

            foreach(string deviceIP in keyName){
                string strIP = myparseToValue(groupName,deviceIP);
                try
                {
                    if(!deviceIP.Equals("SNMP_GXT_Ip_Port"))
                        endpoint.Address = IPAddress.Parse(strIP);
                    else
                        endpoint.Address = IPAddress.Parse(IP_Port);
                     resultdata = Messenger.Get(version,endpoint,community,varlist,timeout);
                     data = resultdata[0];
                     Console.WriteLine("The device:" + deviceIP + "("+ strIP +")"+ " is availabe");
                }
                catch(Exception ex)
                {
                    notAvailable.Add(deviceIP);
                    Console.WriteLine("There is no device in this ip address."+ deviceIP + "("+ strIP +")!" );
                    string log = ex.ToString();
                    continue;
                }
            }

            return notAvailable;
        }