Exemple #1
0
 public static async Task Main(string[] args)
 {
     await ProgramCommon.Execute(args, svc =>
     {
         svc.AddHostedService <Intermediate>();
     });
 }
Exemple #2
0
 static async Task Main(string[] args)
 {
     await ProgramCommon.Execute(args, services =>
     {
         services.AddHostedService <Observer>();
     });
 }
Exemple #3
0
        public override void Loop()
        {
            //DebugTools.AddEvent("ScrollDot.Loop", "START Looping ScrollDot");

            var colors = new List <Color>();

            colors.Add(Color.Red);
            colors.Add(Color.Blue);
            colors.Add(Color.Yellow);
            colors.Add(Color.Green);
            colors.Add(Color.Purple);
            colors.Add(Color.RoyalBlue);
            colors.Add(Color.MediumSeaGreen);

            for (int i = 0; i < LightCount; i++)
            {
                //prepare frame
                var sendColors = new Dictionary <int, Color>();
                Zone.SortedLights.Keys.ToList().ForEach(lightIndex => sendColors.Add(lightIndex, Color.Black));
                sendColors[i] = DotColor != null ? (Color)DotColor : colors[new Random().Next(0, colors.Count - 1)];
                if (i + 1 < LightCount)
                {
                    sendColors[i + 1] = DotColor != null ? (Color)DotColor : colors[new Random().Next(0, colors.Count - 1)];
                }

                SendColors(sendColors);                         //send frame
                ProgramCommon.Delay(DelayTime);                 //pause before next iteration

                SyncContext?.SignalAndWait(100);
            }

            //DebugTools.AddEvent("ScrollDot.Loop", "START Looping ScrollDot");
        }
Exemple #4
0
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            logger.LogInformation("Clearing file {path}", settings.OutFilePath);

            System.IO.File.WriteAllText(settings.OutFilePath, "");

            await ProgramCommon.WaitForRabbitMQ(stoppingToken);

            await client.TryConnect(
                Constants.RabbitUri,
                Constants.ExchangeName,
                Constants.AllMyTopics,
                stoppingToken);

            logger.LogInformation("Connected");

            await Task.Delay(Constants.DelayAfterConnect, stoppingToken);

            // keep the service running
            while (!stoppingToken.IsCancellationRequested)
            {
                await Task.Delay(Constants.LoopDelay, stoppingToken);
            }

            logger.LogInformation("Finished");
        }
Exemple #5
0
        public void ScrollTrail_FourRandomColorsSquareTrails_Works(int?sleepSeconds, float darkenFactor, int delayTime)
        {
            //act
            var zlm = new ZLM(false, false, false, zlmInner =>
            {
                var isv = new ISV();
                isv.Add("DarkenFactor", (float)darkenFactor);
                isv.Add("DelayTime", delayTime);
                isv.Add("ShareShape", true);
                isv.Add("TrailShapes", new List <TrailShape>()
                {
                    new TrailShape(new Trail(4, ProgramCommon.GetRandomColor().Darken(0.5)), new Shape(0, 1, 2, 3, 11, 19, 27, 26, 25, 24, 16, 8)),
                    new TrailShape(new Trail(4, ProgramCommon.GetRandomColor().Darken(0.5)), new Shape(27, 26, 25, 24, 16, 8, 0, 1, 2, 3, 11, 19)),
                    new TrailShape(new Trail(4, ProgramCommon.GetRandomColor().Darken(0.5)), new Shape(4, 5, 6, 7, 15, 23, 31, 30, 29, 28, 20, 12)),
                    new TrailShape(new Trail(4, ProgramCommon.GetRandomColor().Darken(0.5)), new Shape(31, 30, 29, 28, 20, 12, 4, 5, 6, 7, 15, 23)),
                    new TrailShape(new Trail(4, ProgramCommon.GetRandomColor().Darken(0.5)), new Shape(32, 33, 34, 35, 43, 51, 59, 58, 57, 56, 48, 40)),
                    new TrailShape(new Trail(4, ProgramCommon.GetRandomColor().Darken(0.5)), new Shape(59, 58, 57, 56, 48, 40, 32, 33, 34, 35, 43, 51)),
                    new TrailShape(new Trail(4, ProgramCommon.GetRandomColor().Darken(0.5)), new Shape(36, 37, 38, 39, 47, 55, 63, 62, 61, 60, 52, 44)),
                    new TrailShape(new Trail(4, ProgramCommon.GetRandomColor().Darken(0.5)), new Shape(63, 62, 61, 60, 52, 44, 36, 37, 38, 39, 47, 55)),
                });
                var neomatrix = ZoneScaffolder.Instance.AddFadeCandyZone(zlmInner.Zones, "NeoMatrix", PixelType.FadeCandyWS2812Pixel,
                                                                         64, 1);
                zlmInner.CreateSingularProgramSet("", new ScrollTrail(), isv, neomatrix);
            }, Config.Get("NeoMatrixOneZone"));

            //Thread.Sleep(Timeout.Infinite);
            Thread.Sleep((int)(sleepSeconds != null ? sleepSeconds * 1000 : Timeout.Infinite));

            //cleanup
            zlm.Dispose();
        }
        /// <summary>
        /// Entry point
        /// </summary>
        /// <param name="args"></param>
        public static void Main(string[] args)
        {
            //ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => true;

            var startup = new Startup();

            ProgramCommon.Main(args, startup);
        }
        public Task <IdentityResult> NewSocietyUser(ApplicationUser user, ApplicationRole[] roles, long?societyId, ApplicationUser currentUser)
        {
            return(Task.Run(async() =>
            {
                IdentityResult result = await CreateLogin(ProgramCommon.GetFormattedUsername(user.Name), user.Email, user.PhoneNumber, roles
                                                          , null, user.Name, user.PhoneNumber, bBlocked: false, bChangePass: true, isback: false, societyId: societyId, complexId: null, currentUser: currentUser);

                return result;
            }));
        }
        public void Raindrops_Works(int sleepSeconds, int trailLengthAvg, int trailLengthVariability, int intervalAvg, int intervalVariability)
        {
            IntervalAvg         = intervalAvg;
            IntervalVariability = intervalVariability;

            var zlm = new ZLM(false, false, false, zlmInner =>
            {
                dynamic startingParams            = new ExpandoObject();
                startingParams.ClockedTrailShapes = new List <dynamic>();

                for (int i = 0; i < 64; i += 8)
                {
                    dynamic clockedTrailShape = new ExpandoObject();
                    var trailLength           = ProgramCommon.RandomIntBetween(trailLengthAvg - trailLengthVariability, trailLengthAvg + trailLengthVariability);
                    var interval = ProgramCommon.RandomIntBetween(intervalAvg - intervalVariability, intervalAvg + intervalVariability);

                    var darkenFactor             = (float)0.7;
                    clockedTrailShape.TrailShape = new TrailShape(new Trail(trailLength, Color.Green.Darken(0.5)),
                                                                  new Shape(i, i + 1, i + 2, i + 3, i + 4, i + 5, i + 6, i + 7));
                    clockedTrailShape.TrailShape.DarkenFactor = darkenFactor;
                    clockedTrailShape.Interval       = interval;
                    clockedTrailShape.GetNewInterval = (Func <int>)GetNewInterval;
                    clockedTrailShape.AutoTrail      = true;                //todo: implement autotrail
                    clockedTrailShape.AutoSpeed      = true;                //todo: implement autospeed
                    startingParams.ClockedTrailShapes.Add(clockedTrailShape);
                }

                //startingParams.ClockedTrailShapes.Add(new ExpandoObject() )};
                //startingParams.TrailShapes.Add(new TrailShape(new Trail(4, ProgramCommon.GetRandomColor()),
                //	new Shape(8, 9, 10, 11, 12, 13, 14, 15)));
                //startingParams.TrailShapes.Add(new TrailShape(new Trail(4, ProgramCommon.GetRandomColor()),
                //	new Shape(16, 17, 18, 19, 20, 21, 22, 23)));
                //startingParams.TrailShapes.Add(new TrailShape(new Trail(4, ProgramCommon.GetRandomColor()),
                //	new Shape(24, 25, 26, 27, 28, 29, 30, 31)));
                //startingParams.TrailShapes.Add(new TrailShape(new Trail(4, ProgramCommon.GetRandomColor()),
                //	new Shape(32, 33, 34, 35, 36, 37, 38, 39)));
                //startingParams.TrailShapes.Add(new TrailShape(new Trail(4, ProgramCommon.GetRandomColor()),
                //	new Shape(40, 41, 42, 43, 44, 45, 46, 47)));
                //startingParams.TrailShapes.Add(new TrailShape(new Trail(4, ProgramCommon.GetRandomColor()),
                //	new Shape(48, 49, 50, 51, 52, 53, 54, 55)));
                //startingParams.TrailShapes.Add(new TrailShape(new Trail(4, ProgramCommon.GetRandomColor()),
                //	new Shape(56, 57, 58, 59, 60, 61, 62, 63)));

                var neomatrix = ZoneScaffolder.Instance.AddFadeCandyZone(zlmInner.Zones, "NeoMatrix", PixelType.FadeCandyWS2812Pixel,
                                                                         64, 1);
                zlmInner.CreateSingularProgramSet("", new Raindrops(), null, neomatrix, startingParams);
            }, Config.Get("NeoMatrixOneZone"));

            //Thread.Sleep(Timeout.Infinite);
            Thread.Sleep((int)(sleepSeconds != null ? sleepSeconds * 1000 : Timeout.Infinite));

            //cleanup
            zlm.Dispose();
        }
Exemple #9
0
        private void SetTrailColors(ClockedTrailShape clockedTrailShape)
        {
            var trailShape = clockedTrailShape.TrailShape;
            var leadIndex  = trailShape.Trail.LeadIndex;
            var leadPixel  = trailShape.Shape.Pixels[leadIndex];
            var trailEnd   = leadIndex;           //this changes in the for loop after these declarations
            var dotColor   = trailShape.Trail.Color;
            var overflow   = false;

            //establish last index of trail
            for (var j = 0; j < trailShape.Trail.Length; j++)
            {
                bool tempOverflow;
                trailEnd = trailShape.Shape.GetPreviousIndex(trailEnd, out tempOverflow);
                if (tempOverflow)
                {
                    overflow = true;
                }
            }

            for (var i = 0; i < trailShape.Shape.PixelCount; i++)
            {
                //darken pixels inside trail, blacken out the rest
                if (overflow ? (i < leadIndex || i >= trailEnd) : i < leadIndex && i >= trailEnd)
                {
                    ColorsToSend[trailShape.Shape.Pixels[i]] = GetColor(trailShape.Shape.Pixels[i]).Darken(trailShape.DarkenFactor);
                }
                else
                //if not sharing the shape with another trailshape, then clean out the rest of the shape
                if (!false)                 //was if (!ShareShape)
                {
                    ColorsToSend[trailShape.Shape.Pixels[i]] = Color.Black;
                }

                //set lead index color
                if (i == leadIndex)
                {
                    ColorsToSend[leadPixel] = dotColor ?? ProgramCommon.GetRandomColor();
                }
            }

            trailShape.Trail.LeadIndex = trailShape.Shape.GetNextIndex(leadIndex);

            if (trailShape.Trail.LeadIndex == 0)
            {
                trailShape.Trail.Color     = ProgramCommon.GetRandomColor().Darken(0.5);
                clockedTrailShape.Interval = clockedTrailShape.GetNewInterval();
            }

            //Console.WriteLine(trailShape.ToString());
        }
Exemple #10
0
        public override void Loop()
        {
            var sendColors = new Dictionary <int, Color>();

            TrailShapes.ForEach(trailShape =>
            {
                var leadIndex = trailShape.Trail.LeadIndex;
                var leadPixel = trailShape.Shape.Pixels[leadIndex];
                var trailEnd  = leadIndex;                //this changes in the for loop after these declarations
                var dotColor  = trailShape.Trail.Color;
                var overflow  = false;

                //establish last index of trail
                for (var j = 0; j < trailShape.Trail.Length; j++)
                {
                    bool tempOverflow;
                    trailEnd = trailShape.Shape.GetPreviousIndex(trailEnd, out tempOverflow);
                    if (tempOverflow)
                    {
                        overflow = true;
                    }
                }

                for (var i = 0; i < trailShape.Shape.PixelCount; i++)
                {
                    //darken pixels inside trail, blacken out the rest
                    if (overflow ? (i < leadIndex || i >= trailEnd) : i < leadIndex && i >= trailEnd)
                    {
                        sendColors[trailShape.Shape.Pixels[i]] = GetColor(trailShape.Shape.Pixels[i]).Darken(DarkenFactor);
                    }
                    else
                    //if not sharing the shape with another trailshape, then clean out the rest of the shape
                    if (!ShareShape)
                    {
                        sendColors[trailShape.Shape.Pixels[i]] = Color.Black;
                    }

                    //set lead index color
                    if (i == leadIndex)
                    {
                        sendColors[leadPixel] = dotColor ?? ProgramCommon.GetRandomColor();
                    }
                }

                trailShape.Trail.LeadIndex = trailShape.Shape.GetNextIndex(leadIndex);
            });

            SendColors(sendColors);                 //send frame
            ProgramCommon.Delay(DelayTime);         //pause before next iteration
            SyncContext?.SignalAndWait(100);
        }
        public Task RegisterTenant(FlatOwner flatowner, long?societyId, long?complexId, ApplicationUser currentUser)
        {
            return(Task.Run(async() =>
            {
                //Role Tenant = 7
                var memberRole = new ApplicationRole()
                {
                    Id = ProgramCommon.TenantRoleId, Name = "Tenant"
                };
                var roles = new ApplicationRole[] { memberRole };

                IdentityResult result = await CreateLogin(ProgramCommon.GetFormattedUsername(flatowner.Name), flatowner.EmailId, flatowner.MobileNo, roles
                                                          , null, flatowner.Name, flatowner.MobileNo, bBlocked: false, bChangePass: true, isback: false, societyId: societyId, complexId: complexId, currentUser: currentUser);
            }));
        }
Exemple #12
0
        static async Task Main(string[] args)
        {
            ProgramCommon.ConfigureSerilog();

            try
            {
                var host = CreateHostBuilder(args).Build();

                await host.RunAsync();
            }
            catch (Exception ex)
            {
                Log.Fatal("Uncaught exception: {Message} {Exception}", ex.Message, ex);
            }
        }
        public Task RegisterTenantFamily(FlatOwnerFamily family, long?societyId, long?complexId, ApplicationUser currentUser)
        {
            return(Task.Run(async() =>
            {
                //Role Tenant Family = 9
                var familyRole = new ApplicationRole()
                {
                    Id = ProgramCommon.TenantFamily, Name = "Tenant Family"
                };
                var roles = new ApplicationRole[] { familyRole };

                IdentityResult result = await CreateLogin(ProgramCommon.GetFormattedUsername(family.Name), null, family.MobileNo, roles
                                                          , null, family.Name, family.MobileNo, bBlocked: false, bChangePass: true, isback: false, societyId: societyId,
                                                          complexId: complexId, currentUser: currentUser);
            }));
        }
Exemple #14
0
        public override void Loop()
        {
            //DebugTools.AddEvent("ScrollDot.Loop", "START Looping ScrollDot");
            for (int i = 0; i < LightCount; i++)
            {
                //prepare frame
                var sendColors = new Dictionary <int, Color>();
                Zone.SortedLights.Keys.ToList().ForEach(lightIndex => sendColors.Add(lightIndex, Color.Black));
                sendColors[i] = DotColor ?? ProgramCommon.GetRandomColor();

                SendColors(sendColors);                         //send frame
                ProgramCommon.Delay(DelayTime);                 //pause before next iteration

                SyncContext?.SignalAndWait(100);
            }

            ///DebugTools.AddEvent("ScrollDot.Loop", "START Looping ScrollDot");
        }
        public async Task <IHttpActionResult> Generate([FromBody] dynamic inparams)
        {
            long     id         = inparams.id;
            DateTime generation = inparams.generation;

            var result = await _billingService.GenerateBill(id, generation);

            foreach (var item in result)
            {
                try
                {
                    var    emailProvider = new EmailServiceProvider();
                    string monthName     = ProgramCommon.GetMonthName(item.Month);
                    await emailProvider.GenerateBills(item.Name, item.Email, item.Amount, monthName, item.Year);
                }
                catch (Exception) { }
            }

            return(Ok());
        }
Exemple #16
0
 /// <summary>
 /// Blinks a set of colors holding the color for the given amount of milliseconds.
 /// </summary>
 /// <param name="colorsAndHoldTimes">List of tuples of colors and their hold times</param>
 /// <param name="outputMethod">Method to use to output the blinks.</param>
 /// <param name="syncContext">SyncContext to sync the blinking through.</param>
 /// <param name="tightness">Range: [1, 3]. Determines how tightly the blink is sycned.</param>
 public static void Blink(List <Tuple <Color, int> > colorsAndHoldTimes, Action <Color> outputMethod, SyncContext syncContext = null, int tightness = 1)
 {
     colorsAndHoldTimes.ForEach(tuple =>
     {
         if (syncContext != null && tightness < 2)
         {
             syncContext.SignalAndWait();
         }
         outputMethod(tuple.Item1);
         if (syncContext != null && tightness == 2)
         {
             syncContext.SignalAndWait();
         }
         ProgramCommon.Delay(tuple.Item2);
         if (syncContext != null && tightness >= 3)
         {
             syncContext.SignalAndWait();
         }
     });
 }
Exemple #17
0
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            await ProgramCommon.WaitForRabbitMQ(stoppingToken);

            await original.TryConnect(Constants.RabbitUri, Constants.ExchangeName, Constants.OriginalTopic, stoppingToken);

            await intermediate.TryConnect(Constants.RabbitUri, Constants.ExchangeName, Constants.IntermediateTopic, stoppingToken);

            logger.LogInformation("Connected");

            await Task.Delay(Constants.DelayAfterConnect, stoppingToken);

            // keep the service running
            while (!stoppingToken.IsCancellationRequested)
            {
                await Task.Delay(Constants.LoopDelay, stoppingToken);
            }

            logger.LogInformation("Finished");
        }
Exemple #18
0
        public override void Loop()
        {
            for (int i = 0; i < LightCount; i++)
            {
                //prepare frame
                var sendColors = new Dictionary <int, Color>();
                Blackout(sendColors);


                SetLeadingColor(sendColors, i, _colors);
                //SetTrailLeadingColor(sendColors, i, 3, true);
                if (i + 1 < LightCount)
                {
                    sendColors[i + 1] = DotColor != null ? (Color)DotColor : _colors[new Random().Next(0, _colors.Count - 1)];
                }

                SendColors(sendColors);                         //send frame
                ProgramCommon.Delay(DelayTime);                 //pause before next iteration

                SyncContext?.SignalAndWait(100);
            }
        }
Exemple #19
0
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            var stopWatch = System.Diagnostics.Stopwatch.StartNew();

            await ProgramCommon.WaitForRabbitMQ(stoppingToken);

            await rabbitClient.TryConnect(Constants.RabbitUri, Constants.ExchangeName, Constants.OriginalTopic, stoppingToken);

            logger.LogInformation("Connected");

            await Task.Delay(Constants.DelayAfterConnect, stoppingToken);

            int messageToSend = 1;

            while (!stoppingToken.IsCancellationRequested &&
                   messageToSend <= Constants.MaximumNumberOfMessagesToSend)
            {
                rabbitClient.SendMessage($"MSG_{messageToSend}");
                ++messageToSend;
                await Task.Delay(Constants.DelayBetweenMessages, stoppingToken);
            }

            logger.LogInformation("Finished sending messages after {TotalSeconds} seconds", stopWatch.Elapsed.TotalSeconds);
        }
Exemple #20
0
            /// <summary>
            /// Fades from one color to another color.
            /// </summary>
            /// <param name="colorStart">Color to fade from.</param>
            /// <param name="colorEnd">Color to fade to.</param>
            /// <param name="speed">The higher the speed, the more abruptly the colors will change. Max is 127.</param>
            /// <param name="sleepTime">How long each color set is displayed</param>
            /// <param name="loop">Whether or not to loop forever</param>
            /// <param name="outputMethod">Method to be used for outputting the fade.</param>
            /// <param name="endingColor">Last color the fade sets.</param>
            /// <param name="syncContext">Whether or not the fade should by synchronized with a SyncContext.</param>
            /// <param name="reverse">If true, after the fade is complete, another fade will occuur in from colorEnd to colorStart</param>
            /// <param name="cts">CancellationTokenSource to cancel the method call. If ForceStopFlag is set to true, it will stop immediately.
            /// If not, it will stop after the current fade is finished.</param>
            public void Fade(Color colorStart, Color colorEnd, int speed, int sleepTime, bool loop,
                             Action <Color> outputMethod, out Color?endingColor, SyncContext syncContext = null, bool reverse = false,
                             CancellationTokenSource cts = null)
            {
                if (speed > 127)
                {
                    throw new Exception("Speed cannot exceed 127.");
                }

                var   firstLoop    = true;
                Color?currentColor = null;

                while (firstLoop || loop)
                {
                    firstLoop = false;

                    float redDiff   = (colorEnd.R - colorStart.R);
                    float greenDiff = (colorEnd.G - colorStart.G);
                    float blueDiff  = (colorEnd.B - colorStart.B);

                    var redJump   = redDiff / (128 - speed);
                    var greenJump = greenDiff / (128 - speed);
                    var blueJump  = blueDiff / (128 - speed);

                    float redLevel   = colorStart.R;
                    float greenLevel = colorStart.G;
                    float blueLevel  = colorStart.B;

                    //fade
                    for (var a = 0; a < (128 - speed); a++)
                    {
                        redLevel   += redJump;
                        greenLevel += greenJump;
                        blueLevel  += blueJump;

                        var colorToOutput = Color.FromArgb(255, (int)redLevel, (int)greenLevel, (int)blueLevel);
                        outputMethod(colorToOutput);
                        currentColor = colorToOutput;

                        ProgramCommon.Delay(sleepTime);

                        syncContext?.SignalAndWait();

                        if (GetForceStopFlag != null && GetForceStopFlag() && cts != null && cts.IsCancellationRequested)
                        {
                            endingColor = currentColor;
                            return;
                        }
                    }

                    //if looping, loop back from 2nd color to 1st color before looping back
                    if (loop || reverse)
                    {
                        FadeStatic(colorEnd, colorStart, speed, sleepTime, false, outputMethod, out endingColor, syncContext, false, cts);
                    }
                }

                endingColor = currentColor;

                if (cts != null && cts.IsCancellationRequested)
                {
                    return;
                }
            }
Exemple #21
0
        /// <summary>
        /// Entry point
        /// </summary>
        /// <param name="args"></param>
        public static void Main(string[] args)
        {
            var startup = new Startup();

            ProgramCommon.Main(args, startup);
        }
        public int GetNewInterval()
        {
            var value = ProgramCommon.RandomIntBetween(IntervalAvg - IntervalVariability, IntervalAvg + IntervalVariability);

            return(value);
        }
        public Task <Complex> Create(Complex complex, ApplicationUser currentUser)
        {
            var taskResult = Task.Run(async() =>
            {
                using (var context = new DbContext())
                {
                    //check NoOfGate
                    //TODO check assets

                    if (context.ComplexList.Any(r => r.RegistrationNo == complex.RegistrationNo))
                    {
                        throw new Exception("Complex already registered with this Registration number.");
                    }
                    //check NoOfSocieties
                    if (complex.NoOfSocieties != complex.Societies.Count)
                    {
                        throw new Exception("No of societies count does not match with entered society list names count");
                    }

                    //check NoOfBuilding
                    if (complex.NoOfBuilding != complex.Facilities.Count(f => f.Type == (byte)EnFacilityType.Building))
                    {
                        throw new Exception("No of building count does not match with entered building list names count");
                    }

                    //check NoOfAmenities
                    if (complex.NoOfAmenities != complex.Facilities.Count(f => f.Type != (byte)EnFacilityType.Building))
                    {
                        throw new Exception("No of amenities count does not match with entered amenity list names count");
                    }

                    //Check duplicate society
                    if (complex.Societies.GroupBy(f => f.Name).Any(f => f.Count() > 1))
                    {
                        throw new Exception("Duplicate names found. All societies should have different name");
                    }

                    //Check duplicate facilities
                    if (complex.Facilities.GroupBy(f => f.Name + "|" + f.Wing).Any(f => f.Count() > 1))
                    {
                        throw new Exception("Duplicate names found. All facilities should have different name");
                    }

                    //check date of DateOfRegistration
                    if (complex.DateOfRegistration < complex.DateOfIncorporation)
                    {
                        throw new Exception("Date of registration cannot be before date of incorporation of the complex");
                    }

                    var facilities = complex
                                     .Facilities
                                     .Where(f => f.Type == (byte)EnFacilityType.Building)
                                     .Select(f => f.Name + '|' + f.Wing)
                                     .ToList();

                    foreach (var item in complex.Facilities)
                    {
                        if (item.Type == (byte)EnFacilityType.Building)
                        {
                            item.Name = item.Name.Split('|')[0];
                        }
                    }

                    //copy details from complex to society
                    foreach (var item in complex.Societies)
                    {
                        item.RegistrationNo      = complex.RegistrationNo;
                        item.DateOfIncorporation = complex.DateOfIncorporation;
                        item.DateOfRegistration  = complex.DateOfRegistration;
                        item.ContactPerson       = complex.ContactPerson;
                        item.PhoneNo             = complex.PhoneNo;
                        item.Email = complex.Email;

                        item.BillingCycle   = ProgramCommon.BillingCycle;
                        item.DueDays        = ProgramCommon.DueDays;
                        item.ApprovalsCount = 1;
                    }

                    foreach (var item in complex.Facilities)
                    {
                        if (item.Type == (byte)EnFacilityType.OpenParking)
                        {
                            item.IsParkingLot = true;
                        }
                    }

                    if (complex.City != null)
                    {
                        complex.CityId = complex.City.Id;
                        complex.City   = null;
                    }

                    if (complex.State != null)
                    {
                        complex.StateId = complex.State.Id;
                        complex.State   = null;
                    }

                    //assets
                    var assets = new List <SocietyAsset>();
                    assets.AddRange(complex.SocietyAssets);

                    complex.SocietyAssets = null;
                    context.ComplexList.Add(complex);
                    context.SaveChanges();


                    ApplicationUser user = new ApplicationUser
                    {
                        UserName    = ProgramCommon.GetFormattedUsername(complex.ContactPerson),
                        Email       = complex.Email,
                        Name        = complex.ContactPerson,
                        MaxAttempts = ProgramCommon.MaxAttempts,
                        bBlocked    = false,
                        bChangePass = true,
                        Deleted     = false,
                        CreatedBy   = currentUser.UserName,
                        ModifiedBy  = currentUser.UserName,
                        PhoneNumber = complex.PhoneNo,
                        IsBack      = false,
                        IsDefault   = true
                    };

                    //create complex user
                    await _userRepository.CreateComplexUser(user, complex.Id, currentUser);

                    //create society user
                    foreach (var item in complex.Societies)
                    {
                        await _userRepository.CreateSocietyUser(user, item.Id, currentUser);
                    }

                    //try
                    //{

                    //After saving facilities and societies map them
                    if (complex.Type == (byte)EnComplexType.SingleSociety)
                    {
                        //For single society
                        var society     = complex.Societies.First();
                        var facilities1 = complex.Facilities.Where(f => f.Type == (byte)EnFacilityType.Building).ToList();

                        foreach (var item in facilities1)
                        {
                            context.MapsSocietiesToFacilities.Add(new MapSocietiesToFacilities()
                            {
                                SocietyId = society.Id, FacilityId = item.Id
                            });
                        }

                        context.SaveChanges();
                    }
                    else
                    {
                        //For group of societies
                        foreach (var item in facilities)
                        {
                            var spilt = item.Split('|');
                            if (spilt.Length >= 3)
                            {
                                var facName  = spilt[0];
                                var socName  = spilt[1];
                                var wingName = spilt[2];

                                var fac = complex.Facilities.Where(f => f.Name == facName && f.Wing == wingName).First();
                                var soc = complex.Societies.Where(s => s.Name == socName).First();

                                context.MapsSocietiesToFacilities.Add(new MapSocietiesToFacilities()
                                {
                                    SocietyId = soc.Id, FacilityId = fac.Id
                                });
                            }
                        }

                        context.SaveChanges();
                    }

                    //add building assets
                    var buildingassets = assets.Where(a => a.Facility != null).ToList();
                    foreach (var item in buildingassets)
                    {
                        //After saving facilities and societies map them
                        if (complex.Type == (byte)EnComplexType.SingleSociety)
                        {
                            var spilt = item.Facility.Name.Split('|');
                            if (spilt.Length >= 2)
                            {
                                var facName  = spilt[0];
                                var wingName = item.Facility.Wing;

                                var fac = complex.Facilities.Where(f => f.Name == facName && f.Wing == wingName).First();

                                context.SocietyAssets.Add(new SocietyAsset()
                                {
                                    Name = item.Name, FacilityId = fac.Id, ComplexId = complex.Id, Quantity = 1
                                });
                            }
                        }
                        else
                        {
                            var spilt = item.Facility.Name.Split('|');
                            if (spilt.Length >= 2)
                            {
                                var facName  = spilt[0];
                                var wingName = item.Facility.Wing;

                                var fac = complex.Facilities.Where(f => f.Name == facName && f.Wing == wingName).First();

                                context.SocietyAssets.Add(new SocietyAsset()
                                {
                                    Name = item.Name, FacilityId = fac.Id, ComplexId = complex.Id, Quantity = 1
                                });
                            }
                        }
                    }
                    context.SaveChanges();


                    //var buildings = complex.Facilities.Where(f => f.Type == (byte)EnFacilityType.Building).ToList();
                    //for (int i = 0; i < buildings.Count; i++)
                    //{
                    //var building = buildings[i];

                    ////Code to add floors
                    //if (building.NoOfFloors == 0) continue;

                    //int flatPerFloor = building.NoOfFlats / building.NoOfFloors;

                    //for (int j = 0; j < building.NoOfFloors + 1; j++)
                    //{
                    //    //add Floor
                    //    var floor = new Floor()
                    //    {
                    //        Name = (j == 0 ? "Ground Floor" : "Floor " + j.ToString()),
                    //        FloorNumber = j,
                    //        FacilityId = building.Id,
                    //        Type = (j == 0 ? (byte)EnFloorType.Parkings : (byte)EnFloorType.Floor)
                    //    };

                    //    if (j > 0)
                    //    {
                    //        //add Flats
                    //        for (int k = 0; k < flatPerFloor; k++)
                    //        {
                    //            var flat = new Flat()
                    //            {
                    //                Name = ((floor.FloorNumber * 100) + (k + 1)).ToString()
                    //            };

                    //            floor.Flats.Add(flat);
                    //        }
                    //    }

                    //    context.Floors.Add(floor);
                    //    context.SaveChanges();
                    //}
                    //}


                    //}
                    //catch (Exception)
                    //{

                    //}

                    //add complex assets
                    var complexassets = assets.Where(a => a.Facility == null).ToList();
                    foreach (var item in complexassets)
                    {
                        context.SocietyAssets.Add(new SocietyAsset()
                        {
                            Name = item.Name, ComplexId = complex.Id, Quantity = 1
                        });
                    }
                    context.SaveChanges();

                    CreateNewArea(complex.Area, complex.Pincode);

                    return(complex);
                }
            });

            return(taskResult);
        }