public ActionResult <AddSystemErrorResponse> Post(AddSystemError request)
 {
     request.Error.Generation = DateTime.Now;
     host.Connection.Insert(GXInsertArgs.Insert(request.Error));
     host.SetChange(TargetType.SystemError, DateTime.Now);
     return(new AddSystemErrorResponse());
 }
Exemple #2
0
        private void AddSchedule(GXDbConnection connection)
        {
            List <GXSchedule> list = new List <GXSchedule>();
            GXSchedule        m    = new GXSchedule();

            m.Name = "Minutely";
            GXDateTime dt = new GXDateTime(DateTime.Now.Date);

            dt.Skip = DateTimeSkips.Year | DateTimeSkips.Month | DateTimeSkips.Day | DateTimeSkips.Hour | DateTimeSkips.Minute;
            m.Start = dt.ToFormatString();
            list.Add(m);
            GXSchedule h = new GXSchedule();

            h.Name  = "Hourly";
            dt.Skip = DateTimeSkips.Year | DateTimeSkips.Month | DateTimeSkips.Day | DateTimeSkips.Hour;
            h.Start = dt.ToFormatString();
            list.Add(h);
            GXSchedule d = new GXSchedule();

            d.Name  = "Daily";
            dt.Skip = DateTimeSkips.Year | DateTimeSkips.Month | DateTimeSkips.Day;
            d.Start = dt.ToFormatString();
            list.Add(d);
            connection.Insert(GXInsertArgs.InsertRange(list));
        }
Exemple #3
0
        public void AddUserRolesTest()
        {
            GXUser user = new GXUser();

            user.Id       = "642c8f77-aeeb-4e86-86db-1a8b1b2fc982";
            user.UserName = "******";
            List <string> roles = new List <string>();

            roles.Add("Admin");
            roles.Add("User");
            roles.Add("DeviceManager");
            roles.Add("SystemErrorManager");
            GXSelectArgs sel  = GXSelectArgs.Select <GXRole>(q => q.Id);
            GXSelectArgs sel2 = GXSelectArgs.Select <GXUserRole>(q => q.UserId, q => q.UserId == "642c8f77-aeeb-4e86-86db-1a8b1b2fc982");

            sel.Where.And <GXRole>(q => !GXSql.Exists <GXRole, GXUserRole>(q => q.Id, q => q.RoleId, sel2));
            sel.Where.And <GXRole>(q => roles.Contains(q.Name));
            GXUserRole ur = new GXUserRole();

            ur.UserId = user.Id;
            GXInsertArgs i = GXInsertArgs.Insert(ur);

            i.Add <GXUserRole>(sel, q => q.RoleId);
            Assert.AreEqual("", i.ToString());
        }
Exemple #4
0
        public ActionResult <AddReaderResponse> Post(AddReader request)
        {
            GXSelectArgs arg = GXSelectArgs.SelectAll <GXReaderInfo>();

            arg.Where.And <GXReaderInfo>(q => q.Guid == request.Reader.Guid);
            GXReaderInfo i = host.Connection.SingleOrDefault <GXReaderInfo>(arg);

            if (i == null)
            {
                request.Reader.Detected = request.Reader.Generation = DateTime.Now;
                host.Connection.Insert(GXInsertArgs.Insert(request.Reader));
            }
            else if (i.Name != request.Reader.Name && !string.IsNullOrEmpty(request.Reader.Name))
            {
                //Update reader name.
                i.Detected = DateTime.Now;
                host.Connection.Update(GXUpdateArgs.Update(i, u => new { u.Detected, u.Name }));
            }
            else
            {
                i.Detected = DateTime.Now;
                host.Connection.Update(GXUpdateArgs.Update(i, u => u.Detected));
            }
            host.SetChange(TargetType.Readers, DateTime.Now);
            return(new AddReaderResponse());
        }
        public ActionResult <AddValueResponse> Post(AddValue request)
        {
            AddValueResponse ret = new AddValueResponse();
            GXUpdateArgs     arg;

            if (request.Items != null)
            {
                DateTime now = DateTime.Now;
                foreach (GXValue it in request.Items)
                {
                    if (it.Read == DateTime.MinValue)
                    {
                        it.Read = now;
                    }
                    GXAttribute value = new GXAttribute();
                    value.Id    = it.AttributeId;
                    value.Value = it.Value;
                    value.Read  = it.Read;
                    arg         = GXUpdateArgs.Update <GXAttribute>(value, q => new { q.Value, q.Read });
                    host.Connection.Update(arg);
                }
                host.Connection.Insert(GXInsertArgs.InsertRange(request.Items));
                host.SetChange(TargetType.Value, now);
            }
            return(ret);
        }
Exemple #6
0
 public ActionResult <ReaderDevicesUpdateResponse> AddDevicesToReaders(ReaderDevicesUpdate request)
 {
     try
     {
         List <GXDeviceToReader> list = new List <GXDeviceToReader>();
         for (int pos = 0; pos != request.Readers.Length; ++pos)
         {
             GXDeviceToReader it = new GXDeviceToReader();
             it.ReaderId = request.Readers[pos];
             it.DeviceId = request.Devices[pos];
             if (it.ReaderId == 0)
             {
                 return(BadRequest(Gurux.DLMS.AMI.Properties.Resources.ReaderIdIsZero));
             }
             if (it.DeviceId == 0)
             {
                 return(BadRequest(Gurux.DLMS.AMI.Properties.Resources.DeviceIdIsZero));
             }
             list.Add(it);
         }
         host.Connection.Insert(GXInsertArgs.InsertRange(list));
         host.SetChange(TargetType.Readers | TargetType.Device, DateTime.Now);
         return(new ReaderDevicesUpdateResponse());
     }
     catch (Exception ex)
     {
         return(BadRequest(ex));
     }
 }
Exemple #7
0
        public void InsertTest()
        {
            TestClass t = new TestClass();

            t.Text = "Gurux";
            GXInsertArgs args = GXInsertArgs.Insert(t, x => new { x.Text, x.Guid });

            Assert.AreEqual("INSERT INTO TestClass (`Text`, `Guid`) VALUES('Gurux', '00000000000000000000000000000000')", args.ToString());
        }
Exemple #8
0
        public void ExcludeInsertTest()
        {
            TestClass t = new TestClass();

            t.Text = "Gurux";
            GXInsertArgs args = GXInsertArgs.Insert(t);

            args.Exclude <TestClass>(x => new { x.Time, x.Text2, x.Text3, x.Text4, x.BooleanTest, x.IntTest, x.DoubleTest, x.FloatTest, x.Span, x.Object, x.Status });
            Assert.AreEqual("INSERT INTO TestClass (`Guid`, `Text`) VALUES('00000000000000000000000000000000', 'Gurux')", args.ToString());
        }
        public ActionResult <AddScheduleTargetResponse> Post(AddScheduleTarget request)
        {
            if (request.Schedules == null || request.Schedules.Length == 0)
            {
                return(BadRequest("Schedules array is empty."));
            }
            AddScheduleTargetResponse    ret  = new AddScheduleTargetResponse();
            List <GXScheduleToAttribute> list = new List <GXScheduleToAttribute>();

            foreach (UInt64 s in request.Schedules)
            {
                if (request.DeviceId != 0)
                {
                    ListObjects req = new ListObjects();
                    req.DeviceId = request.DeviceId;
                    req.Targets  = TargetType.Object | TargetType.Attribute;
                    req.Objects  = request.Objects;
                    using (System.Net.Http.HttpResponseMessage response = Helpers.client.PostAsJsonAsync(this.Request.Scheme + "://" + this.Request.Host + "/api/object/ListObjects", req).Result)
                    {
                        Helpers.CheckStatus(response);
                        ListObjectsResponse objs = response.Content.ReadAsAsync <ListObjectsResponse>().Result;
                        foreach (GXObject obj in objs.Items)
                        {
                            if (obj.Attributes != null)
                            {
                                foreach (GXAttribute a in obj.Attributes)
                                {
                                    list.Add(new GXScheduleToAttribute()
                                    {
                                        ScheduleId = s, AttributeId = a.Id
                                    });
                                }
                            }
                        }
                    }
                }
                else if (request.Objects != null && request.Objects.Length != 0)
                {
                    foreach (GXObject o in request.Objects)
                    {
                        foreach (GXAttribute a in o.Attributes)
                        {
                            list.Add(new GXScheduleToAttribute()
                            {
                                ScheduleId = s, AttributeId = a.Id
                            });
                        }
                    }
                }
            }
            host.Connection.Insert(GXInsertArgs.InsertRange(list));
            host.SetChange(TargetType.Schedule, DateTime.Now);
            return(ret);
        }
Exemple #10
0
        public ActionResult <AddDeviceLogResponse> Post(AddDeviceLog request)
        {
            AddDeviceLogResponse ret = new AddDeviceLogResponse();
            DateTime             now = DateTime.Now;

            foreach (var it in request.Logs)
            {
                it.Generation = now;
                host.Connection.Insert(GXInsertArgs.Insert(it));
            }
            host.SetChange(TargetType.DeviceLog, DateTime.Now);
            return(ret);
        }
Exemple #11
0
        public void CultureTest()
        {
            List <GXLanguage> list = new List <GXLanguage>();

            list.Add(new GXLanguage()
            {
                Id = "fi", EnglishName = "Finland",
            });
            GXInsertArgs insert = GXInsertArgs.InsertRange(list);

            insert.Exclude <GXConfigurationValue>(e => e.Group);
            Assert.AreEqual("Mikko", insert.ToString());
        }
        public ActionResult <UpdateScheduleResponse> Post(UpdateSchedule request)
        {
            if (request.Schedules == null || request.Schedules.Count == 0)
            {
                return(BadRequest("Schedules array is empty."));
            }
            UpdateScheduleResponse       ret   = new UpdateScheduleResponse();
            List <UInt64>                list  = new List <UInt64>();
            List <GXScheduleToAttribute> list2 = new List <GXScheduleToAttribute>();

            foreach (var it in request.Schedules)
            {
                List <GXObject> tmp = it.Objects;
                it.Objects = null;
                if (it.Id == 0)
                {
                    host.Connection.Insert(GXInsertArgs.Insert(it));
                    list.Add(it.Id);
                    if (tmp != null)
                    {
                        foreach (GXObject o in tmp)
                        {
                            if (o.Attributes != null)
                            {
                                foreach (GXAttribute a in o.Attributes)
                                {
                                    list2.Add(new GXScheduleToAttribute()
                                    {
                                        ScheduleId = it.Id, AttributeId = a.Id
                                    });
                                }
                            }
                        }
                        host.Connection.Insert(GXInsertArgs.InsertRange(list2));
                    }
                }
                else
                {
                    host.Connection.Update(GXUpdateArgs.Update(it));
                }
            }
            ret.ScheduleIds = list.ToArray();
            host.SetChange(TargetType.Schedule, DateTime.Now);
            return(ret);
        }
Exemple #13
0
        public void ExcludeTest()
        {
            GXUser user = new GXUser()
            {
                Id = "Default"
            };
            GXUserGroup item = new GXUserGroup()
            {
                Name = "Default"
            };

            item.Users.Add(user);
            GXInsertArgs insert = GXInsertArgs.Insert(item);

            insert.Exclude <GXUserGroup>(e => e.CreationTime);
            insert.Exclude <GXUserGroup>(e => e.Users);
            Assert.AreEqual("Mikko", insert.ToString());
        }
        public ActionResult <AddObjectResponse> Post(AddObject request)
        {
            AddObjectResponse ret = new AddObjectResponse();

            foreach (var it in request.Items)
            {
                it.Generation = DateTime.Now;
            }
            host.Connection.Insert(GXInsertArgs.InsertRange(request.Items));
            host.SetChange(TargetType.Object, DateTime.Now);
            ret.Ids = new UInt64[request.Items.Length];
            int pos = 0;

            foreach (var it in request.Items)
            {
                ret.Ids[pos] = it.Id;
                ++pos;
            }
            return(ret);
        }
Exemple #15
0
        public void InsertSettingsTest()
        {
            List <GXConfigurationValue> list = new List <GXConfigurationValue>();

            list.Add(new GXConfigurationValue()
            {
                Name = "SiteName",
            });
            list.Add(new GXConfigurationValue()
            {
                Name = "Email",
            });
            list.Add(new GXConfigurationValue()
            {
                Name = "Slogan",
            });
            //            GXInsertArgs insert = GXInsertArgs.InsertRange(list, c => new { c.Id, c.Generation });
            GXInsertArgs insert = GXInsertArgs.InsertRange(list);

            insert.Exclude <GXConfigurationValue>(e => e.Group);
            Assert.AreEqual("Mikko", insert.ToString());
        }
        public ActionResult <AddTaskResponse> Post(AddTask request)
        {
            AddTaskResponse ret = new AddTaskResponse();
            DateTime        now = DateTime.Now;

            foreach (var it in request.Actions)
            {
                if (it.Object.Id == 0)
                {
                    UInt64 dId = it.Object.DeviceId;
                    int    ot  = it.Object.ObjectType;
                    string ln  = it.Object.LogicalName;
                    it.Object = host.Connection.SingleOrDefault <GXObject>(GXSelectArgs.Select <GXObject>(null, q => q.DeviceId == dId && q.ObjectType == ot && q.LogicalName == ln));
                    if (it.Object == null)
                    {
                        return(BadRequest(string.Format("Invalid target {0}:{1} DeviceID {2}.", ot, ln, dId)));
                    }
                }
                it.Generation = now;
                host.Connection.Insert(GXInsertArgs.Insert(it));
            }
            host.SetChange(TargetType.Tasks, DateTime.Now);
            return(ret);
        }
Exemple #17
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            if (!Configuration.GetSection("Scheduler").Get <SchedulerOptions>().Disabled)
            {
                services.AddHostedService <TimedHostedService>();
            }

            string settings = Configuration.GetSection("Database").Get <DatabaseOptions>().Settings;
            string type     = Configuration.GetSection("Database").Get <DatabaseOptions>().Type;

            Console.WriteLine("Database type: " + type);
            Console.WriteLine("Connecting: " + settings);
            DbConnection connection;

            if (string.IsNullOrEmpty(type))
            {
                //Gurux.DLMS.AMI DB is defined elsewhere.
                connection = null;
            }
            if (string.Compare(type, "Oracle", true) == 0)
            {
                connection = new OracleConnection(settings);
            }
            else if (string.Compare(type, "MSSQL", true) == 0)
            {
                connection = new SqlConnection(settings);
            }
            else if (string.Compare(type, "MySQL", true) == 0)
            {
                connection = new MySql.Data.MySqlClient.MySqlConnection(settings);
            }
            else if (string.Compare(type, "SQLite", true) == 0)
            {
                connection = new SQLiteConnection(settings);
            }
            else
            {
                throw new Exception("Invalid connection type. " + type);
            }
            if (connection != null)
            {
                connection.Open();
                GXHost h = new GXHost()
                {
                    Connection = new GXDbConnection(connection, null)
                };
                if (!h.Connection.TableExist <GXDevice>())
                {
                    Console.WriteLine("Creating tables.");
                    h.Connection.CreateTable <GXSystemError>(false, false);
                    h.Connection.CreateTable <GXDeviceTemplate>(false, false);
                    h.Connection.CreateTable <GXDevice>(false, false);
                    h.Connection.CreateTable <GXObjectTemplate>(false, false);
                    h.Connection.CreateTable <GXAttributeTemplate>(false, false);
                    h.Connection.CreateTable <GXObject>(false, false);
                    h.Connection.CreateTable <GXAttribute>(false, false);
                    h.Connection.CreateTable <GXValue>(false, false);
                    h.Connection.CreateTable <GXTask>(false, false);
                    h.Connection.CreateTable <GXError>(false, false);
                    h.Connection.CreateTable <GXSchedule>(false, false);
                    h.Connection.CreateTable <GXScheduleToAttribute>(false, false);
                    h.Connection.CreateTable <GXSchedulerInfo>(false, false);
                    h.Connection.CreateTable <GXReaderInfo>(false, false);
                    h.Connection.CreateTable <GXDeviceToReader>(false, false);
                    AddSchedule();
                }
                else
                {
                    h.Connection.UpdateTable <GXSystemError>();
                    h.Connection.UpdateTable <GXError>();
                    h.Connection.UpdateTable <GXReaderInfo>();
                    h.Connection.UpdateTable <GXObjectTemplate>();
                    h.Connection.UpdateTable <GXAttributeTemplate>();
                    h.Connection.UpdateTable <GXDeviceTemplate>();
                    h.Connection.UpdateTable <GXObject>();
                    h.Connection.UpdateTable <GXAttribute>();
                    h.Connection.UpdateTable <GXDevice>();
                }
                h.Connection.Insert(GXInsertArgs.Insert(new GXSystemError()
                {
                    Generation = DateTime.Now,
                    Error      = "Service started: " + ServerAddress
                }));;
                Console.WriteLine("Service started: " + ServerAddress);
                services.AddScoped <GXHost>(q =>
                {
                    return(h);
                });
            }
            services.Configure <ReaderOptions>(Configuration.GetSection("Reader"));
            if (!Configuration.GetSection("Scheduler").Get <SchedulerOptions>().Disabled)
            {
                services.AddHostedService <TimedHostedService>();
            }
            if (Configuration.GetSection("Reader").Get <ReaderOptions>().Threads != 0)
            {
                services.AddHostedService <ReaderService>();
            }
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        }
Exemple #18
0
        public ActionResult <UpdateDeviceResponse> Post(UpdateDevice request)
        {
            if (request.Device.TemplateId == 0)
            {
                return(BadRequest("Device template ID is unknown."));
            }
            bool newDevice = request.Device.Id == 0;

            if (request.Device.DeviceSystemTitle != null)
            {
                request.Device.DeviceSystemTitle = request.Device.DeviceSystemTitle.Replace(" ", "");
            }
            if (request.Device.AuthenticationKey != null)
            {
                request.Device.AuthenticationKey = request.Device.AuthenticationKey.Replace(" ", "");
            }
            if (request.Device.BlockCipherKey != null)
            {
                request.Device.BlockCipherKey = request.Device.BlockCipherKey.Replace(" ", "");
            }
            if (newDevice)
            {
                DateTime now = DateTime.Now;
                request.Device.Generation = now;
                //Add new DC.
                List <GXObject> tmp = request.Device.Objects;
                request.Device.Objects    = null;
                request.Device.Generation = now;
                host.Connection.Insert(GXInsertArgs.Insert(request.Device));

                //Add default objects.
                GXSelectArgs arg = GXSelectArgs.SelectAll <GXObjectTemplate>(q => q.DeviceTemplateId == request.Device.TemplateId && q.Removed == DateTime.MinValue);
                arg.Columns.Add <GXAttributeTemplate>();
                arg.Joins.AddLeftJoin <GXObjectTemplate, GXAttributeTemplate>(o => o.Id, a => a.ObjectTemplateId);
                arg.Where.And <GXAttributeTemplate>(q => q.Removed == DateTime.MinValue);
                List <GXObjectTemplate> l = host.Connection.Select <GXObjectTemplate>(arg);
                foreach (GXObjectTemplate it in l)
                {
                    GXObject obj = new GXObject()
                    {
                        TemplateId  = it.Id,
                        Generation  = now,
                        DeviceId    = request.Device.Id,
                        ObjectType  = it.ObjectType,
                        Name        = it.Name,
                        LogicalName = it.LogicalName,
                        ShortName   = it.ShortName,
                    };
                    host.Connection.Insert(GXInsertArgs.Insert(obj));
                    foreach (GXAttributeTemplate ait in it.Attributes)
                    {
                        GXAttribute a = new GXAttribute();
                        a.ObjectId       = obj.Id;
                        a.Index          = ait.Index;
                        a.TemplateId     = ait.Id;
                        a.AccessLevel    = ait.AccessLevel;
                        a.DataType       = ait.DataType;
                        a.UIDataType     = ait.UIDataType;
                        a.Generation     = now;
                        a.ExpirationTime = ait.ExpirationTime;
                        obj.Attributes.Add(a);
                    }
                    ;
                    host.Connection.Insert(GXInsertArgs.InsertRange(obj.Attributes));
                }
                host.SetChange(TargetType.ObjectTemplate, DateTime.Now);
            }
            else
            {
                request.Device.Updated = DateTime.Now;
                host.Connection.Update(GXUpdateArgs.Update(request.Device));
                host.SetChange(TargetType.DeviceTemplate, DateTime.Now);
            }
            return(new UpdateDeviceResponse()
            {
                DeviceId = request.Device.Id
            });
        }
Exemple #19
0
        public ActionResult <UpdateDeviceTemplateResponse> Post(UpdateDeviceTemplate request)
        {
            GXDeviceTemplate dev = request.Device;

            if (dev == null)
            {
                return(BadRequest("Device is null."));
            }
            bool newDevice = dev.Id == 0;

            if (dev.DeviceSystemTitle != null)
            {
                dev.DeviceSystemTitle = dev.DeviceSystemTitle.Replace(" ", "");
            }
            if (dev.AuthenticationKey != null)
            {
                dev.AuthenticationKey = dev.AuthenticationKey.Replace(" ", "");
            }
            if (dev.BlockCipherKey != null)
            {
                dev.BlockCipherKey = dev.BlockCipherKey.Replace(" ", "");
            }
            dev.Generation = DateTime.Now;
            if (newDevice)
            {
                //Add new DC.
                List <GXObjectTemplate> tmp = dev.Objects;
                dev.Objects = null;
                DateTime now = DateTime.Now;
                dev.Generation = now;
                host.Connection.Insert(GXInsertArgs.Insert(dev));
                if (tmp != null)
                {
                    //Add default objects.
                    foreach (GXObjectTemplate it in tmp)
                    {
                        List <GXAttributeTemplate> tmp2 = it.Attributes;
                        it.Attributes       = null;
                        it.DeviceTemplateId = dev.Id;
                        it.Generation       = now;
                        host.Connection.Insert(GXInsertArgs.Insert(it));
                        if (it.Attributes != tmp2)
                        {
                            foreach (GXAttributeTemplate a in tmp2)
                            {
                                a.Generation       = now;
                                a.ObjectTemplateId = it.Id;
                            }
                            host.Connection.Insert(GXInsertArgs.InsertRange(tmp2));
                        }
                    }
                }
                host.SetChange(TargetType.Object, DateTime.Now);
            }
            else
            {
                host.Connection.Update(GXUpdateArgs.Update(dev));
                host.SetChange(TargetType.DeviceTemplate, DateTime.Now);
            }
            return(new UpdateDeviceTemplateResponse()
            {
                DeviceId = dev.Id
            });
        }
Exemple #20
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
#if !NETCOREAPP2_0 && !NETCOREAPP2_1
            services.AddControllers();
#endif//!NETCOREAPP2_0 && !NETCOREAPP2_1
            DatabaseOptions db       = Configuration.GetSection("Database").Get <DatabaseOptions>();
            string          settings = db.Settings;
            string          type     = db.Type;
            bool            disabled = db.Disabled;
            if (disabled)
            {
                Console.WriteLine("Database service is disabled.");
            }
            else
            {
                Console.WriteLine("Database type: " + type);
                Console.WriteLine("Connecting: " + settings);
            }
            DbConnection connection;
            if (disabled || string.IsNullOrEmpty(type))
            {
                //Gurux.DLMS.AMI DB is defined elsewhere.
                connection = null;
            }
            else if (string.Compare(type, "Oracle", true) == 0)
            {
                connection = new OracleConnection(settings);
            }
            else if (string.Compare(type, "MSSQL", true) == 0)
            {
                connection = new SqlConnection(settings);
            }
            else if (string.Compare(type, "MySQL", true) == 0)
            {
                connection = new MySql.Data.MySqlClient.MySqlConnection(settings);
            }
            else if (string.Compare(type, "SQLite", true) == 0)
            {
                connection = new SQLiteConnection(settings);
            }
            else
            {
                throw new Exception("Invalid connection type. " + type);
            }
            if (connection != null)
            {
                connection.Open();
                GXHost h = new GXHost()
                {
                    Connection = new GXDbConnection(connection, null)
                };
                h.Connection.OnSqlExecuted += Connection_OnSqlExecuted;
                if (!h.Connection.TableExist <GXDevice>())
                {
                    Console.WriteLine("Creating tables.");
                    h.Connection.CreateTable <GXSystemError>(false, false);
                    h.Connection.CreateTable <GXDeviceTemplate>(false, false);
                    h.Connection.CreateTable <GXDevice>(false, false);
                    h.Connection.CreateTable <GXObjectTemplate>(false, false);
                    h.Connection.CreateTable <GXAttributeTemplate>(false, false);
                    h.Connection.CreateTable <GXObject>(false, false);
                    h.Connection.CreateTable <GXAttribute>(false, false);
                    h.Connection.CreateTable <GXValue>(false, false);
                    h.Connection.CreateTable <GXTask>(false, false);
                    h.Connection.CreateTable <GXError>(false, false);
                    h.Connection.CreateTable <GXSchedule>(false, false);
                    h.Connection.CreateTable <GXScheduleToAttribute>(false, false);
                    h.Connection.CreateTable <GXSchedulerInfo>(false, false);
                    h.Connection.CreateTable <GXReaderInfo>(false, false);
                    h.Connection.CreateTable <GXDeviceToReader>(false, false);
                    h.Connection.CreateTable <GXDeviceLog>(false, false);
                    AddSchedule(h.Connection);
                }
                else
                {
                    h.Connection.UpdateTable <GXSystemError>();
                    h.Connection.UpdateTable <GXError>();
                    h.Connection.UpdateTable <GXReaderInfo>();
                    h.Connection.UpdateTable <GXObjectTemplate>();
                    h.Connection.UpdateTable <GXAttributeTemplate>();
                    h.Connection.UpdateTable <GXDeviceTemplate>();
                    h.Connection.UpdateTable <GXObject>();
                    h.Connection.UpdateTable <GXAttribute>();
                    h.Connection.UpdateTable <GXDevice>();
                    if (!h.Connection.TableExist <GXDeviceLog>())
                    {
                        h.Connection.CreateTable <GXDeviceLog>(false, false);
                    }
                    else
                    {
                        h.Connection.UpdateTable <GXDeviceLog>();
                    }
                }
                h.Connection.Insert(GXInsertArgs.Insert(new GXSystemError()
                {
                    Generation = DateTime.Now,
                    Error      = "Service started: " + ServerAddress
                }));;
                Console.WriteLine("Service started: " + ServerAddress);
                services.AddScoped <GXHost>(q =>
                {
                    return(h);
                });
            }
            services.Configure <ListenerOptions>(Configuration.GetSection("Listener"));
            ListenerOptions listener = Configuration.GetSection("Listener").Get <ListenerOptions>();
            if (!listener.Disabled)
            {
                services.AddHostedService <GXListenerService>();
            }
            else
            {
                Console.WriteLine("Listener service is disabled.");
            }
            services.Configure <NotifyOptions>(Configuration.GetSection("Notify"));
            NotifyOptions n = Configuration.GetSection("Notify").Get <NotifyOptions>();
            if (!n.Disabled && n.Port != 0)
            {
                services.AddHostedService <GXNotifyService>();
            }
            else
            {
                Console.WriteLine("Notify service is disabled.");
            }
            services.Configure <SchedulerOptions>(Configuration.GetSection("Scheduler"));
            SchedulerOptions s = Configuration.GetSection("Scheduler").Get <SchedulerOptions>();
            if (!s.Disabled)
            {
                services.AddHostedService <GXSchedulerService>();
            }
            else
            {
                Console.WriteLine("Scheduler service is disabled.");
            }
            services.Configure <ReaderOptions>(Configuration.GetSection("Reader"));
            ReaderOptions r = Configuration.GetSection("Reader").Get <ReaderOptions>();
            Console.WriteLine("Reader trace level is " + r.TraceLevel);
            Console.WriteLine("Listener trace level is " + listener.TraceLevel);
            if (r.Threads != 0 && !r.Disabled)
            {
                services.AddHostedService <ReaderService>();
            }
            else
            {
                Console.WriteLine("Reader '" + r.Name + "' ID: " + r.Id);
            }
#if NETCOREAPP2_0 || NETCOREAPP2_1
            services.AddMvc().SetCompatibilityVersion(Microsoft.AspNetCore.Mvc.CompatibilityVersion.Version_2_1);
#endif //NETCOREAPP2_0 || NETCOREAPP2_1
        }
        public ActionResult <AddTestDeviceResponse> Post(AddTestDevice request)
        {
            if (request.Device.TemplateId == 0)
            {
                return(BadRequest("Device template ID is unknown."));
            }
            if (request.Device.DeviceSystemTitle != null)
            {
                request.Device.DeviceSystemTitle = request.Device.DeviceSystemTitle.Replace(" ", "");
            }
            if (request.Device.AuthenticationKey != null)
            {
                request.Device.AuthenticationKey = request.Device.AuthenticationKey.Replace(" ", "");
            }
            if (request.Device.BlockCipherKey != null)
            {
                request.Device.BlockCipherKey = request.Device.BlockCipherKey.Replace(" ", "");
            }
            DateTime now = DateTime.Now;

            //Add new DC.
            request.Device.Generation = now;
            //We are accessing meters using serial number when test mode is used.
            request.Device.HDLCAddressing = ManufacturerSettings.HDLCAddressType.SerialNumber;
            request.Device.LogicalAddress = request.Index;
            for (UInt16 pos = 0; pos != request.Count; ++pos)
            {
                request.Device.Objects = null;
                request.Device.Name    = "Test_" + request.Device.LogicalAddress;
                ++request.Device.LogicalAddress;
                request.Device.Id = 0;

                host.Connection.Insert(GXInsertArgs.Insert(request.Device));
                //Add default objects.
                GXSelectArgs arg = GXSelectArgs.SelectAll <GXObjectTemplate>(q => q.DeviceTemplateId == request.Device.TemplateId);
                arg.Columns.Add <GXAttributeTemplate>();
                arg.Joins.AddLeftJoin <GXObjectTemplate, GXAttributeTemplate>(o => o.Id, a => a.ObjectTemplateId);
                List <GXObjectTemplate> l = host.Connection.Select <GXObjectTemplate>(arg);
                foreach (GXObjectTemplate it in l)
                {
                    GXObject obj = new GXObject()
                    {
                        TemplateId  = it.Id,
                        Generation  = now,
                        DeviceId    = request.Device.Id,
                        ObjectType  = it.ObjectType,
                        Name        = it.Name,
                        LogicalName = it.LogicalName,
                        ShortName   = it.ShortName,
                    };
                    host.Connection.Insert(GXInsertArgs.Insert(obj));
                    foreach (GXAttributeTemplate ait in it.Attributes)
                    {
                        GXAttribute a = new GXAttribute();
                        a.ObjectId       = obj.Id;
                        a.Index          = ait.Index;
                        a.TemplateId     = ait.Id;
                        a.AccessLevel    = ait.AccessLevel;
                        a.DataType       = ait.DataType;
                        a.UIDataType     = ait.UIDataType;
                        a.Generation     = now;
                        a.ExpirationTime = ait.ExpirationTime;
                        obj.Attributes.Add(a);
                    }
                    ;
                    host.Connection.Insert(GXInsertArgs.InsertRange(obj.Attributes));
                }
            }
            host.SetChange(TargetType.Device, DateTime.Now);
            return(new AddTestDeviceResponse());
        }