Esempio n. 1
0
        void clickedOff(System.Object sender, System.EventArgs e)
        {
            try
            {
                using (ITikConnection connection = ConnectionFactory.CreateConnection(TikConnectionType.Api))
                {
                    connection.Open(ipAdress(), Login.Text, Password.Text);
                    ITikCommand cmd = connection.CreateCommand("/system/identity/print");
                    Console.WriteLine(cmd.ExecuteScalar());
                    var poe = connection.CreateCommand("/interface/ethernet/set");

                    foreach (string i in OptionsPage.numbers)
                    {
                        int numPort = Int32.Parse(i);
                        poe.AddParameter(TikSpecialProperties.Id, ports[numPort - 1]);
                        poe.AddParameter("poe-out", "off");
                        poe.AddParameter("disabled", "yes");
                        //Console.WriteLine("ports: " + ports[numPort]);
                        poe.ExecuteNonQuery();
                    }
                }
            }
            catch
            {
            }
        }
Esempio n. 2
0
        public void RunScript_Issue53_WillNotFail()
        {
            const string name            = "TEST_NAME_ISSUE53";
            const string scriptLines     = ":log info (\"start\") \r\n/ system identity print \r\n/ system identity print\r\n:log info (\"end\") ";
            const int    commandRowsCnt  = 2; // 2x call of / system identity print
            ITikCommand  scriptCreateCmd = Connection.CreateCommandAndParameters("/system/script/add",
                                                                                 "name", name,
                                                                                 "source", scriptLines);
            var id = scriptCreateCmd.ExecuteScalar();

            try
            {
                //run via ID
                ITikCommand scriptRunCmd = Connection.CreateCommand("/system/script/run",
                                                                    Connection.CreateParameter(TikSpecialProperties.Id, id, TikCommandParameterFormat.NameValue));
                var responseRows = scriptRunCmd.ExecuteList();
                Assert.IsTrue(responseRows.Count() == commandRowsCnt); //one empty !re row per script line command

                ////run via number
                //ITikCommand scriptRunCmd1 = Connection.CreateCommand("/system/script/run",
                //    Connection.CreateParameter("number", "0", TikCommandParameterFormat.NameValue));
                //var responseRows1 = scriptRunCmd1.ExecuteList();
                //Assert.IsTrue(responseRows1.Count() == commandRowsCnt); //one empty !re row per script line command
            }
            finally
            {
                Connection.CreateCommandAndParameters("/system/script/remove", TikSpecialProperties.Id, id).ExecuteNonQuery();
            }
        }
Esempio n. 3
0
 private void materialFlatButton1_Click(object sender, EventArgs e)
 {
     using (ITikConnection connection = ConnectionFactory.CreateConnection(TikConnectionType.Api))
     {
         connection.Open("192.168.0.1", "admin", "yami_yonatan");
         ITikCommand cmd = connection.CreateCommand("ip/neighbor/print");
         MessageBox.Show(cmd.ExecuteScalar());
     }
 }
Esempio n. 4
0
        private static void Identity(ITikConnection connection)
        {
            ITikCommand cmd      = connection.CreateCommand("/system/identity/print");
            var         identity = cmd.ExecuteScalar(); //cmd.ExecuteSIngleRow()

            Console.WriteLine("Identity: " + /*identity.GetResponseField("name")*/ identity);

            Console.WriteLine("Press ENTER");
            Console.ReadLine();
        }
Esempio n. 5
0
        private static void OpenConnectionAndExecuteSimpleCommand(TikConnectionType connectionType, string host, string user, string pass)
        {
            using (var connection = CreateOpenedConnection(connectionType, host, user, pass))
            {
                ITikCommand readCmd          = connection.CreateCommand("/system/identity/print");
                var         originalIdentity = readCmd.ExecuteScalar();

                Assert.IsNotNull(originalIdentity);

                connection.Close();
            }
        }
Esempio n. 6
0
        public void ConnectionEncodingWorksCorrectly()
        {
            Connection.Encoding = Encoding.GetEncoding("windows-1250");
            ITikCommand readCmd          = Connection.CreateCommand("/system/identity/print");
            var         originalIdentity = readCmd.ExecuteScalar();

            //modify
            const string testStringWithExoticCharacters = "Příliš žluťoučký kůň úpěl ďábelské ódy.";
            ITikCommand  setCmd = Connection.CreateCommand("/system/identity/set");

            setCmd.AddParameterAndValues("name", testStringWithExoticCharacters);
            setCmd.ExecuteNonQuery();

            //read modified
            var newIdentity = readCmd.ExecuteScalar();

            Assert.AreEqual(testStringWithExoticCharacters, newIdentity);

            //cleanup
            setCmd.Parameters.Clear();
            setCmd.AddParameterAndValues("name", originalIdentity);
            setCmd.ExecuteNonQuery();
        }
Esempio n. 7
0
        public void ConnectionEncodingWorksCorrectly()
        {
            using (var connection = ConnectionFactory.OpenConnection(TikConnectionType.ApiSsl, ConfigurationManager.AppSettings["host"], ConfigurationManager.AppSettings["user"], ConfigurationManager.AppSettings["pass"]))
            {
                connection.Encoding = Encoding.GetEncoding("windows-1250");
                ITikCommand readCmd          = connection.CreateCommand("/system/identity/print");
                var         originalIdentity = readCmd.ExecuteScalar();

                //modify
                const string testStringWithExoticCharacters = "Příliš žluťoučký kůň úpěl ďábelské ódy.";
                ITikCommand  setCmd = connection.CreateCommand("/system/identity/set");
                setCmd.AddParameterAndValues("name", testStringWithExoticCharacters);
                setCmd.ExecuteNonQuery();

                //read modified
                var newIdentity = readCmd.ExecuteScalar();
                Assert.AreEqual(testStringWithExoticCharacters, newIdentity);

                //cleanup
                setCmd.Parameters.Clear();
                setCmd.AddParameterAndValues("name", originalIdentity);
                setCmd.ExecuteNonQuery();
            }
        }
Esempio n. 8
0
        public void ConnectionSendTagWithSyncCommandDisabled_WorksCorrectly()
        {
            using (var connection = OpenConnection())
            {
                connection.SendTagWithSyncCommand = false;
                List <string> sentWords = new List <string>();
                connection.OnWriteRow += (e, args) =>
                {
                    sentWords.Add(args.Word);
                };

                ITikCommand readCmd = connection.CreateCommand("/system/identity/print");
                readCmd.ExecuteScalar();

                Assert.IsFalse(sentWords.Any(w => w.StartsWith(TikSpecialProperties.Tag)));
            }
        }
Esempio n. 9
0
        public void ConnectionSendTagWithSyncCommandDisabled_WorksCorrectly()
        {
            using (var connection = ConnectionFactory.OpenConnection(TikConnectionType.ApiSsl, ConfigurationManager.AppSettings["host"], ConfigurationManager.AppSettings["user"], ConfigurationManager.AppSettings["pass"]))
            {
                connection.SendTagWithSyncCommand = false;
                List <string> sentWords = new List <string>();
                connection.OnWriteRow += (e, args) =>
                {
                    sentWords.Add(args.Word);
                };

                ITikCommand readCmd = connection.CreateCommand("/system/identity/print");
                readCmd.ExecuteScalar();

                Assert.IsFalse(sentWords.Any(w => w.StartsWith(TikSpecialProperties.Tag)));
            }
        }
Esempio n. 10
0
 void ButtonClickedConnect(System.Object sender, System.EventArgs e)
 {
     try
     {
         using (ITikConnection connection = ConnectionFactory.CreateConnection(TikConnectionType.Api))
         {
             connection.Open(ipAdress(), Login.Text, Password.Text);
             ITikCommand cmd = connection.CreateCommand("/system/identity/print");
             Console.WriteLine(cmd.ExecuteScalar());
             if (connection.IsOpened)
             {
                 ConnectionStatus.Text   = "OK";
                 buttonOn.IsVisible      = true;
                 buttonOff.IsVisible     = true;
                 ToOptionsPage.IsVisible = true;
                 buttonClear.Text        = "CANCEL";
                 IP_adress_1.IsEnabled   = false;
                 IP_adress_2.IsEnabled   = false;
                 IP_adress_3.IsEnabled   = false;
                 IP_adress_4.IsEnabled   = false;
                 Login.IsEnabled         = false;
                 Password.IsEnabled      = false;
                 buttonConnect.IsEnabled = false;
                 var poe_status = connection.LoadList <InterfaceEthernet>();
                 int portNum    = 0;
                 foreach (InterfaceEthernet interfaceEthernet in poe_status)
                 {
                     ports.Add(portNum, interfaceEthernet.Name);
                     portNum++;
                 }
                 //Console.WriteLine("Имя порта ", ports[0]); // имя порта
                 Console.WriteLine(ports.Keys.Count); // количество портов
             }
         }
     }
     catch (Exception ex)
     {
         //Console.WriteLine("Exception: " + ex.Message);
         ConnectionStatus.Text = ex.Message;
     }
 }
Esempio n. 11
0
        public static bool Mikrotik()

        {
            using (ITikConnection connection = ConnectionFactory.CreateConnection(TikConnectionType.Api)) // Use TikConnectionType.Api for mikrotikversion prior v6.45
            {
                connection.Open("10.19.20.1", "OrionAdmin", "Frank1e2015");
                ITikCommand cmd      = connection.CreateCommand("/system/identity/print");
                var         identity = cmd.ExecuteScalar();
                Console.WriteLine("Identity: {0}", identity);
                var logs = connection.LoadList <Log>();
                foreach (Log log in logs)
                {
                    Console.WriteLine("{0}[{1}]: {2}", log.Time, log.Topics, log.Message);
                }
                var firewallFilter = new FirewallFilter()
                {
                    Chain  = FirewallFilter.ChainType.Forward,
                    Action = FirewallFilter.ActionType.Accept,
                };
                connection.Save(firewallFilter);
                ITikCommand torchCmd = connection.CreateCommand("/tool/torch",
                                                                connection.CreateParameter("interface", "ether1"),
                                                                connection.CreateParameter("port", "any"),
                                                                connection.CreateParameter("src-address", "0.0.0.0/0"),
                                                                connection.CreateParameter("dst-address", "0.0.0.0/0"));

                torchCmd.ExecuteAsync(response =>
                {
                    Console.WriteLine("Row: " + response.GetResponseField("tx"));
                });
                Console.WriteLine("Press ENTER");
                Console.ReadLine();
                torchCmd.Cancel();
                return(true);
            }
        }
Esempio n. 12
0
        /// <summary>
        /// Saves entity to mikrotik router. Does insert (/add) whan entity has empty id and update(/set + /unset) when id is present).
        /// Behavior of save is modified via <see cref="TikPropertyAttribute"/> on properties.
        /// See <see cref="TikPropertyAttribute.DefaultValue"/>, <see cref="TikPropertyAttribute.UnsetOnDefault"/>.
        /// </summary>
        /// <typeparam name="TEntity">Saved entitie type.</typeparam>
        /// <param name="connection">Tik connection used to save.</param>
        /// <param name="entity">Saved entity.</param>
        /// <param name="usedFieldsFilter">List of field names (on mikrotik) which should be modified. If is not null, only listed fields will be modified.</param>
        public static void Save <TEntity>(this ITikConnection connection, TEntity entity, IEnumerable <string> usedFieldsFilter = null)
            where TEntity : new()
        {
            var metadata = TikEntityMetadataCache.GetMetadata <TEntity>();

            EnsureNotReadonlyEntity(metadata);

            string id;

            if (metadata.IsSingleton)
            {
                id = null;
            }
            else
            {
                EnsureHasIdProperty(metadata);
                id = metadata.IdProperty.GetEntityValue(entity);
            }

            if (!metadata.IsSingleton && string.IsNullOrEmpty(id))
            {
                //create
                ITikCommand createCmd = connection.CreateCommand(metadata.EntityPath + "/add", TikCommandParameterFormat.NameValue);

                foreach (var property in metadata.Properties
                         .Where(pm => !pm.IsReadOnly)
                         .Where(pm => usedFieldsFilter == null || usedFieldsFilter.Contains(pm.FieldName, StringComparer.OrdinalIgnoreCase)))
                {
                    if (!property.HasDefaultValue(entity))
                    {
                        createCmd.AddParameter(property.FieldName, property.GetEntityValue(entity));
                    }
                }

                id = createCmd.ExecuteScalar();
                if (metadata.HasIdProperty)
                {
                    metadata.IdProperty.SetEntityValue(entity, id); // update saved id into entity
                }
            }
            else
            {
                //update (set+unset)
                ITikCommand setCmd = connection.CreateCommand(metadata.EntityPath + "/set", TikCommandParameterFormat.NameValue);

                if (!metadata.IsSingleton && usedFieldsFilter == null)
                {
                    //compare state on mikrotik and update different fields only
                    var unmodifiedEntity = connection.LoadById <TEntity>(id); //TODO some kind of "loaded entities" session cache could be used to avoid another load before save.
                    usedFieldsFilter = entity.GetDifferentFields(unmodifiedEntity);
                }

                List <string> fieldsToUnset = new List <string>();

                foreach (var property in metadata.Properties
                         .Where(pm => !pm.IsReadOnly)
                         .Where(pm => usedFieldsFilter == null || usedFieldsFilter.Contains(pm.FieldName, StringComparer.OrdinalIgnoreCase)))
                {
                    if (property.HasDefaultValue(entity) && property.UnsetOnDefault)
                    {
                        fieldsToUnset.Add(property.FieldName);
                    }
                    else
                    {
                        setCmd.AddParameter(property.FieldName, property.GetEntityValue(entity)); //full update (all values)
                    }
                }

                if (fieldsToUnset.Count > 0)
                {
                    // this should also work (see http://forum.mikrotik.com/viewtopic.php?t=28821 )
                    //ip/route/unset
                    //=.id = *1
                    //= value-name=routing-mark

                    foreach (string fld in fieldsToUnset)
                    {
                        ITikCommand unsetCmd = connection.CreateCommand(metadata.EntityPath + "/unset", TikCommandParameterFormat.NameValue);
                        unsetCmd.AddParameter(TikSpecialProperties.Id, id, TikCommandParameterFormat.NameValue);
                        unsetCmd.AddParameter(TikSpecialProperties.UnsetValueName, fld);

                        unsetCmd.ExecuteNonQuery();
                    }
                }
                if (setCmd.Parameters.Any())
                {
                    if (!metadata.IsSingleton)
                    {
                        setCmd.AddParameter(TikSpecialProperties.Id, id, TikCommandParameterFormat.NameValue);
                    }
                    setCmd.ExecuteNonQuery();
                }
            }
        }