public void TestObserveCollectionChanged()
        {
            // 被観測者, 観測者を生成します
            var modelList = new ModelList <int>()
            {
                1, 2, 3
            };
            var observer = new Observer <NotifyCollectionChangedEventArgs>();

            // イベントを購読します
            var subscription =
                modelList
                .ObserveCollectionChanged()
                .Subscribe(observer.OnObservedEvent);

            observer.Subscriptions.Add(subscription);

            // イベントを送受信することで, 以上の動作を確認します
            modelList.Add(8);
            Assert.That(observer.LastEventArgs.Action, Is.EqualTo(NotifyCollectionChangedAction.Add));

            // イベント購読を解除します
            observer.Subscriptions.Dispose();

            // イベントを受信できないことで, 以上の動作を確認します
            observer.LastEventArgs = null;
            modelList.Add(16);
            Assert.That(observer.LastEventArgs, Is.Null);
        }
        public MainPage()
        {
            this.InitializeComponent();

            var entriesView = entries.CreateView(
                x => new
            {
                Source      = x,
                Description = x.Description,
                Points      = x.Points,
                Date        = x.Date.ToString("dd MMM"),
            },
                x => x.Source
                );

            HistoryItems.ItemsSource  = entriesView;
            TemplateItems.ItemsSource = templates;
            BountyItems.ItemsSource   = bounties;

            TotalScore.DataContext      = entries.DeriveObservableProperty(es => es.Sum(e => e.Points));
            TotalScoreToday.DataContext = entries.DeriveObservableProperty(es =>
                                                                           es.Where(e => e.Date.Date.Equals(DateTime.Now.Date))
                                                                           .Sum(e => e.Points));

            AddTemplateStream.Subscribe(x =>
            {
                templates.Add(x);
                NewTemplateDescription.Text = String.Empty;
                NewTemplatePoints.Text      = "0";
            });
            DeleteTemplateStream.Subscribe(template => templates.Remove(template));
            AddEntryStream.Subscribe(x =>
            {
                entries.Add(x);
                NewEntryDescription.Text = String.Empty;
                NewEntryPoints.Text      = "0";
            });

            DeleteEntryStream.Subscribe(x => entries.Remove(x));

            AddBountyStream.Subscribe(bounty =>
            {
                bounties.Add(bounty);
                NewBountyDescription.Text = String.Empty;
                NewBountyPoints.Text      = "0";
            });
            CompleteBountyStream.Subscribe(bounty =>
            {
                entries.Add(new Entry
                {
                    Points      = bounty.Points,
                    Description = bounty.Description,
                });
                bounties.Remove(bounty);
            });
            DeleteBountyStream.Subscribe(bounty => bounties.Remove(bounty));
        }
Beispiel #3
0
        private void RuleChecker(string line)
        {
            int    modelNameEnd = line.IndexOf("(");
            string TypeOfModel  = line.Substring(0, modelNameEnd);

            //browsking apriopriate model
            // Trzeba się zastanowic nad leszym sposobem na identyfikację mało uniwersalny
            if (TypeOfModel == _config._elementsNamesLanguageConfig.SimpleModel)
            {
                ModelList.Add(SimpleModel(line));
            }
            else if (TypeOfModel == _config._elementsNamesLanguageConfig.ExtendedModel)
            {
                ModelList.Add(ExtendedModel(line));
            }
            else if (TypeOfModel == _config._elementsNamesLanguageConfig.LinearModel)
            {
                ModelList.Add(LinearModel(line));
            }
            else if (TypeOfModel == _config._elementsNamesLanguageConfig.PolyModel)
            {
                ModelList.Add(PolyModel(line));
            }
            else if (TypeOfModel == _config._elementsNamesLanguageConfig.Argument)
            {
                ArgumentList.Add(ReturnArgument(line));
            }
            else if (TypeOfModel == _config._elementsNamesLanguageConfig.ModelFact)
            {
                _modelFactsList.Add(ModelFact(line));
            }
        }
Beispiel #4
0
 /// <summary>
 /// モデルを追加する
 /// </summary>
 /// <param name="model"></param>
 private void AddModel(LiplisModel model)
 {
     //TODO CtrlModelController AddModel 登録キーチェックすべきか?
     TableModel.Add(model.ModelName, model);
     TableModelId.Add(model.AllocationId, model);
     ModelList.Add(model);
 }
Beispiel #5
0
        /// <summary>
        /// 执行指定SQL的命令,返回数据字典集合
        /// </summary>
        /// <param name="transaction">一个有效的连接事务</param>
        /// <param name="cmdType">命令类型 (存储过程,命令文本或其它)</param>
        /// <param name="cmdText">存储过程名称或SQL语句</param>
        /// <param name="parms">分配给命令的SqlParamter参数数组</param>
        /// <returns>返回指定列数据字典集合</returns>
        public static ModelList ExecuteList(SqlTransaction trans, CommandType cmdType, string cmdText, params SqlParameter[] parms)
        {
            QueryCount++;

            SqlCommand cmd = new SqlCommand();

            using (SqlConnection conn = new SqlConnection(CONNECTIONSTRING))
            {
                PrepareCommand(cmd, conn, trans, cmdType, cmdText, parms);
                using (SqlDataReader rdr = cmd.ExecuteReader())
                {
                    if (rdr.HasRows)
                    {
                        ModelList list = new ModelList();
                        do
                        {
                            while (rdr.Read())
                            {
                                Model model = new Model();
                                for (int i = 0; i < rdr.FieldCount; i++)
                                {
                                    model.Add(rdr.GetName(i), rdr[i].ToString());
                                }
                                list.Add(model);
                            }
                        } while (rdr.NextResult());
                        return(list);
                    }
                    else
                    {
                        return(null);
                    }
                }
            }
        }
Beispiel #6
0
        public Tiles(string dbUrl) : base(dbUrl)
        {
            // API only available to authenticated users
            BeforeAsync = async(p, c) => await c.EnsureIsAuthenticatedAsync();

            GetAsync["/"] = async(p, c) =>
            {
                var res      = new ModelList <Tile>();
                var authUser = await c.GetAuthenticatedUserAsync();

                var filterAuth = (new Tile()).FilterAuthUser(authUser);
                using (DB db = await DB.CreateAsync(dbUrl))
                {
                    var result = await Model.SearchAsync <Tile>(db, c, filterAuth);

                    foreach (var tile in result.Data)
                    {
                        if (await tile.GetRightsAsync(c) != TileRightType.None)
                        {
                            res.Add(tile);
                        }
                    }
                }
                c.Response.StatusCode = 200;
                c.Response.Content    = res.ToJson();
            };
        }
Beispiel #7
0
        public void AddModels(ModelFromFile fromFile, bool isNew)//(string fileName,byte[] data)
        {
            if (!availableModel)
            {
                availableGCode = false;
                gCode          = "";
                GCodeChange(gCode);
                InitSlicerView();
            }
            availableModel = true;
            IsChanged      = true;
            PrintModel model = new PrintModel(control, fromFile);

            model.Load(fromFile.Name, fromFile.Data);
            model.update();
            if (isNew)
            {
                model.Center(SettingsProvider.Instance.Printer_Settings.PrintAreaWidth / 2, SettingsProvider.Instance.Printer_Settings.PrintAreaDepth / 2);
                model.Land();
            }
            ModelList.Add(model);
            if (model.ActiveModel.triangles.Count > 0)
            {
                PreView.models.AddLast(model);

                if (isNew)
                {
                    Allocate(model);
                    model.addAnimation(new DropAnimation("drop"));
                }

                updateSTLState(model);
            }
        }
Beispiel #8
0
        private void CreateIPCameraHandlers()
        {
            var i = 0;

            while (i < 4)
            {
                ModelList.Add(new IpCameraHandler());
                i++;
            }
        }
        void ConnectButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (ConnectModel == null || _connecting)
                {
                    return;
                }

                if (CurrentModel == null)
                {
                    CurrentModel = GetCurrentModel((CameraDeviceInfo)CameraDevicesCombo.SelectedItem);
                }

                if (CurrentModel == null ||
                    (!String.IsNullOrEmpty(CurrentModel.CameraState) && !CurrentModel.CameraState.Equals("Disconnected")))
                {
                    return;
                }

                if (CurrentModel is IpCameraEngine)
                {
                    if (!IsSavedCamera(CurrentModel))
                    {
                        CurrentModel = new IpCameraEngine(CameraAddress, UserName, Password);
                    }
                    //else
                    //    CurrentModel = GetSavedCamera(CurrentModel).Camera;
                }

                AddCamera(CurrentModel);
                WireUpCameraEvents(CurrentModel);

                if (CurrentModel.CameraError != null && CurrentModel.CameraError.ToUpper().Contains("LOST"))
                {
                    CurrentModel.CameraError = String.Empty;
                }

                CurrentModel.Connect();
                _connecting = true;

                StartViewer(CurrentModel);

                Server.Model = CurrentModel;

                if (CurrentModel.CameraStreams == null)
                {
                    ModelList.Add(CurrentModel);
                }
            }
            catch
            {
            }
        }
Beispiel #10
0
        public bool Insert(ProductParameter model)
        {
            long id = _productParameterService.InsertBigIdentity(model);

            if (id > 0)
            {
                model.id = (int)id;
                ModelList.Add(model);
                AddTreeNode(model);
                return(true);
            }
            return(false);
        }
Beispiel #11
0
        private void btnAdd_Click(object sender, EventArgs e)
        {
            int markID = Convert.ToInt32(cbMark.SelectedValue);

            Model         model        = new Model(markID);
            Model_AddEdit modelAddEdit = new Model_AddEdit(model);

            if (modelAddEdit.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                ModelList models = ModelList.getInstance();
                models.Add(model);

                loadModel();
            }
        }
        /// <summary>
        /// Calls the add handler, returns the list model that it creates.
        /// </summary>
        /// <returns></returns>
        protected TListModel AddListModel()
        {
            TListModel result = null;

            if (AddHandler != null)
            {
                result = AddHandler();
                if (result != null)
                {
                    ModelList.Add(result);
                    Control.SelectedRecord = result;
                }
            }

            return(result);
        }
Beispiel #13
0
        //ROUTED FROM StarMain TO STORE PROJECT MODELS IN ModelList LIST
        //TO BE DISPLAYED IN UserInput USING Models_ComboBox
        public static void GetCurrModels()
        {
            foreach (Model model in DocModel)
            {
                ModelList.Add(model.RootItem.DisplayName);
            }

            foreach (Model model in DocModel)
            {
                ModelItem root = model.RootItem as ModelItem;
                foreach (ModelItem item in root.Children)
                {
                    ModelList.Add(item.DisplayName);
                }
            }
        }
Beispiel #14
0
        /// <summary>
        /// 加载所有
        /// </summary>
        /// <param name="user_tyepe"></param>
        public void LoadAllModels(int user_tyepe = -1)
        {
            ModelList.Clear();
            List <SystemUser> users = new List <SystemUser>();

            if (user_tyepe > 0)
            {
                users = userService.QueryableToList(x => x.id > 0 && x.user_type == user_tyepe);
            }
            else
            {
                users = userService.QueryableToList(x => x.id > 0);
            }
            foreach (var item in users)
            {
                ModelList.Add(item);
            }
        }
        public virtual void AddModel(IModel model)
        {
            Type type = model.GetType();

            if (typeof(IValueModel).IsAssignableFrom(type))
            {
                m_ValueModel = (IValueModel)model;
            }
            else
            {
                if (m_ModelList == null)
                {
                    m_ModelList = new ModelList();
                }

                m_ModelList.Add(model);
            }
        }
Beispiel #16
0
        internal async Task LoadViewModelAsync(ViewModelBase vm)
        {
            if (vm == null)
            {
                return;
            }

            if (!_viewModelsLoaded.Contains(vm))
            {
                // Call load state on the sub-viewmodel once its requested to be set to curent.
                await vm.LoadStateAsync(this.View, _loadState);

                _viewModelsLoaded.Add(vm);
            }
            else
            {
                await vm.RefreshAsync(false);
            }
        }
Beispiel #17
0
        public void LoadAllInfos()
        {
            ModelTrees.Clear();
            ModelList.Clear();
            var list = _productParameterService.QueryableToList(x => x.id > 0).OrderBy(x => x.product_name).ToList();

            if (list != null && list.Count > 0)
            {
                foreach (var item in list)
                {
                    ModelList.Add(item);
                    AddTreeNode(item);
                }
                EditModel = list[0];
            }
            else
            {
                EditModel = new ProductParameter();
            }
        }
        async Task <ModelList <RecipientUser> > GetRecipientsMessagesAsync(DB db, Publipostage item)
        {
            var recipients = await GetRecipientsAsync(db, item);

            var compactRecipients = new ModelList <RecipientUser>();

            // generate HTML message for all recipients
            foreach (var recipient in recipients)
            {
                GenerateHtmlMessage(item.message, recipient);
            }
            // if a recipient user will received several times the same message remove the duplicates
            foreach (var recipient in recipients)
            {
                if (!compactRecipients.Any((arg) => (arg.user.id == recipient.user.id) && (arg.message == recipient.message)))
                {
                    compactRecipients.Add(recipient);
                }
            }
            return(compactRecipients);
        }
		/// <summary>
		/// Gets the templatize models.
		/// </summary>
		/// <returns>
		/// The templatize models.
		/// </returns>
		public ModelList<Model> getTemplatizeModels() {
			Assembly[] assemblies = this.getAssemblies();
			ModelList<Model> models = new ModelList<Model>();
			Model auxModel = new Model();
			Type[] modelType = new Type[1];
			modelType[0] = typeof(Model);
			
			for(int i = 0; i < assemblies.Length; i++) {
				Type[] types = assemblies[i].GetTypes();
				for(int j = 0; j < types.Length; j++) {
					//types[j].ba
					if(types[j].IsGenericType == false && this.isChildOf(types[j], typeof(Orm.Model))) {
					//if(types[j].GetNestedType("AltairStudios.Core.Orm.Model") != null) {
					//if(types[j].Namespace != null && (types[j].Namespace == "AltairStudios.Core.Orm.Models" || types[j].Namespace.EndsWith(".Model"))) {
						models.Add(auxModel.cast<Model>(Activator.CreateInstance(types[j])));
					}
				}
			}
			
			return models;
		}
Beispiel #20
0
        public virtual ModelContainer AddModel(IModel model)
        {
            if (model == null)
            {
                throw new ArgumentNullException();
            }
            Type type = model.GetType();

            if (typeof(IValueModel).IsAssignableFrom(type))
            {
                m_ValueModel = (IValueModel)model;
            }
            else
            {
                if (m_ModelList == null)
                {
                    m_ModelList = new ModelList();
                }

                m_ModelList.Add(model);
            }
            return(this);
        }
Beispiel #21
0
 private void InitModelList()
 {
     foreach (var(_, value) in BindAiSvc.AiDic)
     {
         ModelList.Add(new ScheduleDoModel()
         {
             Interval = PicCleanFreq * 1000,
             Data     = new CacheCleanerDTO
             {
                 Path          = value.ImagePath,
                 IsCascading   = false,
                 MaxCacheCount = MaxPicCache
             }
         });
         ModelList.Add(new ScheduleDoModel()
         {
             Interval = SchedulerTimer.DairlyInterval,
             Data     = new CacheCleanerDTO
             {
                 Path          = value.LogPath,
                 IsCascading   = false,
                 MaxCacheCount = 7
             }
         });
         ModelList.Add(new ScheduleDoModel()
         {
             Interval = SchedulerTimer.HourlyInterval / 2,
             Data     = new CacheCleanerDTO
             {
                 Path          = value.VoicePath,
                 IsCascading   = false,
                 MaxCacheCount = 50
             }
         });
     }
 }
Beispiel #22
0
        async Task <(ModelList <SmsUser>, bool)> GetSmsResultAsync(ModelList <SmsUser> targets)
        {
            var hasNull = false;
            var result  = new ModelList <SmsUser>();

            if (targets.Count <= 50)
            {
                var res = await GetSmsResultMax50Async(targets);

                result.AddRange(res.Item1);
                if (res.Item2)
                {
                    hasNull = true;
                }
            }
            else
            {
                var pos = 0;
                while (pos < targets.Count)
                {
                    var limitedTargets = new ModelList <SmsUser>();
                    for (var i = 0; i < 50 && (pos < targets.Count); i++, pos++)
                    {
                        limitedTargets.Add(targets[pos]);
                    }
                    var res = await GetSmsResultMax50Async(limitedTargets);

                    result.AddRange(res.Item1);
                    if (res.Item2)
                    {
                        hasNull = true;
                    }
                }
            }
            return(result, hasNull);
        }
Beispiel #23
0
        private void CheckFirewall()
        {
            AresChannel channel = null;
            DateTime    now     = DateTime.Now;

            lock (Channels)
                channel = Channels.Find((s) => !s.ExternalIp.IsLocalAreaNetwork() && now.Subtract(s.LastAskedFirewall).TotalMinutes > 5);

            if (channel != null)
            {
                channel.LastAskedFirewall = now;
                IPAddress ip = channel.ExternalIp;

                lock (myfirewalltests) myfirewalltests.Add(channel);

                socket.SendAsync(
                    new CheckFirewallWanted(channel.Port),
                    new IPEndPoint(ip, channel.Port));
            }
            else
            {
                TestingFirewall = false;
            }
        }
Beispiel #24
0
        private void HandleUdpPacket(PacketEventArgs e)
        {
            if (CheckBanned(e.RemoteEndPoint.Address))
            {
                return;
            }

            switch ((AresUdpId)e.Packet.Id)
            {
            case AresUdpId.OP_SERVERLIST_ACKINFO: {
                AckInfo info = (AckInfo)e.Packet;

                AckInfoHits++;
                lastackinfo = DateTime.Now;

                AresChannel channel = FindChannel(e.RemoteEndPoint.Address, info.Port);

                if (channel == null)
                {
                    channel = FindLocalChannel(e.RemoteEndPoint.Address);
                }

                if (channel == null)
                {
                    return;
                }

                channel.Port     = info.Port;
                channel.Users    = info.Users;
                channel.Name     = info.Name;
                channel.Topic    = info.Topic;
                channel.Language = info.Language;
                channel.Version  = info.Version;

                ParseServers(info.Servers);
            }
            break;

            case AresUdpId.OP_SERVERLIST_ADDIPS: {
                AddIps add = (AddIps)e.Packet;

                AddIpHits++;

                AresChannel channel = FindChannel(e.RemoteEndPoint.Address, add.Port);

                if (channel != null)
                {
                    channel.Port = add.Port;
                }
                else
                {
                    var address = e.RemoteEndPoint.Address;

                    if (e.RemoteEndPoint.Address.IsLocalAreaNetwork())
                    {
                        address = ExternalIp ?? address;
                    }

                    channel = new AresChannel(address, add.Port);
                    Channels.Add(channel);
                }

                uint num = 6;
                ParseServers(add.Servers);

                socket.SendAsync(new AckIps()
                    {
                        Port    = channel.Port,
                        Servers = GetSendServers(server.ExternalIp, ref num),
                    }, e.RemoteEndPoint);
            }
            break;

            case AresUdpId.OP_SERVERLIST_ACKIPS: {
                AckIps ips = (AckIps)e.Packet;

                AckIpHits++;

                AresChannel channel = FindChannel(e.RemoteEndPoint.Address, ips.Port);

                if (channel != null)
                {
                    channel.Port = ips.Port;
                    channel.AckCount++;
                    channel.TryCount  = 0;
                    channel.LastAcked = DateTime.Now;
                }

                ParseServers(ips.Servers);
            }
            break;

            case AresUdpId.OP_SERVERLIST_CHECKFIREWALLBUSY: {
                CheckFirewallBusy busy = (CheckFirewallBusy)e.Packet;

                lock (myfirewalltests)
                    myfirewalltests.RemoveAll((s) => s.ExternalIp.Equals(e.RemoteEndPoint.Address));

                ParseServers(busy.Servers);
            }
            break;

            case AresUdpId.OP_SERVERLIST_PROCEEDCHECKFIREWALL: {
                CheckFirewall check = (CheckFirewall)e.Packet;
                FirewallTest  test  = null;

                lock (firewalltests)
                    test = firewalltests.Find(s => s.GetHashCode() == check.Token);

                if (test != null)
                {
                    test.RemoteEndPoint.Port = check.Port;
                    test.Begin();
                }
            }
            break;

            case AresUdpId.OP_SERVERLIST_READYTOCHECKFIREWALL: {
                CheckFirewallReady ready = (CheckFirewallReady)e.Packet;

                if (!ready.Target.IsLocalAreaNetwork())
                {
                    ExternalIp = ready.Target;
                    //Console.Write()
                    socket.SendAsync(new CheckFirewall()
                        {
                            Port  = (ushort)socket.LocalEndPoint.Port,
                            Token = ready.Token,
                        }, e.RemoteEndPoint);
                }
            }
            break;

            case AresUdpId.OP_SERVERLIST_WANTCHECKFIREWALL: {
                CheckFirewallWanted want = (CheckFirewallWanted)e.Packet;

                CheckFirewallHits++;

                if (firewalltests.Count < 5)
                {
                    FirewallTest test = new FirewallTest(e.RemoteEndPoint.Address, want.Port);

                    lock (firewalltests) firewalltests.Add(test);

                    socket.SendAsync(
                        new CheckFirewallReady((uint)test.GetHashCode(), e.RemoteEndPoint.Address),
                        e.RemoteEndPoint);
                }
                else
                {
                    uint num = 6;

                    socket.SendAsync(new CheckFirewallBusy()
                        {
                            Port    = (ushort)socket.LocalEndPoint.Port,
                            Servers = GetSendServers(e.RemoteEndPoint.Address, ref num)
                        }, e.RemoteEndPoint);
                }
            }
            break;

            case AresUdpId.OP_SERVERLIST_SENDINFO: {
                SendInfo sendInfo = (SendInfo)e.Packet;

                SendInfoHits++;

                if (Listing && Server != null)
                {
                    AckInfo ackinfo = new AckInfo()
                    {
                        Language = Server.Config.Language,
                        Name     = Server.Config.Name,
                        Topic    = Server.Config.Topic,
                        Version  = Strings.VersionChannels,
                        Port     = (ushort)socket.LocalEndPoint.Port,
                        Users    = (ushort)(Server.Users.Count + 1),
                    };

                    uint num = 6;

                    ackinfo.Servers    = GetSendServers(e.RemoteEndPoint.Address, ref num);
                    ackinfo.ServersLen = (byte)num;

                    socket.SendAsync(ackinfo, e.RemoteEndPoint);
                }
            }
            break;
            }
        }
Beispiel #25
0
 private void Validate_Claims(Binding binding, ModelList<ClaimsetType> claims, SoaModel model)
 {
     foreach (Endpoint endpoint in model.Instances.OfType<Endpoint>().Where(ep => ep.Binding == binding))
     {
         Authorization authorization = endpoint.Authorization;
         if (authorization != null)
         {
             foreach (OperationAuthorization operation in authorization.OperationAuthorizations)
             {
                 foreach (Reference reference in operation.References.Where(rf => rf.Object is ClaimsetType))
                 {
                     ClaimsetType claimset = (ClaimsetType)reference.Object;
                     if (!claims.Contains(claimset))
                     {
                         claims.Add(claimset);
                     }
                 }
                 foreach (Reference reference in operation.References.Where(rf => rf.Object is ClaimField))
                 {
                     ClaimsetType claimset = ((ClaimField)reference.Object).Claimset;
                     if (!claims.Contains(claimset))
                     {
                         claims.Add(claimset);
                     }
                 }
             }
         }
     }
 }
		/// <summary>
		/// Sqls the create table.
		/// </summary>
		/// <returns>
		/// The create table.
		/// </returns>
		/// <param name='type'>
		/// Type.
		/// </param>
		public string sqlCreateTable(Type type) {
			StringBuilder sql = new StringBuilder();
			PropertyInfo[] properties = type.GetProperties();
			ModelList<string> sqlFields = new ModelList<string>();
			ModelList<string> primaryFields = new ModelList<string>();
			ModelList<string> indexFields = new ModelList<string>();
			ModelList<string> uniqueFields = new ModelList<string>();
			ModelList<string> foreignFields = new ModelList<string>();
			//ModelList<string> keys = new ModelList<string>();
			ModelList<string> createdModelsName = new ModelList<string>();
			
			sql.Append("CREATE TABLE IF NOT EXISTS " + this.sqlEscapeTable(type.Name) + " (");
			
			for(int i = 0; i < properties.Length; i++) {
				TemplatizeAttribute[] attributes = (TemplatizeAttribute[])properties[i].GetCustomAttributes(typeof(TemplatizeAttribute), true);
				PrimaryKeyAttribute[] primaryKeys = (PrimaryKeyAttribute[])properties[i].GetCustomAttributes(typeof(PrimaryKeyAttribute), true);
				IndexAttribute[] indexes = (IndexAttribute[])properties[i].GetCustomAttributes(typeof(IndexAttribute), true);
				//ForeignKeyAttribute[] foreigns = (ForeignKeyAttribute[])properties[i].GetCustomAttributes(typeof(ForeignKeyAttribute), true);
				
				if(primaryKeys.Length > 0) {
					primaryFields.Add(this.sqlEscapeField(properties[i].Name));
				} else if(indexes.Length > 0 && indexes[0].Unique) {
					uniqueFields.Add(this.sqlEscapeField(properties[i].Name));
				} else if(indexes.Length > 0) {
					indexFields.Add(this.sqlEscapeField(properties[i].Name));
				}
				
				if(attributes.Length > 0) {
					string sqlType = this.convertTypeToSql(properties[i].PropertyType);
					
					if(primaryKeys.Length > 0 && primaryKeys[0].AutoIncrement) {
						sqlFields.Add(this.sqlEscapeField(properties[i].Name) + " " + sqlType + " NOT NULL AUTO_INCREMENT");
					} else {
						if(properties[i].PropertyType.GetInterface("IModelizable") != null && !createdModelsName.Contains(properties[i].PropertyType.ToString())) {
							if(properties[i].PropertyType.GetInterface("IList") != null) {
								if(properties[i].PropertyType.GetGenericArguments()[0].GetInterface("IModelizable") != null) {
									foreignFields.Add(this.sqlCreateTable(properties[i].PropertyType.GetGenericArguments()[0]));
									foreignFields.Add(this.sqlCreateForeignTable(type, properties[i].PropertyType.GetGenericArguments()[0]));
								} else {
									foreignFields.Add(this.sqlCreateForeignBasicTable(type, properties[i].Name, properties[i].PropertyType.GetGenericArguments()[0]));
								}
							} else {
								foreignFields.Add(this.sqlCreateTable(properties[i].PropertyType));
								foreignFields.Add(this.sqlCreateForeignTable(type, properties[i].PropertyType));
							}
							
							createdModelsName.Add(properties[i].PropertyType.ToString());
						} else {
							sqlFields.Add(this.sqlEscapeField(properties[i].Name) + " " + sqlType + " NOT NULL");
						}
					}
				}
			}
			
			if(primaryFields.Count > 0) {
				sqlFields.Add("PRIMARY KEY (" + string.Join(",", primaryFields.ToArray()) + ")");
			}
			
			if(uniqueFields.Count > 0) {
				sqlFields.Add("UNIQUE KEY (" + string.Join(",", uniqueFields.ToArray()) + ")");
			}
			
			if(indexFields.Count > 0) {
				sqlFields.Add("KEY (" + string.Join(",", indexFields.ToArray()) + ")");
			}
			
			sql.Append(string.Join(",", sqlFields.ToArray()));
			
			sql.Append(") ENGINE=InnoDB DEFAULT CHARSET=utf8");
			
			if(foreignFields.Count > 0) {
				sql.Append(";" + string.Join(";", foreignFields.ToArray()));
			}
			
			return sql.ToString();
		}
		/// <summary>
		/// Sqls the update.
		/// </summary>
		/// <returns>
		/// The update.
		/// </returns>
		/// <param name='type'>
		/// Type.
		/// </param>
		public string sqlUpdate(Type type) {
			StringBuilder sql = new StringBuilder();
			PropertyInfo[] properties = type.GetProperties();
			ModelList<string> sqlFields = new ModelList<string>();
			ModelList<string> sqlNames = new ModelList<string>();
			ModelList<string> whereFields = new ModelList<string>();
			
			sql.Append("UPDATE " + this.sqlEscapeTable(type.Name));
			
			for(int i = 0; i < properties.Length; i++) {
				TemplatizeAttribute[] attributes = (TemplatizeAttribute[])properties[i].GetCustomAttributes(typeof(TemplatizeAttribute), true);
				PrimaryKeyAttribute[] primaryKeys = (PrimaryKeyAttribute[])properties[i].GetCustomAttributes(typeof(PrimaryKeyAttribute), true);
				
				if(attributes.Length > 0 && attributes[0].Templatize && primaryKeys.Length == 0 && properties[i].PropertyType.GetInterface("IModelizable") == null) {
					sqlNames.Add(properties[i].Name);
					sqlFields.Add(this.sqlEscapeField(properties[i].Name) + " = @" + properties[i].Name);
				} else if(primaryKeys.Length > 0 && properties[i].PropertyType.GetInterface("IModelizable") == null) {
					whereFields.Add(this.sqlEscapeField(properties[i].Name) + " = @" + properties[i].Name);
				}
			}
			
			sql.Append(" SET " + string.Join(",", sqlFields.ToArray()) + "");
			sql.Append(" WHERE ");
			sql.Append("(" + string.Join(",", whereFields.ToArray()) + ")");
			
			return sql.ToString();
		}
		/// <summary>
		/// Gets the core plugins.
		/// </summary>
		/// <returns>
		/// The core plugins.
		/// </returns>
		public ModelList<PluginBase> getCorePlugins() {
			Assembly[] assemblies = this.getAssemblies();
			ModelList<PluginBase> plugins = new ModelList<PluginBase>();
			Model auxModel = new Model();
			
			for(int i = 0; i < assemblies.Length; i++) {
				Type[] types = assemblies[i].GetTypes();
				for(int j = 0; j < types.Length; j++) {
					if(types[j].Namespace != null && types[j].Namespace.Contains("Plugin.") && types[j].GetInterface("iPlugin") != null) {
						plugins.Add(auxModel.cast<PluginBase>(Activator.CreateInstance(types[j])));
					}
				}
			}
			
			return plugins;
		}
Beispiel #29
0
 protected Model(string name)
 {
     ModelList.Add(this);
 }
		/// <summary>
		/// Sqls the create foreign basic table.
		/// </summary>
		/// <returns>
		/// The create foreign basic table.
		/// </returns>
		/// <param name='type1'>
		/// Type1.
		/// </param>
		/// <param name='type2'>
		/// Type2.
		/// </param>
		public string sqlCreateForeignBasicTable(Type type1, string basicName, Type type2) {
			StringBuilder sql = new StringBuilder();
			PropertyInfo[] properties1 = type1.GetProperties();
			ModelList<string> fields = new ModelList<string>();
			ModelList<string> keys = new ModelList<string>();
			
			for(int i = 0; i < properties1.Length; i++) {
				PrimaryKeyAttribute[] primaryKeys = (PrimaryKeyAttribute[])properties1[i].GetCustomAttributes(typeof(PrimaryKeyAttribute), true);
				
				if(primaryKeys.Length > 0) {
					string sqlType = this.convertTypeToSql(properties1[i].PropertyType);
					string name = this.sqlEscapeField(type1.Name + "_" + properties1[i].Name);
					
					fields.Add(name + " " + sqlType + " NOT NULL");
					keys.Add(name);
				}
			}
			
			string sqlBasicType = this.convertTypeToSql(type2);
			//basicName = this.sqlEscapeField(basicName);
					
			fields.Add(this.sqlEscapeField(basicName) + " " + sqlBasicType + " NOT NULL");
			
			
			if(keys.Count > 0) {
				fields.Add("KEY (" + string.Join(",", keys.ToArray()) + ")");
			}
			
			sql.Append("CREATE TABLE IF NOT EXISTS " + this.sqlEscapeTable(type1.Name + "_" + basicName) + " (");
			sql.Append(string.Join(",", fields.ToArray()));
			
			sql.Append(") ENGINE=InnoDB DEFAULT CHARSET=utf8");
			
			return sql.ToString();
		}
		/// <summary>
		/// Sqls the string.
		/// </summary>
		/// <returns>
		/// The string.
		/// </returns>
		/// <param name='model'>
		/// Model.
		/// </param>
		/// <param name='type'>
		/// Type.
		/// </param>
		/// <param name='fields'>
		/// Fields.
		/// </param>
		/// <param name='properties'>
		/// Properties.
		/// </param>
		public string sqlString(Model model, Type type, List<string> fields, PropertyInfo[] properties) {
			StringBuilder sql = new StringBuilder();
			ModelList<PropertyInfo> parameters = new ModelList<PropertyInfo>();
			
			for(int i = 0; i < fields.Count; i++) {
				fields[i] = this.sqlEscapeField(fields[i]);
			}
			
			sql.Append("SELECT " + string.Join(",", fields.ToArray()) + " FROM " + this.sqlEscapeTable(type.Name) + " WHERE ");
			
			for(int i = 0; i < properties.Length; i++) {
				if(properties[i].GetValue(model, null) != null) {					
					TemplatizeAttribute[] attributes = (TemplatizeAttribute[])properties[i].GetCustomAttributes(typeof(TemplatizeAttribute), true);
					if(attributes.Length > 0 && properties[i].PropertyType.GetInterface("IModelizable") == null) {
						sql.Append(this.sqlEscapeField(properties[i].Name) + " = @" + properties[i].Name + " AND " );
						parameters.Add(properties[i]);
					}
				}
			}
			
			sql.Append("1 = 1");
			
			return sql.ToString();
		}
        void Model_CameraStateChanged(object sender, CameraStateEventArgs e)
        {
            if (!(e.State == IPCameraState.Streaming || e.State == IPCameraState.Disconnected))
            {
                return;
            }

            _connecting = false;

            switch (e.State)
            {
            case IPCameraState.Streaming:
                InitMediaGateway();
                var camToAdd = (Camera)sender;

                if (!CameraListContains(ModelList, camToAdd))
                {
                    ModelList.Add(camToAdd);
                }

                if (!IsSavedCamera(camToAdd))
                {
                    ConnectModel.SavedCameras.Add(new SavedCamera {
                        Camera = camToAdd, UserName = UserName, Password = Password
                    });
                }

                if (CurrentModel.CustomInfos == null)
                {
                    return;
                }

                InvokeGuiThread(() =>
                {
                    foreach (var item in CurrentModel.CustomInfos)
                    {
                        if (item.Name == "ImageSettingName")
                        {
                            CurrentModel.CameraName = item.Value;
                        }
                        if (item.Name == "Location")
                        {
                            CurrentModel.CameraLocation = item.Value;
                        }
                    }

                    DiscoverAbleCheckbox.IsChecked = CurrentModel.IsDiscoverable;

                    try
                    {
                        foreach (var slider in _imageSliders)
                        {
                            slider.Model = CurrentModel;
                        }
                    }
                    catch (Exception ex)
                    {
                    }
                });
                break;

            case IPCameraState.Disconnected:
                break;
            }

            OnPropertyChanged("IsStreamable");
            OnPropertyChanged("IsIPCamera");
            OnPropertyChanged("IsImagingSupported");
            OnPropertyChanged("CurrentModel");
        }
Beispiel #33
0
        async Task <(ModelList <SmsUser>, bool)> GetSmsResultMax50Async(List <SmsUser> targets)
        {
            var hasNull   = false;
            var result    = new ModelList <SmsUser>();
            var statusIds = new JsonArray();

            targets.ForEach((t) => statusIds.Add(t.status_id));
            // get the SMS delivery status
            var uri = new Uri(smsSetup.url);

            using (var client = await HttpClient.CreateAsync(uri))
            {
                var requestUri    = new Uri(uri, "/api/smsStatus");
                var clientRequest = new HttpClientRequest
                {
                    Method  = "POST",
                    Path    = requestUri.AbsolutePath,
                    Headers =
                    {
                        ["authorization"] = "Bearer " + smsSetup.token,
                        ["content-type"]  = "application/json"
                    },
                    Content = new JsonObject {
                        ["cra"] = statusIds
                    }
                };
                await client.SendRequestAsync(clientRequest);

                var response = await client.GetResponseAsync();

                if (response.StatusCode != 200)
                {
                    logger.Log(LogLevel.Error, $"SMS smsState fails. HTTP STATUS {response.StatusCode}");
                }
                else
                {
                    var json = await response.ReadAsJsonAsync();

                    if (!(json is JsonArray))
                    {
                        logger.Log(LogLevel.Error, $"SMS smsState fails. Result not JsonArray");
                    }
                    else
                    {
                        foreach (var item in json as JsonArray)
                        {
                            if (item == null)
                            {
                                hasNull = true;
                            }
                            if (item is JsonObject && ((JsonObject)item).ContainsKey("ID") &&
                                ((JsonObject)item).ContainsKey("STATUS") &&
                                ((JsonObject)item).ContainsKey("CALLRESULT") &&
                                ((JsonObject)item).ContainsKey("LASTCHANGE"))
                            {
                                var itemObj = item as JsonObject;
                                var smsUser = new SmsUser();
                                smsUser.status_id   = itemObj["ID"];
                                smsUser.status_text = itemObj["CALLRESULT"];
                                SmsStatusState state;
                                if (Enum.TryParse(itemObj["STATUS"], out state))
                                {
                                    smsUser.status_state = state;
                                }
                                DateTime lastChange;
                                if (DateTime.TryParseExact(itemObj["LASTCHANGE"], "dd/MM/yyyy HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out lastChange))
                                {
                                    smsUser.status_mtime = lastChange;
                                }
                                result.Add(smsUser);
                            }
                        }
                    }
                }
            }
            return(result, hasNull);
        }
		public string sqlInsertBasicForeign(Type type1, string basicName, Type type2) {
			StringBuilder sql = new StringBuilder();
			PropertyInfo[] properties1 = type1.GetProperties();
			PropertyInfo[] properties2 = type2.GetProperties();
			ModelList<string> fields = new ModelList<string>();
			ModelList<string> parameters = new ModelList<string>();
			string name = type1.Name + "_" + type2.Name;
			
			for(int i = 0; i < properties1.Length; i++) {
				PrimaryKeyAttribute[] primaryKeys = (PrimaryKeyAttribute[])properties1[i].GetCustomAttributes(typeof(PrimaryKeyAttribute), true);
				
				if(primaryKeys.Length > 0) {
					fields.Add(this.sqlEscapeField(type1.Name + "_" + properties1[i].Name));
					parameters.Add("@" + type1.Name + "_" + properties1[i].Name);
				}
			}
			
			fields.Add(this.sqlEscapeField(basicName));
			parameters.Add("@" + basicName);
			
			sql.Append("INSERT INTO " + this.sqlEscapeTable(name));
			sql.Append("(" + string.Join(",", fields.ToArray()) + ") VALUES (" + string.Join(",", parameters.ToArray()) + ")");
			
			return sql.ToString();
		}
 public void AddPhrase(PhraseEdit phrase)
 {
     ModelList.Add(phrase);
 }
		public string sqlInsert(Type type, ModelList<PropertyInfo> parameters) {
			StringBuilder sql = new StringBuilder();
			ModelList<string> sqlFields = new ModelList<string>();
			ModelList<string> sqlNames = new ModelList<string>();
			
			sql.Append("INSERT INTO " + this.sqlEscapeTable(type.Name));
			
			for(int i = 0; i < parameters.Count; i++) {
				TemplatizeAttribute[] attributes = (TemplatizeAttribute[])parameters[i].GetCustomAttributes(typeof(TemplatizeAttribute), true);
				PrimaryKeyAttribute[] primaryKeys = (PrimaryKeyAttribute[])parameters[i].GetCustomAttributes(typeof(PrimaryKeyAttribute), true);
				
				if((primaryKeys.Length > 0 && primaryKeys[0].AutoIncrement == false) || (primaryKeys.Length == 0 && attributes.Length > 0)) {
					if(parameters[i].PropertyType.GetInterface("IModelizable") == null) {
						sqlNames.Add(this.sqlEscapeField(parameters[i].Name));
						sqlFields.Add("@" + parameters[i].Name);
					}
				}
			}
			
			sql.Append("(" + string.Join(",", sqlNames.ToArray()) + ")");
			sql.Append(" VALUES ");
			sql.Append("(" + string.Join(",", sqlFields.ToArray()) + ")");
			
			sql.Append(";");
			
			sql.Append(this.getInsertedId());
			
			return sql.ToString();
		}
        public Mailboxes(string dbUrl, string rootPath)
        {
            GetAsync["/"] = async(p, c) =>
            {
                await c.EnsureIsSuperAdminAsync();

                var expand = false;
                if (c.Request.QueryString.ContainsKey("expand") && bool.Parse(c.Request.QueryString["expand"]))
                {
                    expand = true;
                }

                var mailboxes = new ModelList <Mailbox>();
                // browse mail folder to find users mailboxes
                foreach (var subdir in System.IO.Directory.GetDirectories(rootPath))
                {
                    foreach (var mailboxFolder in System.IO.Directory.GetDirectories(subdir))
                    {
                        var info     = new DirectoryInfo(mailboxFolder);
                        var filename = Path.GetFileName(mailboxFolder);
                        if ((filename.Length < 3) || !filename.EndsWith(Path.GetFileName(subdir), StringComparison.InvariantCulture))
                        {
                            continue;
                        }
                        var mailbox = new Mailbox
                        {
                            id         = filename.ToUpper(),
                            ctime      = info.CreationTime,
                            mtime      = info.LastWriteTime,
                            is_deleted = true
                        };
                        if (expand)
                        {
                            mailbox.size = GetDirectorySize(info);
                        }
                        mailboxes.Add(mailbox);
                    }
                }

                var userIds   = mailboxes.Select(mailbox => mailbox.id);
                var usersDict = new Dictionary <string, Directory.User>();
                using (DB db = await DB.CreateAsync(dbUrl, false))
                {
                    var tmpIds   = new List <string>();
                    var idsCount = 0;

                    Func <Task> loadUsers = async delegate
                    {
                        var sql = $"SELECT * FROM `user` WHERE {DB.InFilter(nameof(Directory.User.id), tmpIds)} ORDER BY `{nameof(Directory.User.id)}`";
                        foreach (var user in await db.SelectAsync <Directory.User>(sql))
                        {
                            usersDict[user.id] = user;
                        }
                    };

                    // batch request by a group of 200 because it is too slowest for bigger id group
                    foreach (var id in userIds)
                    {
                        tmpIds.Add(id);
                        idsCount++;
                        if (idsCount > 200)
                        {
                            await loadUsers();

                            tmpIds.Clear();
                            idsCount = 0;
                        }
                    }
                    if (idsCount > 0)
                    {
                        await loadUsers();
                    }
                }
                foreach (var mailbox in mailboxes)
                {
                    if (usersDict.ContainsKey(mailbox.id))
                    {
                        var user = usersDict[mailbox.id];
                        mailbox.firstname  = user.firstname;
                        mailbox.lastname   = user.lastname;
                        mailbox.is_deleted = false;
                    }
                }

                c.Response.StatusCode = 200;
                c.Response.Content    = mailboxes.Search(c);
            };

            DeleteAsync["/"] = async(p, c) =>
            {
                await c.EnsureIsSuperAdminAsync();

                var json = await c.Request.ReadAsJsonAsync();

                if (json is JsonArray jsonArray && jsonArray.Count > 0)
                {
                    foreach (var jsonValue in jsonArray)
                    {
                        if (jsonValue.Value is string value && value.All(char.IsLetterOrDigit))
                        {
                            value = value.ToLower();
                            var subdir     = value.Substring(value.Length - 3);
                            var parentPath = Path.Combine(rootPath, subdir);
                            var mailPath   = Path.Combine(parentPath, value);
                            if (System.IO.Directory.Exists(mailPath))
                            {
                                System.IO.Directory.Delete(mailPath, true);
                                // remove the parent folder if empty
                                if (!System.IO.Directory.EnumerateFileSystemEntries(parentPath).Any())
                                {
                                    System.IO.Directory.Delete(parentPath, false);
                                }
                            }
                        }
                    }
                }
                c.Response.StatusCode = 200;
            };
        }
		/// <summary>
		/// Sqls the delete.
		/// </summary>
		/// <returns>
		/// The delete.
		/// </returns>
		/// <param name='type'>
		/// Type.
		/// </param>
		public string sqlDelete(Type type) {
			StringBuilder sql = new StringBuilder();
			PropertyInfo[] properties = type.GetProperties();
			ModelList<string> whereFields = new ModelList<string>();
			
			sql.Append("DELETE FROM " + this.sqlEscapeTable(type.Name));
			
			for(int i = 0; i < properties.Length; i++) {
				PrimaryKeyAttribute[] primaryKeys = (PrimaryKeyAttribute[])properties[i].GetCustomAttributes(typeof(PrimaryKeyAttribute), true);
				
				if(primaryKeys.Length > 0 && properties[i].PropertyType.GetInterface("IModelizable") == null) {
					whereFields.Add(this.sqlEscapeField(properties[i].Name) + " = @" + properties[i].Name);
				}
			}
			
			sql.Append(" WHERE ");
			sql.Append("(" + string.Join(",", whereFields.ToArray()) + ")");
			
			return sql.ToString();
		}
 public void AddVehicle(Vehicle vehicle)
 {
     ModelList.Add(vehicle);
 }
        async Task <ModelList <RecipientUser> > GetRecipientsAsync(DB db, Publipostage item)
        {
            var recipients = new ModelList <RecipientUser>();

            if ((item.groups != null) && (item.groups.Count > 0))
            {
                var profiles = (JsonValue.Parse(item.profils) as JsonArray).Select((arg) => (string)arg);
                foreach (var publiGroup in item.groups)
                {
                    var group = new Group {
                        id = publiGroup.group_id
                    };
                    await group.LoadAsync(db, true);

                    // get all teachers
                    var teachers = new List <User>();
                    foreach (var userId in group.users.FindAll((obj) => obj.type == "ENS").Select((arg) => arg.user_id))
                    {
                        var user = new User {
                            id = userId
                        };
                        await user.LoadAsync(db, true);

                        teachers.Add(user);
                    }
                    // get all students
                    var students = new List <User>();
                    foreach (var userId in group.users.FindAll((obj) => obj.type == "ELV").Select((arg) => arg.user_id))
                    {
                        var user = new User {
                            id = userId
                        };
                        await user.LoadAsync(db, true);

                        students.Add(user);
                    }

                    if (profiles.Contains("eleves"))
                    {
                        foreach (var student in students)
                        {
                            recipients.Add(new RecipientUser {
                                group = group, user = student
                            });
                        }
                    }
                    if (profiles.Contains("profs"))
                    {
                        foreach (var teacher in teachers)
                        {
                            recipients.Add(new RecipientUser {
                                group = group, user = teacher
                            });
                        }
                    }
                    if (profiles.Contains("parents"))
                    {
                        foreach (var student in students)
                        {
                            foreach (var userParent in student.parents)
                            {
                                var parent = new User {
                                    id = userParent.parent_id
                                };
                                await parent.LoadAsync(db, true);

                                recipients.Add(new RecipientUser {
                                    group = group, user = parent, child = student
                                });
                            }
                        }
                    }
                }
            }
            else if (item.users != null)
            {
                var users = await db.SelectExpandAsync <User>("SELECT * FROM `user` WHERE " + DB.InFilter("id", item.users.Select((arg) => arg.user_id)), new object[] { });

                foreach (var user in users)
                {
                    recipients.Add(new RecipientUser {
                        user = user
                    });
                }
            }
            return(recipients);
        }