private void AddAppUsers(MainDatabaseContext context)
        {
            SystemUser sysAdmin = context.SystemUsers.Where(x => x.Name == SystemUsers.SystemUserName).FirstOrDefault();

            if (!context.AppUsers.Any())
            {
                Language polish       = context.Languages.FirstOrDefault(x => x.LanguageDictionary == LanguageDictionary.Polish);
                AppRole  adminRole    = context.AppRoles.FirstOrDefault(x => x.AppRoleType == AppRoleType.Administrator);
                string   currentlogin = $"{Environment.MachineName}\\{Environment.UserName}";

                var admin = new AppUser()
                {
                    CreatedById = sysAdmin.Id,
                    CreatedDate = DateTime.Now,
                    Email       = "*****@*****.**",
                    IsActive    = true,
                    LastName    = "Administrator",
                    FirstName   = "",
                    LanguageId  = polish.Id,
                    Login       = currentlogin
                };
                context.AppUsers.Add(admin);

                var adminAdmin = new AppUserRole()
                {
                    CreatedById = sysAdmin.Id,
                    CreatedDate = DateTime.Now,
                    AppRole     = adminRole,
                    AppUser     = admin
                };
                context.AppUserRoles.Add(adminAdmin);

                context.SaveChanges();
            }
        }
Exemple #2
0
        public string OrderDelivered(Guid guid)
        {
            using (var context = new MainDatabaseContext())
            {
                var order = context.Orders
                            .Where(x => x.Id == guid)
                            .Include(x => x.Buyer)
                            .FirstOrDefault();

                if (order == null)
                {
                    return("order not found");
                }
                if (order.Status != OrderStatus.Delivering)
                {
                    return("invalid order status");
                }

                order.Delivered();

                _emailService.SendEmail(order.Buyer.Email, EmailType.OrderReceived);

                context.SaveChanges();
            }

            return("order delivered");
        }
        private void AddCoreData(MainDatabaseContext context)
        {
            if (!context.Languages.Any())
            {
                Language polish = new Language()
                {
                    CultureSymbol      = "pl-PL",
                    LanguageDictionary = LanguageDictionary.Polish
                };
                context.Languages.Add(polish);
                context.SaveChanges();
            }
            if (!context.SystemUsers.Any())
            {
                Language   polish = context.Languages.FirstOrDefault(x => x.LanguageDictionary == LanguageDictionary.Polish);
                SystemUser admin  = new SystemUser()
                {
                    CreatedDate = DateTime.Now,
                    Email       = SystemUsers.SystemUserEmail,
                    FirstName   = SystemUsers.SystemUserName,
                    IsActive    = true,
                    LastName    = "",
                    LanguageId  = polish.Id,
                    Name        = SystemUsers.SystemUserName
                };
                context.SystemUsers.Add(admin);
                context.SaveChanges();
                admin.CreatedById          = admin.Id;
                context.Entry(admin).State = EntityState.Modified;

                SystemUser unknownUser = new SystemUser()
                {
                    CreatedDate = DateTime.Now,
                    CreatedById = admin.Id,
                    Email       = SystemUsers.UnknownUserEmail,
                    FirstName   = SystemUsers.UnknownUserName,
                    IsActive    = true,
                    LastName    = "",
                    LanguageId  = polish.Id,
                    Name        = SystemUsers.UnknownUserName
                };
                context.SystemUsers.Add(unknownUser);

                context.SaveChanges();
            }
        }
 private void AddAppSeetings(MainDatabaseContext context)
 {
     if (!context.AppSettings.Any(r => r.Type == AppSettingEnum.ApplicationWebAddress))
     {
         AppSetting setting = new AppSetting();
         setting.Type  = AppSettingEnum.ApplicationWebAddress;
         setting.Value = "http://localhost:18828/";
         context.AppSettings.Add(setting);
     }
     context.SaveChanges();
 }
Exemple #5
0
        public IActionResult Put([FromBody] ICollection <ProductOrder> productOrders)
        {
            var order = new Order(productOrders);

            using (var context = new MainDatabaseContext())
            {
                context.Orders.Add(order);
                context.SaveChanges();
            }

            return(Ok(new { orderId = order.Id }));
        }
Exemple #6
0
        public IActionResult CreatePayment(Payment payment)
        {
            var email = User.GetEmail();

            var successfullPayment = false;

            using (var context = new MainDatabaseContext())
            {
                var order = context.Orders
                            .Where(x => x.Id == payment.OrderId)
                            .Include(p => p.ProductOrders.Select(po => po.Product))
                            .Include(p => p.Buyer)
                            .FirstOrDefault();

                if (order == null)
                {
                    return(View("Error"));
                }

                order.AddBuyer(GetOrCreateNewBuyer(context, email));

                if (payment.Type == PaymentType.Card)
                {
                    successfullPayment = _paymentProvider.SendPaymentData(payment);
                    order.PayByCard(payment, successfullPayment);
                    _emailService.SendEmail(email, successfullPayment ? EmailType.PaymentAccepted : EmailType.PaymentRefused);
                    context.SaveChanges();
                    return(successfullPayment ? View("Success") : View("Failure"));
                }
                else
                {
                    _emailService.SendEmail(email, EmailType.WaitingForTransfer);
                    order.PayByTransfer(payment);
                    context.SaveChanges();
                    return(View("Success"));
                }
            }
        }
Exemple #7
0
        public IActionResult Update([FromForm] int numberAvailable, int id)
        {
            using (var context = new MainDatabaseContext())
            {
                var productWarehouse = context.ProductsWarehouse
                                       .SingleOrDefault(x => x.Product.Id == id);

                productWarehouse.NumberAvailable = numberAvailable;

                context.SaveChanges();

                return(RedirectToAction("Index"));
            }
        }
        private void AddFunctionalities(MainDatabaseContext context)
        {
            if (!context.Functionalities.Any(x => x.FunctionalityType == FunctionalityType.GeneralSettings))
            {
                var functionality = new Functionality()
                {
                    FunctionalityType = FunctionalityType.GeneralSettings,
                    Name        = "Name",
                    Description = "Description",
                };
                context.Functionalities.Add(functionality);
            }

            context.SaveChanges();
        }
Exemple #9
0
        static void Main(string[] args)
        {
            MainDatabaseContext mainDatabase  = new MainDatabaseContext();
            shwaContext         worldDatabase = new shwaContext();

            var mapperConfiguration = new MapperConfiguration(cfg =>
            {
                cfg.CreateMap <Country, Fridge.Models.Main.Country>();
                cfg.CreateMap <City, Fridge.Models.Main.City>();
            });

            var mapper    = new Mapper(mapperConfiguration);
            var countries =
                mapper.Map <List <Country>, List <Fridge.Models.Main.Country> >(worldDatabase.Countries.Include(c => c.Cities)
                                                                                .ToList());

            mainDatabase.Countries.AddRange(countries);
            mainDatabase.SaveChanges();
        }
        private void AddAppRoles(MainDatabaseContext context)
        {
            SystemUser sysAdmin = context.SystemUsers.Where(x => x.Name == SystemUsers.SystemUserName).FirstOrDefault();

            if (!context.AppRoles.Any())
            {
                AppRole administrators = new AppRole()
                {
                    AppRoleType = AppRoleType.Administrator,
                    CreatedById = sysAdmin.Id,
                    CreatedDate = DateTime.Now,
                    Name        = "Administratorzy",
                    Description = "Grupa administratorów systemu",
                };
                context.AppRoles.Add(administrators);

                context.SaveChanges();
            }
        }
Exemple #11
0
        public string Init()
        {
            var mockedListOfProducts = new List <Product>
            {
                new Product(10.0m, "Bike", 1),
                new Product(5.0m, "Scooter", 2),
                new Product(4.99m, "Ball", 3),
                new Product(89.99m, "Helmet", 4)
            };

            var mockedListOfWarehouse = new List <ProductWarehouse>
            {
                new ProductWarehouse(mockedListOfProducts[0], 10),
                new ProductWarehouse(mockedListOfProducts[1], 10),
                new ProductWarehouse(mockedListOfProducts[2], 10),
                new ProductWarehouse(mockedListOfProducts[3], 10)
            };

            try
            {
                using (var context = new MainDatabaseContext())
                {
                    foreach (var mockedListOfProduct in mockedListOfProducts)
                    {
                        context.Products.Add(mockedListOfProduct);
                    }

                    foreach (var mockedWar in mockedListOfWarehouse)
                    {
                        context.ProductsWarehouse.Add(mockedWar);
                    }

                    context.SaveChanges();

                    return("data initialized");
                }
            }
            catch (Exception ex)
            {
                return($"there was a problem with \r\n- {ex.Message}");
            }
        }
Exemple #12
0
        public void Execute(IJobExecutionContext jobContext)
        {
            using (var context = new MainDatabaseContext())
            {
                var orders = context.Orders
                             .Where(x => x.Status == OrderStatus.WaitingForWarehouse)
                             .Include(o => o.Buyer)
                             .Include(o => o.ProductOrders.Select(p => p.Product))
                             .ToList();

                foreach (var order in orders)
                {
                    var cannotFulfill = (from productOrder in order.ProductOrders
                                         let productWarehouse = context.ProductsWarehouse.FirstOrDefault(pw => pw.Product.Id == productOrder.ProductId)
                                                                where productWarehouse.NumberAvailable < productOrder.Count
                                                                select productOrder).Any();

                    if (cannotFulfill)
                    {
                        break;
                    }
                    else
                    {
                        foreach (var productOrder in order.ProductOrders)
                        {
                            var productW = context.ProductsWarehouse
                                           .Include(pw => pw.Product)
                                           .FirstOrDefault(x => x.Product.Id == productOrder.ProductId);

                            productW.NumberAvailable = productW.NumberAvailable - productOrder.Count;
                        }

                        _emailService.SendEmail(order.Buyer.Email, EmailType.OrderSend);
                        order.Delivering();
                    }
                }

                context.SaveChanges();
            }
        }
        public void Execute(IJobExecutionContext jobContext)
        {
            using (var context = new MainDatabaseContext())
            {
                var orders = context.Orders
                             .Where(x => x.Status == OrderStatus.WaitingForPayment)
                             .Include(o => o.Buyer)
                             .ToList();

                foreach (var order in orders)
                {
                    var hasReceivedMoney = _transferCheckService.Check(order.Id);
                    if (hasReceivedMoney)
                    {
                        order.TransferReceived();
                        _emailService.SendEmail(order.Buyer.Email, EmailType.TransferReceived);
                    }
                }

                context.SaveChanges();
            }
        }
Exemple #14
0
        /// <summary>
        /// Updates the database based upon SessionDetails in the UpdatesToStore queue.
        /// If the SessioStoreData.SessionData entry is null, the data is removed.
        /// Runs in a loop until either Token.IsCancellationRequested is true.
        /// Will finish updating the database when we are disposing and there are still updates to store
        /// </summary>
        private void UpdateDatabase()
        {
            while (!this.token.IsCancellationRequested || (this.disposing && this.updatesToStore.Count > 0))
            {
                MainDatabaseContext context = new MainDatabaseContext();

                int count = 0;
                if (this.updatesToStore.Count > 0)
                {
                    while (this.updatesToStore.Count > 0 && count < 100)
                    {
                        count++;
                        SessionDetails session = this.updatesToStore.Dequeue();
                        if (session.Role == null)
                        {
                            if (context.SessionStore.Any(s => s.SessionId == session.SessionId))
                            {
                                context.SessionStore.Local.Where(s => s.SessionId == session.SessionId).ToList().ForEach(s => context.Entry(s).State = System.Data.Entity.EntityState.Deleted);
                            }
                            else
                            {
                                // Crashed on duplicate key error
                                context.Entry(session).State = System.Data.Entity.EntityState.Deleted;
                            }
                        }
                        else
                        {
                            SessionDetails newSession = new SessionDetails();
                            newSession.SessionId  = session.SessionId;
                            newSession.Role       = session.Role;
                            newSession.LastAccess = session.LastAccess;

                            if (context.SessionStore.Local.Any(s => s.SessionId == newSession.SessionId) && context.Entry(context.SessionStore.Local.Where(s => s.SessionId == newSession.SessionId).Single()).State != System.Data.Entity.EntityState.Deleted)
                            {
                                SessionDetails details = context.SessionStore.Local.Where(s => s.SessionId == newSession.SessionId).Single();
                                details.Role       = newSession.Role;
                                details.LastAccess = newSession.LastAccess;
                            }
                            else if (context.SessionStore.Any(s => s.SessionId == newSession.SessionId))
                            {
                                context.Entry(newSession).State = System.Data.Entity.EntityState.Modified;
                            }
                            else
                            {
                                context.Entry(newSession).State = System.Data.Entity.EntityState.Added;
                            }
                        }
                    }

                    if (count > 0)
                    {
                        try
                        {
                            context.SaveChanges();
                        }
                        catch (DbEntityValidationException e)
                        {
                            string errorResult = string.Empty;
                            foreach (var eve in e.EntityValidationErrors)
                            {
                                errorResult += "Entity of type \" " + eve.Entry.Entity.GetType().Name + "\" in state \"" + eve.Entry.State + "\" has the following validation errors: \n";
                                foreach (var ve in eve.ValidationErrors)
                                {
                                    errorResult += "- Property: \"" + ve.PropertyName + "\", Error: \"" + ve.ErrorMessage + "\" \n";
                                }
                            }

                            throw new DbEntityValidationException(errorResult, e);
                        }
                    }
                }
                else
                {
                    Thread.Sleep(100);
                }
            }
        }
        /// <summary>
        /// Synchronizing local contacts to server
        /// </summary>
        /// <returns>Result of operation: 0 - synchronization is success, 1 - synchrozination problems</returns>
        public static async Task <int> ContactsSynchronizationRequestAsync()
        {
            int resultOfSynchronization = 1;

            string receivedlink = "https://planningway.ru/contact/synchronization";
            string token        = (await FileSystemRequests.LoadUserEmailAndTokenFromFileAsync()).token;

            ApplicationDataContainer localSettings = ApplicationData.Current.LocalSettings;
            string deviceId = (string)localSettings.Values["DeviceId"];

            using (MainDatabaseContext db = new MainDatabaseContext())
            {
                #region Create anonymous types for sending to server

                // is_delete - list of local deleted items
                // story_list - list of local elements of the current user and not deleted from the local database

                var contacts = new
                {
                    is_delete  = db.Contacts.Where(i => i.IsDelete && i.EmailOfOwner == (string)localSettings.Values["email"]).Select(i => i.Id).ToList(),
                    story_list = db.Contacts.
                                 Where(i => i.EmailOfOwner == (string)localSettings.Values["email"] && !i.IsDelete).
                                 Select(i => new
                    {
                        create_at = i.CreateAt.Value.ToString("yyyy-MM-dd HH:mm:ss"),
                        id        = i.Id,
                        update_at = i.UpdateAt.Value.ToString("yyyy-MM-dd HH:mm:ss"),
                    }).ToList()
                };

                #endregion

                Debug.WriteLine($"Данные для сверки: {JsonSerialize(new { _csrf = token, idDevice = deviceId, contacts })}");
                var resultOfRequest = await BasePostRequestAsync(receivedlink, JsonSerialize(new { _csrf = token, idDevice = deviceId, contacts }));

                JObject jsonString = JObject.Parse(resultOfRequest);

                Debug.WriteLine($"Получаемые данные \n{jsonString}");

                #region Contacts processing

                #region Adding new to database

                // Get contacts items for adding to local database
                IList <Contact> receivedContacts = new List <Contact>();
                foreach (var result in jsonString["contacts"]["item"].Children().ToList())
                {
                    var searchResult = result.ToObject <Contact>();
                    receivedContacts.Add(searchResult);
                }

                // Add received contacts to local database
                db.Contacts.AddRange(receivedContacts);

                Debug.WriteLine($"Добавляем: {receivedContacts.Count} контактов");

                #endregion

                #region Remove from database

                // Get removed contacts, for removing from local database
                IList <string> removedContacts = new List <string>();
                foreach (var result in jsonString["contacts"]["is_delete"].Children().ToList())
                {
                    removedContacts.Add(result.ToObject <string>());
                }

                // Removing contacts from local database
                foreach (var removedContact in removedContacts)
                {
                    db.Contacts.Remove(db.Contacts.FirstOrDefault(i => i.Id == removedContact));
                }

                Debug.WriteLine($"Удаляем: {removedContacts.Count} контактов");

                #endregion

                #region Seding to server

                // Create sending contacts
                IList <string> sendedContacts = new List <string>();
                foreach (var result in jsonString["contacts"]["requires"].Children().ToList())
                {
                    sendedContacts.Add(result.ToObject <string>());
                }

                Debug.WriteLine($"Отправляемых: {sendedContacts.Count} контактов");

                #endregion

                #endregion

                var sendingData = new
                {
                    contacts = db.Contacts.Join
                               (
                        sendedContacts,
                        i => i.Id,
                        w => w,
                        (i, w) => new
                    {
                        id          = i.Id,
                        email       = i.Email,
                        name        = i.Name,
                        update_at   = i.UpdateAt.Value.ToString("yyyy-MM-dd HH:mm:ss"),
                        create_at   = i.CreateAt.Value.ToString("yyyy-MM-dd HH:mm:ss"),
                        personEmail = i.EmailOfOwner
                    }
                               )
                };

                string departureAddress    = "https://planningway.ru/contact/save";
                var    completeSendingData = new
                {
                    _csrf    = token,
                    idDevice = deviceId,
                    contacts = sendingData.contacts
                };

                Debug.WriteLine($"Отправляем данные:\n{JsonSerialize(completeSendingData)}");

                var finalResult = await BasePostRequestAsync(departureAddress, JsonSerialize(completeSendingData));

                jsonString = JObject.Parse(finalResult);
                resultOfSynchronization = (int)jsonString["answer"];

                if (resultOfSynchronization == 0)
                {
                    db.Contacts.RemoveRange(db.Contacts.Where(i => i.IsDelete && i.EmailOfOwner == (string)localSettings.Values["email"]));
                }

                db.SaveChanges();
            }

            return(resultOfSynchronization);
        }
        /// <summary>
        /// Synchronizing local calendars to server
        /// </summary>
        /// <returns>Result of operation: 0 - synchronization is success, 1 - synchrozination problems</returns>
        public static async Task <int> SynchronizationRequestAsync()
        {
            int resultOfSynchronization = 1;

            string receivedlink = "https://planningway.ru/data/synchronization";
            string token        = (await FileSystemRequests.LoadUserEmailAndTokenFromFileAsync()).token;

            ApplicationDataContainer localSettings = ApplicationData.Current.LocalSettings;
            string deviceId = (string)localSettings.Values["DeviceId"];

            using (MainDatabaseContext db = new MainDatabaseContext())
            {
                #region Create anonymous types for sending to server

                // is_delete - list of local deleted items
                // story_list - list of local elements of the current user and not deleted from the local database

                var areas = new
                {
                    is_delete  = db.Areas.Where(i => i.IsDelete && i.EmailOfOwner == (string)localSettings.Values["email"]).Select(i => i.Id).ToList(),
                    story_list = db.Areas.
                                 Where(i => i.EmailOfOwner == (string)localSettings.Values["email"] && !i.IsDelete).
                                 Select(i => new
                    {
                        create_at   = i.CreateAt.Value.ToString("yyyy-MM-dd HH:mm:ss"),
                        id          = i.Id,
                        update_at   = i.UpdateAt.Value.ToString("yyyy-MM-dd HH:mm:ss"),
                        personEmail = i.EmailOfOwner
                    }).ToList()
                };

                var projects = new
                {
                    is_delete  = db.Projects.Where(i => i.IsDelete && i.EmailOfOwner == (string)localSettings.Values["email"]).Select(i => i.Id).ToList(),
                    story_list = db.Projects.
                                 Where(i => i.EmailOfOwner == (string)localSettings.Values["email"] && !i.IsDelete).
                                 Select(i => new
                    {
                        create_at = i.CreateAt.Value.ToString("yyyy-MM-dd HH:mm:ss"),
                        id        = i.Id,
                        update_at = i.UpdateAt.Value.ToString("yyyy-MM-dd HH:mm:ss")
                    }).ToList()
                };

                var events = new
                {
                    is_delete  = db.MapEvents.Where(i => i.IsDelete && i.EmailOfOwner == (string)localSettings.Values["email"]).Select(i => i.Id).ToList(),
                    story_list = db.MapEvents.
                                 Where(i => i.EmailOfOwner == (string)localSettings.Values["email"] && !i.IsDelete).
                                 Select(i => new
                    {
                        create_at = i.CreateAt.Value.ToString("yyyy-MM-dd HH:mm:ss"),
                        id        = i.Id,
                        update_at = i.UpdateAt.Value.ToString("yyyy-MM-dd HH:mm:ss")
                    }).ToList()
                };

                #endregion

                Debug.WriteLine($"Данные для сверки: {JsonSerialize(new { _csrf = token, idDevice = deviceId, areas, projects, events })}");
                var resultOfRequest = await BasePostRequestAsync(receivedlink, JsonSerialize(new { _csrf = token, idDevice = deviceId, areas, projects, events }));

                JObject jsonString = JObject.Parse(resultOfRequest);

                Debug.WriteLine($"Получаемые данные \n{jsonString}");

                #region Areas processing

                #region Adding new to database

                // Get areas items for adding to local database
                IList <Area> receivedAreas = new List <Area>();
                foreach (var result in jsonString["areas"]["item"].Children().ToList())
                {
                    var searchResult = result.ToObject <Area>();
                    receivedAreas.Add(searchResult);
                }

                // Add received areas to local database
                db.Areas.AddRange(receivedAreas);

                Debug.WriteLine($"Добавляем: {receivedAreas.Count} зон");

                #endregion

                #region Remove from database

                // Get removed areas, for removing from local database
                IList <string> removedAreas = new List <string>();
                foreach (var result in jsonString["areas"]["is_delete"].Children().ToList())
                {
                    removedAreas.Add(result.ToObject <string>());
                }

                // Removing areas from local database
                foreach (var removedArea in removedAreas)
                {
                    db.Areas.Remove(db.Areas.FirstOrDefault(i => i.Id == removedArea));
                }

                Debug.WriteLine($"Удаляем: {removedAreas.Count} зон");

                #endregion

                #region Seding to server

                // Create sending areas
                IList <string> sendedAreas = new List <string>();
                foreach (var result in jsonString["areas"]["requires"].Children().ToList())
                {
                    sendedAreas.Add(result.ToObject <string>());
                }

                Debug.WriteLine($"Отправляемых: {sendedAreas.Count} зон");

                #endregion

                #endregion

                #region Projects processing

                #region Adding new to database

                // Get projects items for adding to local database
                IList <Project> receivedProjects = new List <Project>();
                foreach (var result in jsonString["projects"]["item"].Children().ToList())
                {
                    var searchResult = result.ToObject <Project>();
                    receivedProjects.Add(searchResult);
                }

                // Add received projects to local database
                db.Projects.AddRange(receivedProjects);

                Debug.WriteLine($"Добавляем: {receivedProjects.Count} проектов");

                #endregion

                #region Remove from database

                // Get removed projects, for removing from local database
                IList <string> removedProjects = new List <string>();
                foreach (var result in jsonString["projects"]["is_delete"].Children().ToList())
                {
                    removedProjects.Add(result.ToObject <string>());
                }

                // Removing projects from local database
                foreach (var removedProject in removedProjects)
                {
                    db.Projects.Remove(db.Projects.FirstOrDefault(i => i.Id == removedProject));
                }

                Debug.WriteLine($"Удаляем: {removedProjects.Count} проектов");

                #endregion

                #region Sending to server

                // Create sending projects
                IList <string> sendedProjects = new List <string>();
                foreach (var result in jsonString["projects"]["requires"].Children().ToList())
                {
                    sendedProjects.Add(result.ToObject <string>());
                }

                Debug.WriteLine($"Отправляемых: {sendedProjects.Count} проектов");

                #endregion

                #endregion

                #region MapEvents processing

                #region Adding to database

                // Get map events items for adding to local database
                IList <MapEvent> receivedMapEvents = new List <MapEvent>();
                foreach (var result in jsonString["events"]["item"].Children().ToList())
                {
                    var searchResult = result.ToObject <MapEvent>();
                    receivedMapEvents.Add(searchResult);
                }

                // Add received map events to local database
                db.MapEvents.AddRange(receivedMapEvents);

                Debug.WriteLine($"Добавляем: {receivedMapEvents.Count} событий");

                #endregion

                #region Remove from database

                // Get removed map events, for removing from local database
                IList <string> removedMapEvents = new List <string>();
                foreach (var result in jsonString["events"]["is_delete"].Children().ToList())
                {
                    removedMapEvents.Add(result.ToObject <string>());
                }

                // Removing map events from local database
                foreach (var removedMapEvent in removedMapEvents)
                {
                    db.MapEvents.Remove(db.MapEvents.FirstOrDefault(i => i.Id == removedMapEvent));
                }

                Debug.WriteLine($"Удаляем: {removedMapEvents.Count} событий");

                #endregion

                #region Sending to server

                // Create sending map events
                IList <string> sendedMapEvents = new List <string>();
                foreach (var result in jsonString["events"]["requires"].Children().ToList())
                {
                    sendedMapEvents.Add(result.ToObject <string>());
                }

                Debug.WriteLine($"Отправляемых: {sendedMapEvents.Count} событий");

                #endregion

                #endregion

                var sendingData = new
                {
                    areas = db.Areas.Join
                            (
                        sendedAreas,
                        i => i.Id,
                        w => w,
                        (i, w) => new
                    {
                        id          = i.Id,
                        summary     = i.Name,
                        description = i.Description,
                        color       = i.Color,
                        favourite   = i.Favorite,
                        update_at   = i.UpdateAt.Value.ToString("yyyy-MM-dd HH:mm:ss"),
                        create_at   = i.CreateAt.Value.ToString("yyyy-MM-dd HH:mm:ss"),
                        personEmail = i.EmailOfOwner
                    }
                            ),
                    projects = db.Projects.Join
                               (
                        sendedProjects,
                        i => i.Id,
                        w => w,
                        (i, w) => new
                    {
                        id          = i.Id,
                        summary     = i.Name,
                        description = i.Description,
                        color       = i.Color,
                        area_id     = i.AreaId,
                        update_at   = i.UpdateAt.Value.ToString("yyyy-MM-dd HH:mm:ss"),
                        create_at   = i.CreateAt.Value.ToString("yyyy-MM-dd HH:mm:ss"),
                        personEmail = i.EmailOfOwner,
                        from        = i.From
                    }
                               ),
                    events = db.MapEvents.Join
                             (
                        sendedMapEvents,
                        i => i.Id,
                        w => w,
                        (i, w) => new
                    {
                        id                 = i.Id,
                        start              = i.Start.ToString("yyyy-MM-dd HH:mm:ss"),
                        end                = i.End.ToString("yyyy-MM-dd HH:mm:ss"),
                        location           = i.Location,
                        summary            = i.Name,
                        description        = i.Description,
                        color              = i.Color,
                        recurrence         = i.EventInterval,
                        project_id         = i.ProjectId,
                        update_at          = i.UpdateAt.Value.ToString("yyyy-MM-dd HH:mm:ss"),
                        create_at          = i.CreateAt.Value.ToString("yyyy-MM-dd HH:mm:ss"),
                        projectPersonEmail = i.ProjectOwnerEmail,
                        personEmail        = i.EmailOfOwner,
                        isPublic           = i.IsPublic,
                        timeNotification   = i.NotificationTime.ToString("yyyy-MM-dd HH:mm:ss"),
                        people             = i.UserBind
                    }
                             )
                };

                string departureAddress    = "https://planningway.ru/data/save";
                var    completeSendingData = new
                {
                    _csrf    = token,
                    idDevice = deviceId,
                    areas    = sendingData.areas,
                    projects = sendingData.projects,
                    events   = sendingData.events,
                };

                Debug.WriteLine($"Отправляем данные:\n{JsonSerialize(completeSendingData)}");

                var finalResult = await BasePostRequestAsync(departureAddress, JsonSerialize(completeSendingData));

                jsonString = JObject.Parse(finalResult);
                resultOfSynchronization = (int)jsonString["answer"];


                if (resultOfSynchronization == 0)
                {
                    db.Areas.RemoveRange(db.Areas.Where(i => i.IsDelete && i.EmailOfOwner == (string)localSettings.Values["email"]));
                    db.Projects.RemoveRange(db.Projects.Where(i => i.IsDelete && i.EmailOfOwner == (string)localSettings.Values["email"]));
                    db.MapEvents.RemoveRange(db.MapEvents.Where(i => i.IsDelete && i.EmailOfOwner == (string)localSettings.Values["email"]));
                }

                db.SaveChanges();
            }

            return(resultOfSynchronization);
        }