Esempio n. 1
0
 public static bool ValidateUser(string username, string password)
 {
     using (var context = new PlansDc(EsterConnectionString))
     {
         if (context.Users.Any(u => u.Login == username && u.Password == password))
             return true;
     }
     return false;
 }
Esempio n. 2
0
 public static bool IsUserExist(string username)
 {
     using (var context = new PlansDc(EsterConnectionString))
     {
         if (context.Users.Any(u => u.Login == username))
             return true;
     }
     return false;
 }
Esempio n. 3
0
 public void Delete(string id)
 {
     using (var context = new PlansDc(_esterConnectionString))
     {
         var plan = GetPlanObjectById(id, context);
         DeleteChilds(plan, context);
         context.PlanObjects.DeleteOnSubmit(plan);
         context.SubmitChanges();
     }
 }
Esempio n. 4
0
        public static void ExportToDbObject(this BaseObject baseObject, PlanObject dbObject, PlansDc context, int order = 0)
        {
            dbObject.Id = baseObject.Id >= 0 ? baseObject.Id : GetNewPlanObjectId(context);

            if (baseObject.ParentId != null && baseObject.ParentId >= 0)
                dbObject.ParentId = baseObject.ParentId;

            dbObject.Order = order;
            dbObject.Name = baseObject.Name;
            dbObject.Description = baseObject.Description;
            dbObject.Left = baseObject.Left;
            dbObject.Top = baseObject.Top;
            dbObject.Width = baseObject.Width;
            dbObject.Height = baseObject.Height;
            dbObject.TypeId = baseObject.TypeId;
            if (baseObject.Path != null)
                dbObject.Geometry = baseObject.Path.ToSvg();

            if (baseObject.Properties != null)
            {
                dbObject.Properties.Clear();
                foreach (var baseObjectProperty in baseObject.Properties.Where(p => !string.IsNullOrWhiteSpace(p.Path)))
                {
                        var newProperty = new Property
                        {
                            AddressTypeId = baseObjectProperty.TypeId,
                            Path = baseObjectProperty.Path
                        };
                        dbObject.Properties.Add(newProperty);
                }
            }

            if (!baseObject.IsContainer) return;

            var baseContainer = baseObject as IContainerObject;
            if (baseContainer == null) throw new BadRequestException("Children cannot be null in ContainerObject");

            for (var i = dbObject.PlanObjects.Count - 1; i >= 0; i--)
            {
                if (baseContainer.Children.All(s => s.Id != dbObject.PlanObjects[i].Id))
                    dbObject.PlanObjects.RemoveAt(i);
            }
            var childOrder = 0;
            foreach (var childObject in baseContainer.Children)
            {
                var dbChildObject = dbObject.PlanObjects.FirstOrDefault(p => p.Id == childObject.Id);
                if (dbChildObject == null)
                {
                    dbChildObject = new PlanObject();
                    dbObject.PlanObjects.Add(dbChildObject);
                }
                childObject.ExportToDbObject(dbChildObject, context, childOrder++);
            }
        }
Esempio n. 5
0
 public static bool IsValidAPIKey(string key)
 {
     using (var classes = new PlansDc(EsterConnectionString))
     {
         Guid apiKey;
         if (Guid.TryParse(key, out apiKey) && classes.Users.Any(s => s.ApiKey == apiKey))
         {
             return true;
         }
     }
     return false;
 }
Esempio n. 6
0
        public Stream Get()
        {
            string responseBody;
            using (var context = new PlansDc(_esterConnectionString))
            {
                var plans = context.PlanObjects.Where(p => p.ParentId == null);

                var res = new List<IContainerObject>();
                foreach (var planObject in plans)
                {
                    res.Add(ServerExtensions.FromDbObject(planObject) as IContainerObject);
                }
                responseBody = JsonConvert.SerializeObject(res, Formatting.Indented);
            }
            return SerializeHelper.GetResponceFromString(responseBody);
        }
Esempio n. 7
0
 public void DeleteSchedule(string id)
 {
     try
     {
         int intId = int.Parse(id);
         using (var context = new PlansDc(ConfigurationManager.ConnectionStrings["Ester"].ConnectionString))
         {
             var dbSchedule = context.Schedules.Single(s => s.ObjectId == intId);
             dbSchedule.DeleteOnSync = true;
             context.SubmitChanges();
         }
     }
     catch
     {
         throw new BadRequestException();
     }
 }
Esempio n. 8
0
		private void AddScheduleToDataBase(ScheduleClass controllerSchedule)
		{
			//добавление расписания в бд
			Schedule sch = ConvertScheduleClassToDbSchedule(controllerSchedule);
			using (var context = new PlansDc(ConfigurationManager.ConnectionStrings["Ester"].ConnectionString))
			{
				var dbSch = context.Schedules.FirstOrDefault(s => s.ObjectId == sch.ObjectId);
				if (dbSch != null)
					context.Schedules.DeleteOnSubmit(dbSch);
				context.Schedules.InsertOnSubmit(sch);
				context.SubmitChanges();
			}
		}
Esempio n. 9
0
 private BaseObject SavePlanObjectToDb(string id, BaseObject planObject)
 {
     BaseObject res;
     var plan = new PlanObject();
     using (var context = new PlansDc(_esterConnectionString))
     {
         if (!string.IsNullOrEmpty(id))
             plan = GetPlanObjectById(id, context);
         else
             context.PlanObjects.InsertOnSubmit(plan);
         planObject.ExportToDbObject(plan, context);
         context.SubmitChanges();
         res = ServerExtensions.FromDbObject(plan);
     }
     if (_eventAggregator != null)
         _eventAggregator.GetEvent<PlansModifiedEvent>().Publish(planObject);
     return res;
 }
Esempio n. 10
0
 private void DeleteChilds(PlanObject plan, PlansDc context)
 {
     foreach (var child in plan.PlanObjects)
     {
         DeleteChilds(child, context);
         context.PlanObjects.DeleteOnSubmit(child);
     }
 }
Esempio n. 11
0
 private static PlanObject GetPlanObjectById(string id, PlansDc context)
 {
     int intId;
     if (!int.TryParse(id, out intId))
         throw new BadRequestException("Unknown identifier format");
     var plan = context.PlanObjects.FirstOrDefault(p => p.Id == intId);
     if (plan == null)
         throw new BadRequestException("Object not found");
     return plan;
 }
Esempio n. 12
0
 public Stream GetTypeProperties(string id)
 {
     string responseBody;
     using (var context = new PlansDc(_esterConnectionString))
     {
         int intId;
         if (!int.TryParse(id, out intId))
             throw new BadRequestException("Unknown identifier format");
         var res = context.PropertyTypes.Where(a => a.TypeId == intId).ToDictionary(p1 => p1.Id, p2 => p2.Title);
         responseBody = JsonConvert.SerializeObject(res, Formatting.Indented);
     }
     return SerializeHelper.GetResponceFromString(responseBody);
 }
Esempio n. 13
0
		private List<ScheduleClass> GetSchedulesFromDataBase()
		{
			var dataBaseSchedules = new List<ScheduleClass>();
			using (var context = new PlansDc(ConfigurationManager.ConnectionStrings["Ester"].ConnectionString))
			{
				foreach (var dbSchedule in context.Schedules)
				{
					var schedule = ConvertDbScheduleToScheduleClass(dbSchedule);
					dataBaseSchedules.Add(schedule);
				}
			}
			return dataBaseSchedules;
		}
Esempio n. 14
0
		private void EditScheduleInDataBase(ScheduleClass controllerSchedule)
		{
			Schedule newDbSchedule = ConvertScheduleClassToDbSchedule(controllerSchedule);
			using (var context = new PlansDc(ConfigurationManager.ConnectionStrings["Ester"].ConnectionString))
			{
				var dbSchedule = context.Schedules.Single(s => s.ObjectId == newDbSchedule.ObjectId);
				dbSchedule.Title = newDbSchedule.Title;
				dbSchedule.OverrideController = newDbSchedule.OverrideController;
				dbSchedule.DeleteOnSync = newDbSchedule.DeleteOnSync;
				dbSchedule.SchedulesContents = newDbSchedule.SchedulesContents;
				dbSchedule.SchedulesControlledProperties = newDbSchedule.SchedulesControlledProperties;
				context.SubmitChanges();
			}
		}
Esempio n. 15
0
        /// <summary>
        /// Процедура для обновления планов из БД
        /// </summary>
        private void OnPlansModified(BaseObject obj)
        {
            // прекращаем отправлять значения
            _pushValuesToClientTimer.Stop();

            // очищаем адреса и изменившиеся объекты
            _addresses.Clear();
            _changedValues.Clear();
            _planObjects.Clear();

            using (var plansDb = new PlansDc(_esterConnectionString))
            {
                // обновляем информцию из бд
                _rootObjects = plansDb.PlanObjects.Where(po => po.Parent == null).Select(p => ServerExtensions.FromDbObject(p)).ToList();
                foreach (var group in plansDb.Properties.GroupBy(g => g.Path)) _addresses.Add(group.Key, group.ToList());
            }

            FillPlanObjects(_planObjects, _rootObjects);

            // обновляем подписку на всех работающих провайдерах данных
            foreach (var dataProvider in _providers.Where(p => p.State == DataProviderState.Working))
                dataProvider.UpdateSubscription(_addresses.Keys.ToList());

            // возобновляем ход времени :)
            _pushValuesToClientTimer.Start();

            // уведомляем подписчиков о необходимости перечитать дерево целиком
            PushValuesToClients(true);
        }
Esempio n. 16
0
 public Stream GetScheduleById(string id)
 {
     try
     {
         int intId = int.Parse(id);
         using (var context = new PlansDc(ConfigurationManager.ConnectionStrings["Ester"].ConnectionString))
         {
             var dbSchedule = context.Schedules.Single(s => s.ObjectId == intId);
             var schedule = ConvertDbScheduleToScheduleClass(dbSchedule);
             var myResponseBody = JsonConvert.SerializeObject(schedule);
             if (WebOperationContext.Current != null)
                 WebOperationContext.Current.OutgoingResponse.ContentType = "application/json; charset=utf-8";
             return new MemoryStream(Encoding.UTF8.GetBytes(myResponseBody));
         }
     }
     catch
     {
         throw new BadRequestException();
     }
 }
Esempio n. 17
0
		private void DeleteScheduleFromDb(ScheduleClass dataBaseSchedule)
		{
			using (var context = new PlansDc(ConfigurationManager.ConnectionStrings["Ester"].ConnectionString))
			{
				var dbSch = context.Schedules.Single(s => s.ObjectId == dataBaseSchedule.Id);
				context.Schedules.DeleteOnSubmit(dbSch);
				context.SubmitChanges();
			}
		}
Esempio n. 18
0
 private static int GetNewPlanObjectId(PlansDc context)
 {
     var lastPlanObject = context.PlanObjects.OrderByDescending(p => p.Id).FirstOrDefault();
     return lastPlanObject == null ? 0 : lastPlanObject.Id + 1;
 }
Esempio n. 19
0
 public Stream GetAlarmLevels()
 {
     string responseBody;
     using (var context = new PlansDc(_esterConnectionString))
     {
         var units = context.PropertyAlarmLevels.ToDictionary(u => u.Id, u => u.Name);
         responseBody = JsonConvert.SerializeObject(units, Formatting.Indented);
     }
     return SerializeHelper.GetResponceFromString(responseBody);
 }
Esempio n. 20
0
        public Stream GetItemProperties(string id)
        {
            string responseBody;
            using (var context = new PlansDc(_esterConnectionString))
            {
                var res = new List<BaseObjectProperty>();
                var plan = GetPlanObjectById(id, context);
                var properties = context.PropertyTypes.Where(a => a.PlanObjectType == plan.PlanObjectType);
                foreach (var addressType in properties)
                {
                    var property =
                        context.Properties.FirstOrDefault(p => p.ObjectId == plan.Id && p.AddressTypeId == addressType.Id);
                    if (property != null)
                        res.Add(new BaseObjectProperty
                            {

                                Id = property.Id,
                                Path = property.Path,
                                TypeName = addressType.Title,
                                TypeId = addressType.Id
                            });
                    else
                        res.Add(new BaseObjectProperty { Id = 0, Path = "", TypeName = addressType.Title, TypeId = addressType.Id });
                }
                responseBody = JsonConvert.SerializeObject(res, Formatting.Indented);
            }
            return SerializeHelper.GetResponceFromString(responseBody);
        }
Esempio n. 21
0
 private List<ScheduleClass> GetSchedulesFromDataBase()
 {
     using (var context = new PlansDc(ConfigurationManager.ConnectionStrings["Ester"].ConnectionString))
         return context.Schedules.Select(dbSchedule => ConvertDbScheduleToScheduleClass(dbSchedule)).ToList();
 }
Esempio n. 22
0
		private int GetFreeIdForType(ScheduleTypes type)
		{
			using (var context = new PlansDc(ConfigurationManager.ConnectionStrings["Ester"].ConnectionString))
			{
				int minId = 0, maxId = 0;
				switch (type)
				{
					case ScheduleTypes.SKUD:
						minId = (int)ScheduleClass.MinScudTypeNumber;
						maxId = (int)ScheduleClass.MaxScudTypeNumber;
						break;
					case ScheduleTypes.Heat:
						minId = (int)ScheduleClass.MinHeatTypeNumber;
						maxId = (int)ScheduleClass.MaxHeatTypeNumber;
						break;
					case ScheduleTypes.Light:
						minId = (int)ScheduleClass.MinLightTypeNumber;
						maxId = (int)ScheduleClass.MaxLightTypeNumber;
						break;
					case ScheduleTypes.AC:
						minId = (int)ScheduleClass.MinACTypeNumber;
						maxId = (int)ScheduleClass.MaxACTypeNumber;
						break;
					case ScheduleTypes.Ventilation:
						minId = (int)ScheduleClass.MinVentialtionTypeNumber;
						maxId = (int)ScheduleClass.MaxVentialtionTypeNumber;
						break;
				}
				var schedules = context.Schedules.Where(s => s.ObjectId >= minId && s.ObjectId <= maxId).ToList();
				for (var i = minId; i <= maxId; i++)
					if (schedules.All(s => s.ObjectId != i))
						return i;
				return 0;
			}
		}
Esempio n. 23
0
        public DataManager(IUnityContainer container)
        {
            // подписываемся на событие обновления планов через редактор
            var eventAggregator = container.Resolve<EventAggregator>();
            var eve = eventAggregator.GetEvent<PlansModifiedEvent>();
            eve.Subscribe(OnPlansModified);

            // инициализируем переменные
            _addresses = new Dictionary<string, List<Property>>();
            _planObjects = new Dictionary<int, BaseObject>();
            _providers = new List<IDataProvider>();
            _changedValues = new List<BaseObject>();

            _pushValuesToClientTimer = new Timer(PushValuesInterval) { AutoReset = true };
            _pushValuesToClientTimer.Elapsed += PushValuesToClientTimerOnElapsed;

            using (var plansDb = new PlansDc(_esterConnectionString))
            {
                // получаем необходимые значения из бд
                _rootObjects = plansDb.PlanObjects.Where(po => po.Parent == null).Select(p => ServerExtensions.FromDbObject(p)).ToList();
                foreach (var group in plansDb.Properties.GroupBy(g => g.Path))
                    _addresses.Add(group.Key, group.ToList());
            }

            FillPlanObjects(_planObjects, _rootObjects);

            // Регистрируем все имеющиеся провайдеры данных
            RegisterDataProviders();

            // формируем конфигурацию для провайдеров данных
            var config = new Dictionary<string, object>
            {
                {
                    "ConfigSource",
                    new XmlConfigSource(Path.Combine(HttpRuntime.AppDomainAppPath, @"Resources\ServerConfig.xml")) { AutoSave = true }
                },
                {
                    "Addresses",
                    _addresses.Keys.ToList()
                }
            };

            // инициализируем провайдеры
            foreach (var dataProvider in _providers)
            {
                dataProvider.DataProviderInitializedEvent += OnDataProviderInitializedEvent;
                dataProvider.Initialize(config);
            }

            // запускаем таймер
            _pushValuesToClientTimer.Start();
        }
Esempio n. 24
0
 public Stream GetItem(string id)
 {
     string responseBody;
     using (var context = new PlansDc(_esterConnectionString))
     {
         var plan = GetPlanObjectById(id, context);
         responseBody = JsonConvert.SerializeObject(ServerExtensions.FromDbObject(plan), Formatting.Indented);
     }
     return SerializeHelper.GetResponceFromString(responseBody);
 }