Example #1
0
        /// <summary>
        /// Performs update operations on mikrotik router.
        /// Items which are present in 'expected' and are not present in 'original' will be created on mikrotik router.
        /// Items which are present in both 'expected' and 'original' will be compared and updated (if are different - see <see cref="Field"/>, <see cref="WithKey"/>).
        /// Items which are not present in 'expected' and are present in 'original' will be deleted from mikrotik router.
        /// </summary>
        /// <returns>List of final entities on mikrotik router after save operation.</returns>
        public IEnumerable <TEntity> Save()
        {
            //TODO ensure all fields set
            List <TEntity> result = new List <TEntity>();
            Dictionary <string, TEntity> expectedDict = _expected.ToDictionary(_keyExtractor);
            Dictionary <string, TEntity> originalDict = _original.ToDictionary(_keyExtractor);

            //Delete
            foreach (var originalEntityPair in originalDict.Reverse()) //delete from end to begining of the list (just for better show in WinBox)
            {
                if (!expectedDict.ContainsKey(originalEntityPair.Key)) //present in original + not present in expected => delete
                {
                    _connection.Delete(originalEntityPair.Value);
                }
            }

            //Insert+Update
            var mergedFieldNames = ResolveFieldsFieldNames().ToArray();

            foreach (var expectedEntityPair in expectedDict.Reverse()) //from last to first ( <= move is indexed as moveBeforeEntity)
            {
                TEntity originalEntity;
                TEntity resultEntity;
                if (originalDict.TryGetValue(expectedEntityPair.Key, out originalEntity))
                {                                                                     //Update //present in both expected and original => update or NOOP
                  //copy .id from original to expected & save
                    if (!EntityFieldEquals(originalEntity, expectedEntityPair.Value)) //modified
                    {
                        UpdateEntityFields(originalEntity, expectedEntityPair.Value);
                        _connection.Save(originalEntity, mergedFieldNames);
                    }
                    resultEntity = originalEntity;
                }
                else
                { //Insert //present in expected and not present in original => insert
                    _connection.Save(expectedEntityPair.Value, mergedFieldNames);
                    resultEntity = expectedEntityPair.Value;
                }

                //Move entity to the right position
                if (_metadata.IsOrdered)
                {
                    if (result.Count > 0) // last one in the list (first taken) should be just added/leavedOnPosition and the next should be moved before the one which was added immediatelly before <=> result[0]
                    {
                        //TODO: only if is in different position
                        _connection.Move(resultEntity, result[0]); //before lastly added entity (foreach in reversed order)
                    }
                }

                result.Insert(0, resultEntity); //foreach in reversed order => put as first in result list
            }

            return(result);
        }
Example #2
0
        private static void AddFirewalFilter(ITikConnection connection)
        {
            var firewallFilter = new FirewallFilter()
            {
                Chain = FirewallFilter.ChainType.Forward,
                Action = FirewallFilter.ActionType.Accept,
            };

            connection.Save(firewallFilter);

            var loaded = connection.LoadAll<FirewallFilter>().First();
            loaded.Comment = "TEST";
            connection.Save(loaded);
        }
Example #3
0
        private static void AddFirewalFilter(ITikConnection connection)
        {
            var firewallFilter = new FirewallFilter()
            {
                Chain  = FirewallFilter.ChainType.Forward,
                Action = FirewallFilter.ActionType.Accept,
            };

            connection.Save(firewallFilter);

            var loaded = connection.LoadAll <FirewallFilter>().First();

            loaded.Comment = "TEST";
            connection.Save(loaded);
        }
Example #4
0
        private static void ModifyIpAccounting(ITikConnection connection)
        {
            var accounting = connection.LoadSingle <IpAccounting>();

            accounting.Threshold = 257;
            connection.Save(accounting);
        }
Example #5
0
 /// <summary>
 /// Update user with changed user
 /// </summary>
 /// <param name="user">The user to be updated</param>
 /// <returns>The status of the proccess</returns>
 public Task <bool> UpdateUserAsync(UserManagerUser user) => Task.Run(() =>
 {
     try
     {
         _connection.Save(user);
         return(true);
     }
     catch (Exception ex)
     {
         Console.WriteLine(ex.Message);
         return(false);
     }
 });
Example #6
0
        private static void CreateOrUpdateAddressList(ITikConnection connection)
        {
            var existingAddressList = connection.LoadList<FirewallAddressList>(
                connection.CreateParameter("list", listName),
                connection.CreateParameter("address", ipAddress)).SingleOrDefault();
            if (existingAddressList == null)
            {
                //Create
                var newAddressList = new FirewallAddressList()
                {
                    Address = ipAddress,
                    List = listName,
                };
                connection.Save(newAddressList);
            }
            else
            {
                //Update
                existingAddressList.Comment = "Comment update: " + DateTime.Now.ToShortTimeString();

                connection.Save(existingAddressList);
            }
        }
Example #7
0
        private static void CreateOrUpdateAddressList(ITikConnection connection)
        {
            var existingAddressList = connection.LoadList <FirewallAddressList>(
                connection.CreateParameter("list", listName),
                connection.CreateParameter("address", ipAddress)).SingleOrDefault();

            if (existingAddressList == null)
            {
                //Create
                var newAddressList = new FirewallAddressList()
                {
                    Address = ipAddress,
                    List    = listName,
                };
                connection.Save(newAddressList);
            }
            else
            {
                //Update
                existingAddressList.Comment = "Comment update: " + DateTime.Now.ToShortTimeString();

                connection.Save(existingAddressList);
            }
        }
Example #8
0
 public Task <bool> UpdateUserAsync(HotspotUser user)
 {
     return(Task.Run(() =>
     {
         try
         {
             _connection.Save(user);
             return true;
         }
         catch (Exception ex)
         {
             Console.WriteLine(ex.Message);
             return false;
         }
     }));
 }
Example #9
0
        private void btnDisplayChangePassword_Click(object sender, EventArgs e)
        {
            if (lbSec.SelectedItem == null)
            {
                return;
            }
            var dialog = new PasswordInputDialog(
                "Password for " + (lbSec.SelectedItem as CapsManSecurity).Comment,
                (lbSec.SelectedItem as CapsManSecurity).Passphrase);

            if (dialog.ShowDialog(this) == DialogResult.OK)
            {
                if (dialog.Password.Length >= 8)
                {
                    (lbSec.SelectedItem as CapsManSecurity).Passphrase = dialog.Password;
                    connection.Save(lbSec.SelectedItem as CapsManSecurity);
                }
                else
                {
                    MessageBox.Show("Password too short (min. 8 characters)!", "Notice", MessageBoxButtons.OK);
                }
            }
        }
Example #10
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);
            }
        }
Example #11
0
 private static void ModifyIpAccounting(ITikConnection connection)
 {
     var accounting = connection.LoadSingle<IpAccounting>();
     accounting.Threshold = 257;
     connection.Save(accounting);
 }
Example #12
0
        private static void FirewallMangleMerge(ITikConnection connection)
        {
            //manage just subset before rules marked with comment =START= and =END=

            //Create subset boundaries if not present
            const string startComment = "=START=";
            const string endComment = "=END=";
            var startMangle = connection.LoadSingleOrDefault<FirewallMangle>(connection.CreateParameter("comment", startComment));
            if (startMangle == null)
            {
                startMangle = new FirewallMangle()
                {
                    Chain = "forward",
                    Action = FirewallMangle.ActionType.Passthrough,
                    Comment = startComment,
                    Disabled = true,
                };
                connection.Save(startMangle);
            };
            var endMangle = connection.LoadSingleOrDefault<FirewallMangle>(connection.CreateParameter("comment", endComment));
            if (endMangle == null)
            {
                endMangle = new FirewallMangle()
                {
                    Chain = "forward",
                    Action = FirewallMangle.ActionType.Passthrough,
                    Comment = endComment,
                    Disabled = true,
                };
                connection.Save(endMangle);
            };

            //Merge subset between boundaries
            string unique = Guid.NewGuid().ToString();
            List<FirewallMangle> original = connection.LoadAll<FirewallMangle>().SkipWhile(m=>m.Comment != startComment).TakeWhile(m=>m.Comment != endComment)
                .Concat(new List<FirewallMangle> { endMangle})
                .ToList(); //just subset between =START= and =END= (not very elegant but functional and short ;-) )
            List<FirewallMangle> expected = new List<FirewallMangle>();
            expected.Add(startMangle);
            expected.Add(new FirewallMangle()
            {
                Chain = "forward",
                SrcAddress = "192.168.1.1",
                Action = FirewallMangle.ActionType.MarkPacket,
                NewPacketMark = "mark-001",
                Passthrough = false,
            });
            expected.Add(new FirewallMangle()
            {
                Chain = "forward",
                SrcAddress = "192.168.1.2",
                Action = FirewallMangle.ActionType.MarkPacket,
                NewPacketMark = "mark-002" + "-" +  unique,
                Passthrough = false,
            });
            expected.Add(new FirewallMangle()
            {
                Chain = "forward",
                SrcAddress = "192.168.1.3",
                Action = FirewallMangle.ActionType.MarkPacket,
                NewPacketMark = "mark-003",
                Passthrough = false,
                Comment = unique,
            });
            expected.Add(endMangle);

            connection.CreateMerge(expected, original)
                .WithKey(mangle => mangle.SrcAddress + ":" + mangle.Comment) //Use src-address as key
                .Field(q => q.Chain)
                .Field(q => q.SrcAddress) //Do not forget include also key fields !!!
                .Field(q => q.Action)
                .Field(q => q.NewPacketMark)
                .Field(q => q.Passthrough)
                .Field(q => q.Comment)
                .Save();
        }
Example #13
0
        private static void FirewallMangleMerge(ITikConnection connection)
        {
            //manage just subset before rules marked with comment =START= and =END=

            //Create subset boundaries if not present
            const string startComment = "=START=";
            const string endComment   = "=END=";
            var          startMangle  = connection.LoadSingleOrDefault <FirewallMangle>(connection.CreateParameter("comment", startComment));

            if (startMangle == null)
            {
                startMangle = new FirewallMangle()
                {
                    Chain    = "forward",
                    Action   = FirewallMangle.ActionType.Passthrough,
                    Comment  = startComment,
                    Disabled = true,
                };
                connection.Save(startMangle);
            }
            ;
            var endMangle = connection.LoadSingleOrDefault <FirewallMangle>(connection.CreateParameter("comment", endComment));

            if (endMangle == null)
            {
                endMangle = new FirewallMangle()
                {
                    Chain    = "forward",
                    Action   = FirewallMangle.ActionType.Passthrough,
                    Comment  = endComment,
                    Disabled = true,
                };
                connection.Save(endMangle);
            }
            ;

            //Merge subset between boundaries
            string unique = Guid.NewGuid().ToString();
            List <FirewallMangle> original = connection.LoadAll <FirewallMangle>().SkipWhile(m => m.Comment != startComment).TakeWhile(m => m.Comment != endComment)
                                             .Concat(new List <FirewallMangle> {
                endMangle
            })
                                             .ToList(); //just subset between =START= and =END= (not very elegant but functional and short ;-) )
            List <FirewallMangle> expected = new List <FirewallMangle>();

            expected.Add(startMangle);
            expected.Add(new FirewallMangle()
            {
                Chain         = "forward",
                SrcAddress    = "192.168.1.1",
                Action        = FirewallMangle.ActionType.MarkPacket,
                NewPacketMark = "mark-001",
                Passthrough   = false,
            });
            expected.Add(new FirewallMangle()
            {
                Chain         = "forward",
                SrcAddress    = "192.168.1.2",
                Action        = FirewallMangle.ActionType.MarkPacket,
                NewPacketMark = "mark-002" + "-" + unique,
                Passthrough   = false,
            });
            expected.Add(new FirewallMangle()
            {
                Chain         = "forward",
                SrcAddress    = "192.168.1.3",
                Action        = FirewallMangle.ActionType.MarkPacket,
                NewPacketMark = "mark-003",
                Passthrough   = false,
                Comment       = unique,
            });
            expected.Add(endMangle);

            connection.CreateMerge(expected, original)
            .WithKey(mangle => mangle.SrcAddress + ":" + mangle.Comment) //Use src-address as key
            .Field(q => q.Chain)
            .Field(q => q.SrcAddress)                                    //Do not forget include also key fields !!!
            .Field(q => q.Action)
            .Field(q => q.NewPacketMark)
            .Field(q => q.Passthrough)
            .Field(q => q.Comment)
            .Save();
        }
Example #14
0
        private IEnumerable <TEntity> SaveInternal(bool simulateOnly, out int insertCnt, out int updateCnt, out int deleteCnt, out int moveCnt)
        {
            insertCnt = 0;
            updateCnt = 0;
            deleteCnt = 0;
            moveCnt   = 0;

            //TODO ensure all fields set
            List <TEntity> result = new List <TEntity>();
            Dictionary <string, TEntity> expectedDict = _expected.ToDictionaryEx(_keyExtractor);
            Dictionary <string, TEntity> originalDict = _original.ToDictionaryEx(_keyExtractor);
            int idx = 0;
            Dictionary <string, int> originalIndexes = _original.ToDictionaryEx(_keyExtractor, i => idx++);

            //Delete
            foreach (var originalEntityPair in originalDict.Reverse()) //delete from end to begining of the list (just for better show in WinBox)
            {
                if (!expectedDict.ContainsKey(originalEntityPair.Key)) //present in original + not present in expected => delete
                {
                    if (_filterCallback(MergeOperation.Delete, originalEntityPair.Value, default(TEntity)))
                    {
                        if (!simulateOnly)
                        {
                            LogDml(MergeOperation.Delete, originalEntityPair.Value, default(TEntity));
                            _connection.Delete(originalEntityPair.Value);
                        }
                        deleteCnt++;
                    }
                }
            }

            //Insert+Update
            var mergedFieldNames   = ResolveFieldsFieldNames().ToArray();
            var insertedFieldNames = ResolveJustForInsertFieldNames().ToArray();

            foreach (var expectedEntityPair in expectedDict.Reverse()) //from last to first ( <= move is indexed as moveBeforeEntity)
            {
                TEntity originalEntity;
                TEntity resultEntity;
                if (originalDict.TryGetValue(expectedEntityPair.Key, out originalEntity))
                {                                                                     //Update //present in both expected and original => update or NOOP
                  //copy .id from original to expected & save
                    if (!EntityFieldEquals(originalEntity, expectedEntityPair.Value)) //modified
                    {
                        if (_filterCallback(MergeOperation.Update, originalEntity, expectedEntityPair.Value))
                        {
                            if (!simulateOnly)
                            {
                                LogDml(MergeOperation.Update, originalEntity, expectedEntityPair.Value);
                                UpdateEntityFields(originalEntity, expectedEntityPair.Value);
                                _connection.Save(originalEntity, mergedFieldNames);
                            }
                            updateCnt++;
                        }
                    }
                    resultEntity = originalEntity;
                }
                else
                { //Insert //present in expected and not present in original => insert
                    if (_filterCallback(MergeOperation.Insert, default(TEntity), expectedEntityPair.Value))
                    {
                        if (!simulateOnly)
                        {
                            LogDml(MergeOperation.Insert, default(TEntity), expectedEntityPair.Value);
                            _connection.Save(expectedEntityPair.Value, mergedFieldNames.Concat(insertedFieldNames));
                        }
                        insertCnt++;
                    }
                    resultEntity = expectedEntityPair.Value;
                }

                //Move entity to the right position
                if (_metadata.IsOrdered)
                {
                    if (result.Count > 0) // last one in the list (first taken) should be just added/leavedOnPosition and the next should be moved before the one which was added immediatelly before <=> result[0]
                    {
                        // only if is in different position (is not after result[0])
                        int resultEntityIdx, previousEntityIdx = -1;
                        if (!originalIndexes.TryGetValue(_keyExtractor(resultEntity), out resultEntityIdx) ||
                            !originalIndexes.TryGetValue(_keyExtractor(result[0]), out previousEntityIdx) ||
                            resultEntityIdx != previousEntityIdx - 1)
                        {
                            if (!simulateOnly)
                            {
                                LogMove(resultEntity, resultEntityIdx, previousEntityIdx);
                                _connection.Move(resultEntity, result[0]); //before lastly added entity (foreach in reversed order)
                            }
                            moveCnt++;
                        }
                    }
                }

                result.Insert(0, resultEntity); //foreach in reversed order => put as first in result list
            }

            return(result);
        }