public void CreateNewSubscription(long followerId, long observedId)
        {
            if (this.IsUserSubscribedToUser(followerId, observedId))
            {
                return;
            }

            var userSubscription = new UserSubscription { FollowerId = followerId, ObservedId = observedId };
            this.database.UsersSubscriptions.Add(userSubscription);
            this.database.SaveChanges();
        }
 public Task <bool> SubscribeToUser(UserSubscription userSubscription)
 {
     throw new NotImplementedException();
 }
Beispiel #3
0
        public static void AddData(ModelBuilder builder)
        {
            // seed user roles
            var roleAdmin = new Role()
            {
                Id = Guid.NewGuid(), Name = "Administrator"
            };
            var roleModerator = new Role()
            {
                Id = Guid.NewGuid(), Name = "Moderator"
            };
            var roleSimple = new Role()
            {
                Id = Guid.NewGuid(), Name = "Simple"
            };
            // seed user states
            var stateActive = new State()
            {
                Id = Guid.NewGuid(), Name = "Active"
            };
            var stateFreezed = new State()
            {
                Id = Guid.NewGuid(), Name = "Freezed"
            };
            // seed users
            var user1 = new User()
            {
                Id       = Guid.NewGuid(),
                Email    = "*****@*****.**",
                Nickname = "lineyk27",
                // decode - 12345678
                PasswordHash   = "ef797c8118f02dfb649607dd5d3f8c7623048c9c063d532cc95c5ed7a898a64f",
                JoinDate       = DateTime.Now,
                BeginStateDate = DateTime.Now,
                EndStateDate   = new DateTime(2050, 12, 12),
                StateId        = stateActive.Id,
                RoleId         = roleSimple.Id,
                PictureName    = "https://res.cloudinary.com/dgepkksyl/image/upload/v1590192208/user_pics/IMG_0572_ut5cxl.jpg"
            };
            var user2 = new User()
            {
                Id       = Guid.NewGuid(),
                Nickname = "kit22",
                Email    = "*****@*****.**",
                // decode - password
                PasswordHash   = "5e884898da28047151d0e56f8dc6292773603d0d6aabbdd62a11ef721d1542d8",
                JoinDate       = DateTime.Now,
                BeginStateDate = DateTime.Now,
                EndStateDate   = new DateTime(2050, 12, 13),
                StateId        = stateActive.Id,
                RoleId         = roleSimple.Id,
                PictureName    = "https://res.cloudinary.com/dgepkksyl/image/upload/v1590194554/user_pics/index_gz1sqk.jpg"
            };
            // seed communities
            var community1 = new Community()
            {
                Id            = Guid.NewGuid(),
                Name          = "Cars",
                Description   = "Community for car lovers.",
                CreationDate  = DateTime.Now,
                CreatorUserId = user1.Id,
                PictureName   = "https://res.cloudinary.com/dgepkksyl/image/upload/v1590193947/user_pics/cars2_c5wyqk.jpg"
            };
            var community2 = new Community()
            {
                Id            = Guid.NewGuid(),
                Name          = "Sport",
                Description   = "Community footbal, basketall, tenis and other.",
                CreationDate  = DateTime.Now,
                CreatorUserId = user1.Id,
                PictureName   = "https://res.cloudinary.com/dgepkksyl/image/upload/v1590193942/user_pics/sport2_fs0yab.jpg"
            };

            var community3 = new Community()
            {
                Id            = Guid.NewGuid(),
                Name          = "Food",
                Description   = "Community for those who love cooking.",
                CreationDate  = DateTime.Now,
                CreatorUserId = user1.Id,
                PictureName   = "https://res.cloudinary.com/dgepkksyl/image/upload/v1590193991/user_pics/food2_uckrcb.jpg"
            };

            var community4 = new Community()
            {
                Id            = Guid.NewGuid(),
                Name          = "Programming",
                Description   = "IT industry communicates here.",
                CreationDate  = DateTime.Now,
                CreatorUserId = user1.Id,
                PictureName   = "https://res.cloudinary.com/dgepkksyl/image/upload/v1590193952/user_pics/programing_wlmjj4.jpg"
            };

            var community5 = new Community()
            {
                Id            = Guid.NewGuid(),
                Name          = "Culture",
                Description   = "Culture life.",
                CreationDate  = DateTime.Now,
                CreatorUserId = user1.Id,
                PictureName   = "https://res.cloudinary.com/dgepkksyl/image/upload/v1590193976/user_pics/culture2_hdclpb.jpg"
            };
            // seed subscriptions
            var subscription1 = new UserSubscription()
            {
                Id = Guid.NewGuid(),
                SubscriberUserId   = user1.Id,
                SubscriptionUserId = user2.Id
            };

            builder.Entity <User>().HasData(user1, user2);
            builder.Entity <Community>().HasData(community1, community2, community3, community4, community5);
            builder.Entity <UserSubscription>().HasData(subscription1);
            builder.Entity <State>().HasData(stateActive, stateFreezed);
            builder.Entity <Role>().HasData(roleAdmin, roleModerator, roleSimple);
        }
Beispiel #4
0
        private void ProcessCSV(HttpPostedFileBase file)
        {
            List <List <string> > csvList = new List <List <string> >();

            using (CsvReader reader = new CsvReader(file.InputStream))
            {
                csvList = reader.Parse();
            }

            //Process of creating automatic user subscriptions:
            //1. Group all users by section
            //2. For each student in a given section, assign them to all other students in that section
            Dictionary <int, List <int> > sectionGroups = new Dictionary <int, List <int> >();

            //this loop takes care of process step #1
            foreach (List <string> row in csvList)
            {
                if (row.Count == 2)
                {
                    int studentId = 0;
                    int section   = 0;
                    if (Int32.TryParse(row[0], out studentId) == true)
                    {
                        if (Int32.TryParse(row[1], out section) == true)
                        {
                            if (sectionGroups.ContainsKey(section) == false)
                            {
                                sectionGroups.Add(section, new List <int>());
                            }
                            if (sectionGroups[section].Contains(studentId) == false)
                            {
                                sectionGroups[section].Add(studentId);
                            }
                        }
                    }
                }
            }

            //this loop takes care of process step #2
            foreach (int section in sectionGroups.Keys)
            {
                List <int> sectionList         = sectionGroups[section];
                List <UserSubscription> dbSubs = (from sub in Db.UserSubscriptions
                                                  where
                                                  (
                                                      sectionList.Contains(sub.ObserverInstitutionId) ||
                                                      sectionList.Contains(sub.SubjectInstitutionId)
                                                  ) &&
                                                  sub.ObserverSchoolId == CurrentUser.SchoolId
                                                  select sub
                                                  ).ToList();

                foreach (int observerId in sectionGroups[section])
                {
                    foreach (int subjectId in sectionGroups[section])
                    {
                        if (observerId.CompareTo(subjectId) != 0)
                        {
                            UserSubscription dbSub = dbSubs.Where(s => s.ObserverInstitutionId == observerId).Where(s => s.SubjectInstitutionId == subjectId).FirstOrDefault();
                            if (dbSub == null)
                            {
                                UserSubscription sub = new UserSubscription()
                                {
                                    ObserverInstitutionId = observerId,
                                    SubjectInstitutionId  = subjectId,

                                    //assume that the subject and observer attend the same institution as the
                                    //person uploading the CSV file
                                    ObserverSchoolId = CurrentUser.SchoolId,
                                    SubjectSchoolId  = CurrentUser.SchoolId
                                };
                                Db.UserSubscriptions.Add(sub);
                            }
                        }
                    }
                }
            }

            //save any DB changes
            Db.SaveChanges();
        }
        private UserSubscription InitOrIncreaseUserSubscriptionObject(int userId, int subscriptionId, UserSubscription userSubscription = null)
        {
            var validFor = TimeSpan.FromDays(30);
            var now      = DateTime.UtcNow;

            if (userSubscription == null)
            {
                userSubscription = new UserSubscription
                {
                    UserId         = userId,
                    IsActive       = true,
                    SubscriptionId = subscriptionId,
                    ValidDays      = validFor,
                    ValidAt        = now.AddDays(validFor.TotalDays),
                    CreatedAt      = now,
                    ModifiedAt     = now
                };
            }
            else
            {
                userSubscription.IsActive   = true;
                userSubscription.ValidAt    = userSubscription.ValidAt.AddDays(validFor.TotalDays);
                userSubscription.ValidDays  = validFor;
                userSubscription.ModifiedAt = now;
            }

            return(userSubscription);
        }
        //public UserController(WorkersInMotionJobContext context)
        //{
        // //   this._IJobRepository = new JobRepository(context);
        //}

        #endregion
        public ActionResult Index(string id = "", string regionguid = "", string selection = "")
        {
            Logger.Debug("Inside User Controller- Index");
            try
            {
                if (Session["OrganizationGUID"] != null)
                {
                    if (!string.IsNullOrEmpty(id))
                    {
                        TempData["TabName"] = id;
                    }
                    else
                    {
                        TempData["TabName"] = "Details";
                    }
                    mycompany pmycompany = new mycompany();
                    pmycompany.OrganizationEditView = new OrganizationEditView();
                    pmycompany.AspNetUserViewModel  = new AspNetUserViewModel();
                    pmycompany.TerritoryViewModel   = new TerritoryViewModel();
                    pmycompany.RegionViewModel      = new RegionViewModel();


                    //switch (id)
                    //{
                    //    case "Users":
                    //        ViewBag.TabName = "Users";
                    var userList = new AspNetUserViewModel();
                    userList.Users = new List <AspUser>();
                    var appUser = new List <UserProfile>();

                    appUser = _IUserProfileRepository.GetUserProfilesbyOrganizationGUID(new Guid(Session["OrganizationGUID"].ToString())).OrderBy(sort => sort.FirstName).ToList();

                    foreach (var user in appUser.ToList())
                    {
                        UserSubscription userSubscription = _IUserSubscriptionRepository.GetUserSubscriptionByUserID(user.UserGUID);
                        GlobalUser       _globalUser      = _IGlobalUserRepository.GetGlobalUserByID(user.UserGUID);
                        string           Regionname       = string.Empty;
                        string           Territoryname    = string.Empty;
                        string           Groupname        = string.Empty;
                        string           userType         = string.Empty;
                        if (_globalUser != null)
                        {
                            OrganizationUsersMap _orgUserMap = _IOrganizationRepository.GetOrganizationUserMapByUserGUID(user.UserGUID);

                            if (_orgUserMap != null && _orgUserMap.RegionGUID != null)
                            {
                                Regionname = _IRegionRepository.GetRegionNameByRegionGUID(new Guid(_orgUserMap.RegionGUID.ToString()));
                            }
                            else
                            {
                                Regionname = "";
                            }
                            if (_orgUserMap != null && _orgUserMap.TerritoryGUID != null)
                            {
                                Territoryname = _ITerritoryRepository.GetTerritoryNameByTerritoryGUID(new Guid(_orgUserMap.TerritoryGUID.ToString()));
                            }
                            else
                            {
                                Territoryname = "";
                            }


                            // Groupname = _IGroupRepository.GetGroupNameByGroupGUID(new Guid(_globalUser.GroupGUID.ToString()));
                            userType = _IGlobalUserRepository.GetUserTypeByRoleID(_globalUser.Role_Id);
                        }
                        string UserTypeName = _IGlobalUserRepository.GetUserRoleName(user.UserGUID);

                        if (userSubscription != null)
                        {
                            userList.Users.Add(new AspUser {
                                UserTypeName = UserTypeName, RegionName = Regionname, TerritoryName = Territoryname, GroupName = Groupname, OrganizationSubscriptionGUID = userSubscription.OrganizationSubscriptionGUID.ToString(), UserType = userType, IsActive = userSubscription.IsActive, SubscriptionGUID = userSubscription.UserSubscriptionGUID.ToString(), FirstName = user.FirstName, LastName = user.LastName, Id = user.UserGUID.ToString(), EmailID = user.EmailID, MobilePhone = user.MobilePhone, City = user.City, State = user.State, Country = user.Country
                            });
                        }
                    }

                    OrganizationSubscription orgSubscription = new OrganizationSubscription();
                    if (Session["UserType"] != null && Session["UserType"].ToString() != "WIM_A")
                    {
                        orgSubscription = _IOrganizationSubscriptionRepository.GetOrganizationSubscriptionByOrgID(new Guid(Session["OrganizationGUID"].ToString()));
                        if (orgSubscription != null)
                        {
                            ViewBag.EnableCreateUserButton = "true";
                        }
                        else
                        {
                            ViewBag.EnableCreateUserButton = "false";
                        }
                        //if (orgSubscription != null && orgSubscription.SubscriptionPurchased > orgSubscription.SubscriptionConsumed)
                        //{
                        //    ViewBag.EnableCreateUserButton = "true";
                        //}
                        //else
                        //{
                        //    ViewBag.EnableCreateUserButton = "false";
                        //}
                    }
                    else
                    {
                        ViewBag.EnableCreateUserButton = "false";
                    }
                    pmycompany.AspNetUserViewModel = userList;
                    //    break;
                    //case "Region":
                    //    ViewBag.TabName = "Regions";
                    var territoryList = new TerritoryViewModel();
                    territoryList.Territory = new List <TerritoryModel>();
                    List <Territory> appTerritory = new List <Territory>();
                    if (!string.IsNullOrEmpty(regionguid) && regionguid != Guid.Empty.ToString())
                    {
                        appTerritory         = _ITerritoryRepository.GetTerritoryByRegionGUID(new Guid(regionguid)).ToList();
                        TempData["TabName"]  = "Markets";
                        ViewBag.AddTerritory = "true";
                        ViewBag.Id           = regionguid;
                    }
                    else
                    {
                        appTerritory = _ITerritoryRepository.GetTerritoryByOrganizationGUID(new Guid(Session["OrganizationGUID"].ToString())).ToList();
                    }
                    foreach (var territory in appTerritory.ToList())
                    {
                        territoryList.Territory.Add(new TerritoryModel {
                            Name = territory.Name, TerritoryGUID = territory.TerritoryGUID.ToString(), RegionGUID = territory.RegionGUID != null ? territory.RegionGUID.ToString() : Guid.Empty.ToString(), Description = territory.Description, OrganizationGUID = territory.OrganizationGUID != null ? territory.OrganizationGUID.ToString() : Guid.Empty.ToString()
                        });
                    }
                    StringBuilder sb = new StringBuilder();
                    sb.Append("<div class='actions'>");
                    sb.Append("<div class='btn-group'>");
                    if (!string.IsNullOrEmpty(regionguid) && regionguid != Guid.Empty.ToString())
                    {
                        sb.Append("<a href='#' id='ulaworkergroup' class='btn green' data-toggle='dropdown'><i class='icon-map-marker'></i> " + _IRegionRepository.GetRegionNameByRegionGUID(new Guid(regionguid)) + " <i class='icon-angle-down'></i></a>");
                    }
                    else
                    {
                        if (!string.IsNullOrEmpty(selection) && selection == "All")
                        {
                            sb.Append("<a href='#' id='ulaworkergroup' class='btn green' data-toggle='dropdown'><i class='icon-map-marker'></i>All<i class='icon-angle-down'></i></a>");
                        }
                        else
                        {
                            sb.Append("<a href='#' id='ulaworkergroup' class='btn green' data-toggle='dropdown'><i class='icon-map-marker'></i> Select Region <i class='icon-angle-down'></i></a>");
                        }
                    }
                    sb.Append("<ul id='ulworkgroup' style='height:100px;overflow-y:scroll' class='dropdown-menu pull-right'>");
                    if (string.IsNullOrEmpty(selection) || selection != "All")
                    {
                        sb.Append("<li><a href=" + Url.Action("Index", "MyCompany", new { id = "Markets", selection = "All" }) + ">All</a></li>");
                    }
                    List <Region> RegList = _IRegionRepository.GetRegionByOrganizationGUID(new Guid(Session["OrganizationGUID"].ToString())).ToList();
                    foreach (Region item in RegList)
                    {
                        sb.Append("<li><a href=" + Url.Action("Index", "MyCompany", new { regionguid = item.RegionGUID.ToString() }) + " data-groupguid=" + item.RegionGUID + ">" + item.Name + "</a></li>");
                    }
                    sb.Append("</ul>");
                    sb.Append("</div>");
                    sb.Append("</div>");
                    ViewBag.RegionList            = sb.ToString();
                    pmycompany.TerritoryViewModel = territoryList;
                    //    break;
                    //case "Territory":
                    //    ViewBag.TabName = "Territories";
                    var regionList = new RegionViewModel();
                    regionList.Region = new List <RegionModel>();
                    var appRegion = _IRegionRepository.GetRegionByOrganizationGUID(new Guid(Session["OrganizationGUID"].ToString())).ToList();
                    foreach (var region in appRegion.ToList())
                    {
                        regionList.Region.Add(new RegionModel {
                            Name = region.Name, RegionGUID = region.RegionGUID.ToString(), Description = region.Description, OrganizationGUID = region.OrganizationGUID != null ? region.OrganizationGUID.ToString() : Guid.Empty.ToString()
                        });
                    }
                    pmycompany.RegionViewModel = regionList;
                    //    break;
                    //case "Organization":
                    //    ViewBag.TabName = "Details";
                    OrganizationEditView organization = new OrganizationEditView();
                    organization.OrganizationGUID = new Guid(Session["OrganizationGUID"].ToString());
                    Organization Organization = _IOrganizationRepository.GetOrganizationByID(organization.OrganizationGUID);
                    if (organization != null)
                    {
                        organization.OrganizationFullName = Organization.OrganizationFullName;
                        organization.OrganizationName     = Organization.OrganizationFullName.Trim();
                        organization.OrganizationGUID     = Organization.OrganizationGUID;
                        organization.Website            = Organization.Website;
                        organization.Phone              = Organization.Phone;
                        organization.TimeZone           = Organization.TimeZone.ToString();
                        organization.AddressLine1       = Organization.AddressLine1;
                        organization.AddressLine2       = Organization.AddressLine2;
                        organization.ImageURL           = Organization.ImageURL;
                        organization.City               = Organization.City;
                        organization.Country            = Organization.Country;
                        organization.State              = Organization.State;
                        organization.ZipCode            = Organization.ZipCode;
                        organization.EmailID            = Organization.EmailID;
                        organization.IsActive           = Organization.IsActive;
                        organization.IsDeleted          = Organization.IsDeleted;
                        organization.CreatedDate        = Organization.CreateDate;
                        organization.CreateBy           = Organization.CreateBy;
                        pmycompany.OrganizationEditView = organization;
                    }

                    //    break;
                    //default:
                    //    ViewBag.TabName = "Details";
                    //    OrganizationEditView porganization = new OrganizationEditView();
                    //    porganization.OrganizationGUID = new Guid(Session["OrganizationGUID"].ToString());
                    //    Organization pOrganization = _IOrganizationRepository.GetOrganizationByID(porganization.OrganizationGUID);
                    //    if (porganization != null)
                    //    {
                    //        porganization.OrganizationFullName = pOrganization.OrganizationFullName;
                    //        porganization.OrganizationName = pOrganization.OrganizationFullName.Trim();
                    //        porganization.OrganizationGUID = pOrganization.OrganizationGUID;
                    //        porganization.Website = pOrganization.Website;
                    //        porganization.Phone = pOrganization.Phone;
                    //        porganization.TimeZone = pOrganization.TimeZone.ToString();
                    //        porganization.AddressLine1 = pOrganization.AddressLine1;
                    //        porganization.AddressLine2 = pOrganization.AddressLine2;
                    //        porganization.ImageURL = pOrganization.ImageURL;
                    //        porganization.City = pOrganization.City;
                    //        porganization.Country = pOrganization.Country;
                    //        porganization.State = pOrganization.State;
                    //        porganization.ZipCode = pOrganization.ZipCode;
                    //        porganization.EmailID = pOrganization.EmailID;
                    //        porganization.IsActive = pOrganization.IsActive;
                    //        porganization.IsDeleted = pOrganization.IsDeleted;
                    //        porganization.CreatedDate = pOrganization.CreateDate;
                    //        porganization.CreateBy = pOrganization.CreateBy;
                    //        pmycompany.OrganizationEditView.Add(porganization);
                    //    }
                    //    break;
                    // }



                    return(View(pmycompany));
                }
                else
                {
                    return(RedirectToAction("SessionTimeOut", "User"));
                }
            }
            catch (Exception ex)
            {
                Logger.Error(ex.Message);
                return(RedirectToAction("Login", "User"));
            }
        }
Beispiel #7
0
        public static void AddUser(UserSubscription user)
        {
            // 获取某个主题订阅
            SubscriptionsByTopic subscriptionsByTopic;

            SubscriptionsByTopic.TryGetValue(user.Topic, out subscriptionsByTopic);

            // 如果主题不存在,新添加
            if (subscriptionsByTopic == null)
            {
                subscriptionsByTopic = new SubscriptionsByTopic()
                {
                    Topic = user.Topic
                };

                var wasAdded = SubscriptionsByTopic.TryAdd(user.Topic, subscriptionsByTopic);
            }


            // 获取某个主题用户的全部订阅
            SubscriptionsByUser subscriptionsByUser;

            subscriptionsByTopic.SubscriptionsByUser.TryGetValue(user.ConnectionId, out subscriptionsByUser);

            // 主题用户不存在,新添加
            if (subscriptionsByUser == null)
            {
                subscriptionsByUser = new SubscriptionsByUser()
                {
                    ConnectionId = user.ConnectionId,
                };

                var wasAdded = subscriptionsByTopic.SubscriptionsByUser.TryAdd(user.ConnectionId, subscriptionsByUser);
            }

            // 用户订阅值同步
            subscriptionsByUser.SubscriptionsByTopic.AddOrUpdate(user.Topic, user, (key, oldValue) => oldValue = user);
        }
        private static async Task <SubscriptionResponse> ProcessSubscription(BitcornContext dbContext, SubscriptionResponse output, SubRequest subRequest, Subscription subInfo, SubscriptionTier requestedTierInfo, User user)
        {
            decimal cost = 0;

            //if tier usdt cost has been initialized, the corn cost has to be calculated
            if (requestedTierInfo.CostUsdt != null && requestedTierInfo.CostUsdt > 0)
            {
                cost = await CalculateUsdtToCornCost(dbContext, requestedTierInfo);
            }
            // check if cost is initialized properly
            else if (requestedTierInfo.CostCorn != null && requestedTierInfo.CostCorn > 0)
            {
                cost = requestedTierInfo.CostCorn.Value;
            }
            else
            {
                throw new ArgumentException($"Invalid cost setting on subscription tier id:{requestedTierInfo.SubscriptionId}");
            }
            //set the amount that will be removed from subscriber to the response object
            output.Cost = cost;
            //initialize array of existing subscriptions
            UserSubcriptionTierInfo[] existingSubscriptions = new UserSubcriptionTierInfo[0];
            if (user != null)
            {
                //set data to existing subscriptions array
                existingSubscriptions = await GetUserSubscriptions(dbContext, user)
                                        .Where(t => t.SubscriptionTier.SubscriptionId == subInfo.SubscriptionId).ToArrayAsync();
            }
            //initialize reference to existing subtierinfo
            UserSubcriptionTierInfo existingSubscription = null;
            //initialize current substate
            var subState = SubscriptionState.None;

            //if any subscriptions were found
            if (existingSubscriptions.Any())
            {
                //set existing subtierinfo
                existingSubscription = existingSubscriptions[0];
                //if sub has expired, set substate to expired
                if (subInfo.HasExpired(existingSubscription.UserSubscription))
                {
                    subState = SubscriptionState.Expired;
                }
                //if existing sub has not expired, but the tier is below, set subState to TierDown
                else if (existingSubscription.SubscriptionTier.Tier < requestedTierInfo.Tier)
                {
                    subState = SubscriptionState.TierDown;
                }
                //else, the user is subscribed
                else
                {
                    subState = SubscriptionState.Subscribed;
                }
            }
            //initialize reference to usersubscription & tx request
            UserSubscription sub       = null;
            TxRequest        txRequest = null;
            //if current user sub state is not subscribed & the client confirmed the cost to be equal to the cost amount, attempt to subscribe
            var costDiff = Math.Abs(subRequest.Amount - cost);

            if (subState != SubscriptionState.Subscribed && costDiff <= 100000)//subRequest.Amount == cost)
            {
                //initialize recipient of the transaction
                string[] to = new string[1];
                //default to bitcornhub if no subscription owner has been set
                int recipientId = TxUtils.BitcornHubPK;
                //if subscription owner is set, overwrite bitcornhub
                if (subInfo.OwnerUserId != null && subInfo.OwnerUserId > 0)
                {
                    recipientId = subInfo.OwnerUserId.Value;
                }

                to[0] = $"userid|{recipientId}";
                //initialize tx request
                txRequest = new TxRequest(user, cost, subRequest.Platform, "$sub", to);
                //prepare transaction for saving
                var processInfo = await TxUtils.ProcessRequest(txRequest, dbContext);

                var transactions = processInfo.Transactions;
                if (transactions != null && transactions.Length > 0)
                {
                    StringBuilder sql = new StringBuilder();
                    //check if transaction can be executed
                    if (processInfo.WriteTransactionOutput(sql))
                    {
                        //transaction is ready to be saved
                        switch (subState)
                        {
                        case SubscriptionState.None:
                            //user was previously not subscribed, create instance of usersubscription and point it to the user
                            sub = new UserSubscription();
                            sub.SubscriptionId     = subInfo.SubscriptionId;
                            sub.SubscriptionTierId = requestedTierInfo.SubscriptionTierId;
                            sub.UserId             = user.UserId;
                            sub.FirstSubDate       = DateTime.Now;
                            sub.SubCount           = 1;
                            dbContext.UserSubscription.Add(sub);
                            break;

                        case SubscriptionState.TierDown:
                        case SubscriptionState.Expired:
                            //previous subscription was found, update subscription tier
                            existingSubscription.UserSubscription.SubscriptionTierId = requestedTierInfo.SubscriptionTierId;
                            existingSubscription.UserSubscription.SubCount          += 1;
                            sub = existingSubscription.UserSubscription;
                            break;

                        default:
                            break;
                        }
                        //set subscription date to now
                        sub.LastSubDate = DateTime.Now;

                        await DbOperations.ExecuteSqlRawAsync(dbContext, sql.ToString());

                        await dbContext.SaveAsync(IsolationLevel.RepeatableRead);

                        //create subtx that will link user, corntx and usersubscription together
                        var subTx = new SubTx();
                        subTx.UserId             = user.UserId;
                        subTx.SubTxId            = transactions[0].TxId.Value;
                        subTx.UserSubscriptionId = sub.UserSubscriptionId;
                        dbContext.SubTx.Add(subTx);

                        //if user was not subscribed before, attempt to share the payment with a referrer
                        if (!await TrySharePaymentWithReferrer(dbContext, output, subRequest, subInfo, requestedTierInfo, user, recipientId, cost, subState, subTx))
                        {
                            await dbContext.SaveAsync();
                        }

                        subState = SubscriptionState.Subscribed;
                    }
                    //append receipt object with what client requested
                    await TxUtils.AppendTxs(transactions, dbContext, subRequest.Columns);

                    var tx = transactions[0];

                    output.TxId = tx.TxId;
                    output.User = tx.From;
                }
            }
            //couldn't process transaction
            if (txRequest == null)
            {
                //fill out response object
                await PopuplateUserResponse(dbContext, subRequest, output, user);

                if (existingSubscription != null)
                {
                    sub = existingSubscription.UserSubscription;
                }
            }

            if (subState == SubscriptionState.Subscribed && sub != null)
            {
                var end = output.SubscriptionEndTime = sub.LastSubDate.Value.AddDays(subInfo.Duration);
                //calculate days left
                output.DaysLeft = Math.Ceiling((end.Value - DateTime.Now).TotalDays);
                //setup sub info
                output.UserSubscriptionInfo = await GetUserSubscriptions(dbContext, user)
                                              .Where(t => t.SubscriptionTier.SubscriptionId == subInfo.SubscriptionId).FirstOrDefaultAsync();
            }
            return(output);
        }
Beispiel #9
0
        public async ValueTask <(string, ApplicationUser, string)> GetOrCreateExternalLoginUser(string provider,
                                                                                                string key, string email, string firstName, string lastName, Role role, bool isVerified, string picture)
        {
            // Login already linked to a user
            var user = await Item().Include(u => u.UserSubscriptions)
                       .ThenInclude(s => s.Subscription)
                       .FirstOrDefaultAsync(u => u.Email.ToLower() == email.Trim().ToLower());

            //there is a user
            if (user != null)
            {
                //user has not used this provider key
                if (user.Provider?.ToLower() != provider?.ToLower() && key != user.ProviderKey)
                {
                    //user exists but hasn't used external.
                    user.Provider    = provider;
                    user.ProviderKey = key;
                    var(s, u, e)     = await Update(user);

                    if (!s)
                    {
                        return(null, null, e);
                    }
                    user = u;
                }
                UserSubscription userSub      = user.UserSubscriptions.Where(u => u.StartedOn + new TimeSpan(u.Subscription.Duration, 0, 0, 0) >= DateTime.Now).FirstOrDefault();
                TimeSpan         durationLeft = new TimeSpan(0, 0, 0);
                bool             hasDuration  = false;
                if (userSub is object)
                {
                    durationLeft      = (userSub.StartedOn + new TimeSpan(userSub.Subscription.Duration, 0, 0, 0)) - DateTime.Now;
                    hasDuration       = durationLeft > new TimeSpan(0, 0, 0, 0);
                    user.IsSubscribed = hasDuration;
                }
                return(_auth.GetToken(email, Enum.GetName(typeof(Role), user.Role), userSub is object, durationLeft, hasDuration), user, null);
            }

            // No user exists with this email address and provider, we create a new one
            else
            {
                user = new ApplicationUser
                {
                    Email       = email,
                    Provider    = provider,
                    FirstName   = firstName,
                    SurName     = lastName,
                    ProviderKey = key,
                    Image       = picture,
                    Role        = role,
                    IsVerified  = isVerified,
                    VerifiedOn  = DateTime.Now
                };

                var(s, u, e) = await Add(user);

                if (!s)
                {
                    return(null, null, e);
                }
                user = u;

                //await AddUserCoursesAsync(user.Id);
            }
            return(_auth.GetToken(email, Enum.GetName(typeof(Role), user.Role), false, new TimeSpan(0, 0, 0), false), user, null);
        }
Beispiel #10
0
 public SubscribeToUserRequest(UserSubscription userSubscription) : base(RequestType.SubscribeToUser)
 {
     this.UserSubscription = userSubscription;
 }
 public void setUser(UserSubscription user)
 {
     _session.Set <UserSubscription>(key, user);
 }
        private static void SeedServer(IDependencyScope scope)
        {
            var userManager                = (IHaloUserManager)scope.GetService(typeof(IHaloUserManager));
            var userBaseDataRepository     = (IUserBaseDataRepository)scope.GetService(typeof(IUserBaseDataRepository));
            var userSubscriptionRepository = (IUserSubscriptionRepository)scope.GetService(typeof(IUserSubscriptionRepository));
            var clanRepository             = (IClanRepository)scope.GetService(typeof(IClanRepository));
            var clanMembershipRepository   = (IClanMembershipRepository)scope.GetService(typeof(IClanMembershipRepository));

            try
            {
                var clan = clanRepository.FindByNamePrefixAsync("Clan1").Result.FirstOrDefault();
                if (clan == null)
                {
                    clan = new Clan
                    {
                        Name        = "Clan1",
                        Description = "First clan",
                        Tag         = "TAG"
                    };
                    clanRepository.CreateAsync(clan).Wait();
                }

                HaloUser testUser1 = new HaloUser
                {
                    UserName = "******"
                };
                HaloUser testUser2 = new HaloUser
                {
                    UserName = "******"
                };
                userManager.CreateAsync(testUser1, "123").Wait();
                userManager.CreateAsync(testUser2, "456").Wait();

                UserBaseData testUser1Data = new UserBaseData
                {
                    User = new UserId
                    {
                        Id = testUser1.UserId
                    },
                    Nickname = "User1",
                    Clan     = new ClanId
                    {
                        Id = 0
                    },
                    ClanTag   = "",
                    Level     = 2,
                    BattleTag = "BattleTag1"
                };

                UserBaseData testUser2Data = new UserBaseData
                {
                    User = new UserId
                    {
                        Id = testUser2.UserId
                    },
                    Nickname = "User2",
                    Clan     = new ClanId
                    {
                        Id = 0
                    },
                    ClanTag   = "",
                    Level     = 10,
                    BattleTag = "BattleTag2"
                };

                userBaseDataRepository.SetUserBaseDataAsync(testUser1Data);
                userBaseDataRepository.SetUserBaseDataAsync(testUser2Data);

                var testUser1ClanMembership = new ClanMembership
                {
                    UserId = testUser1.UserId,
                    ClanId = clan.ClanId,
                    Role   = 1
                };

                clanMembershipRepository.CreateAsync(testUser1ClanMembership).Wait();

                var testUser1Subscription = new UserSubscription
                {
                    UserId       = testUser1.UserId,
                    FriendUserId = testUser2.UserId
                };
                userSubscriptionRepository.CreateAsync(testUser1Subscription).Wait();
            }
            catch (Exception)
            {
                Debug.WriteLine("Server initialization failed.");
            }
        }
Beispiel #13
0
        public async Task ReceiveUserSubscriptionUpdates()
        {
            var port = NextPort;

            var serializer = new XmlSerializer();

            using (var server = new Server(new TcpListener(new IPEndPoint(IPAddress.Loopback, port), new TestHandshaker()), new XmlSerializer())) {
                server.Attach(new ServerSubscriptionModule(server, new TestChatDataProvider(server.ConnectionProvider)));

                server.Initialize();

                using (var clientA = CreateClient("clientA"))
                    using (var clientB = CreateClient("clientB")) {
                        clientA.ReconnectRetryDelay = TimeSpan.FromSeconds(1);
                        clientB.ReconnectRetryDelay = TimeSpan.FromSeconds(1);

                        clientA.InitializeSubscriptionModule();
                        clientB.InitializeSubscriptionModule();

                        using (var eveUpdateReceived = new AutoResetEvent(false)) {
                            UserSubscription update = null;

                            var updateCount = 0;

                            clientA.Subscription().UserSubscriptionUpdated += (sender, args) => {
                                update = args.Subscription;
                                updateCount++;
                                eveUpdateReceived.Set();
                            };

                            await clientA.Connect("localhost:" + port);

                            var result = await clientA.Subscription().RPC.AddUserSubscription("clientB", null);

                            Assert.NotNull(result);

                            if (!eveUpdateReceived.WaitOne(MaxTimeout))
                            {
                                Assert.Fail("clientA never got an update :(");
                            }

                            Assert.NotNull(update);

                            Assert.AreEqual(UpdateType.Add, update.UpdateType);
                            Assert.AreEqual("clientA", update.SubscriberUserId);
                            Assert.AreEqual("clientB", update.UserId);
                            Assert.AreEqual(null, update.Category);

                            update.Category = "chicken";

                            result = null;
                            result = await clientA.Subscription().RPC.UpdateUserSubscription(update);

                            if (!eveUpdateReceived.WaitOne(MaxTimeout))
                            {
                                Assert.Fail("clientA never got an update :(");
                            }

                            Assert.NotNull(result);

                            Assert.AreEqual(UpdateType.Update, update.UpdateType);
                            Assert.AreEqual("clientA", update.SubscriberUserId);
                            Assert.AreEqual("clientB", update.UserId);
                            Assert.AreEqual("chicken", update.Category);

                            result = null;
                            await clientA.Subscription().RPC.RemoveUserSubscription(update.Id);

                            Assert.AreEqual(UpdateType.Remove, update.UpdateType);
                            Assert.AreEqual("clientA", update.SubscriberUserId);
                            Assert.AreEqual("clientB", update.UserId);
                            Assert.AreEqual("chicken", update.Category);

                            Assert.AreEqual(3, updateCount);
                        }
                    }
            }
        }
Beispiel #14
0
 /// <summary>
 /// Initializes a new instance of an object.
 /// </summary>
 /// <param name="subscription">Subscription.</param>
 public PaymentOptions(UserSubscription subscription) : this(subscription.RenewedTo, subscription.RenewedToDuration)
 {
 }
 public static bool HasExpired(this Subscription subscription, UserSubscription user)
 {
     return(DateTime.Now > user.LastSubDate.Value.AddDays(subscription.Duration));
 }
 private NameAndCountUserSubscription ProjectToNameAndCountUserSubscription(UserSubscription arg)
 {
     return new NameAndCountUserSubscription
     {
         Id = arg.Id,
         Name = arg.Observed.DisplayName,
         Count = arg.EntriesToRead.Count(x => !x.IsRead)
     };
 }
Beispiel #17
0
        private AspNetUserViewModel UserDetails()
        {
            #region UserDetails
            try
            {
                var userList = new AspNetUserViewModel();
                userList.Users = new List <AspUser>();
                var appUser = new List <UserProfile>();

                appUser = _IUserProfileRepository.GetUserProfilesbyOrganizationGUID(new Guid(Session["OrganizationGUID"].ToString())).OrderBy(sort => sort.FirstName).ToList();

                foreach (var user in appUser.ToList())
                {
                    UserSubscription userSubscription = _IUserSubscriptionRepository.GetUserSubscriptionByUserID(user.UserGUID);
                    GlobalUser       _globalUser      = _IGlobalUserRepository.GetGlobalUserByID(user.UserGUID);
                    string           Regionname       = string.Empty;
                    string           Territoryname    = string.Empty;
                    string           Groupname        = string.Empty;
                    string           userType         = string.Empty;
                    if (_globalUser != null)
                    {
                        OrganizationUsersMap _orgUserMap = _IOrganizationRepository.GetOrganizationUserMapByUserGUID(user.UserGUID);

                        if (_orgUserMap != null && _orgUserMap.RegionGUID != null)
                        {
                            Regionname = _IRegionRepository.GetRegionNameByRegionGUID(new Guid(_orgUserMap.RegionGUID.ToString()));
                        }
                        else
                        {
                            Regionname = "";
                        }
                        if (_orgUserMap != null && _orgUserMap.TerritoryGUID != null)
                        {
                            Territoryname = _ITerritoryRepository.GetTerritoryNameByTerritoryGUID(new Guid(_orgUserMap.TerritoryGUID.ToString()));
                        }
                        else
                        {
                            Territoryname = "";
                        }

                        //Regionname = _IRegionRepository.GetRegionNameByRegionGUID(new Guid(_IOrganizationRepository.GetOrganizationUserMapByUserGUID(user.UserGUID).RegionGUID.ToString()));
                        //Territoryname = _ITerritoryRepository.GetTerritoryNameByTerritoryGUID(new Guid(_IOrganizationRepository.GetOrganizationUserMapByUserGUID(user.UserGUID).TerritoryGUID.ToString()));
                        userType = _IGlobalUserRepository.GetUserTypeByRoleID(_globalUser.Role_Id);
                    }
                    string UserTypeName = _IGlobalUserRepository.GetUserRoleName(user.UserGUID);

                    if (userSubscription != null)
                    {
                        userList.Users.Add(new AspUser {
                            UserTypeName = UserTypeName, RegionName = Regionname, TerritoryName = Territoryname, GroupName = Groupname, OrganizationSubscriptionGUID = userSubscription.OrganizationSubscriptionGUID.ToString(), UserType = userType, IsActive = userSubscription.IsActive, SubscriptionGUID = userSubscription.UserSubscriptionGUID.ToString(), FirstName = user.FirstName, LastName = user.LastName, Id = user.UserGUID.ToString(), EmailID = user.EmailID, MobilePhone = user.MobilePhone, City = user.City, State = user.State, Country = user.Country
                        });
                    }
                }

                OrganizationSubscription orgSubscription = new OrganizationSubscription();
                if (Session["UserType"] != null && Session["UserType"].ToString() != "WIM_A")
                {
                    orgSubscription = _IOrganizationSubscriptionRepository.GetOrganizationSubscriptionByOrgID(new Guid(Session["OrganizationGUID"].ToString()));
                    if (orgSubscription != null)
                    {
                        ViewBag.EnableCreateUserButton = "true";
                    }
                    else
                    {
                        ViewBag.EnableCreateUserButton = "false";
                    }
                    //if (orgSubscription != null && orgSubscription.SubscriptionPurchased > orgSubscription.SubscriptionConsumed)
                    //{
                    //    ViewBag.EnableCreateUserButton = "true";
                    //}
                    //else
                    //{
                    //    ViewBag.EnableCreateUserButton = "false";
                    //}
                }
                else
                {
                    ViewBag.EnableCreateUserButton = "false";
                }
                return(userList);
            }
            catch (Exception ex)
            {
                Logger.Error(ex.Message);
                return(null);
            }
            #endregion
        }
Beispiel #18
0
        public ActionResult Index()
        {
            UserSubscription _userSubscription = new UserSubscription();
            // _userSubscription = Mapper.Map<UserSubscription>(_userService.GetUserSubscriptionDetails());
            string decodedHTML  = "";
            string decodedHTML2 = "";

            if (_userSubscription != null)
            {
                decodedHTML  = HttpUtility.HtmlDecode(_userSubscription.AllAccessTermsOfService);
                decodedHTML2 = HttpUtility.HtmlDecode(_userSubscription.EnterpriseTermsOfService);
            }

            Editor Editor1 = new Editor(System.Web.HttpContext.Current, "Editor1");

            Editor1.LoadFormData(decodedHTML);
            Editor1.ClientFolder = "/richtexteditor/";
            Editor1.Width        = Unit.Pixel(1050);
            Editor1.Height       = Unit.Pixel(660);
            Editor1.ResizeMode   = RTEResizeMode.Disabled;

            Editor1.SetSecurity("Gallery", "newimagepath", "AllowAccess", "true");
            Editor1.SetSecurity("Gallery", "newimagepath", "StoragePath", "~" + GlobalConst.FolderName.Storage + GlobalConst.ConstantChar.ForwardSlash + GlobalConst.FolderName.Org + HCRGCLIENT.OrganizationID + GlobalConst.ConstantChar.ForwardSlash + GlobalConst.FolderName.RTEUpload, true);
            Editor1.SetSecurity("Gallery", "newimagepath ", "StorageName", "Image Files");

            Editor1.SetSecurity("Image", "newimagepath", "AllowAccess", "true");
            Editor1.SetSecurity("Image", "newimagepath", "StoragePath", "~" + GlobalConst.FolderName.Storage + GlobalConst.ConstantChar.ForwardSlash + GlobalConst.FolderName.Org + HCRGCLIENT.OrganizationID + GlobalConst.ConstantChar.ForwardSlash + GlobalConst.FolderName.RTEUpload, true);
            Editor1.SetSecurity("Image", "newimagepath ", "StorageName", "Image Files");

            Editor1.SetSecurity("Video", "newimagepath", "AllowAccess", "true");
            Editor1.SetSecurity("Video", "newimagepath", "StoragePath", "~" + GlobalConst.FolderName.Storage + GlobalConst.ConstantChar.ForwardSlash + GlobalConst.FolderName.Org + HCRGCLIENT.OrganizationID + GlobalConst.ConstantChar.ForwardSlash + GlobalConst.FolderName.RTEUpload, true);
            Editor1.SetSecurity("Video", "newimagepath ", "StorageName", "Video Files");

            Editor1.SetSecurity("Document", "newimagepath", "AllowAccess", "true");
            Editor1.SetSecurity("Document", "newimagepath", "StoragePath", "~" + GlobalConst.FolderName.Storage + GlobalConst.ConstantChar.ForwardSlash + GlobalConst.FolderName.Org + HCRGCLIENT.OrganizationID + GlobalConst.ConstantChar.ForwardSlash + GlobalConst.FolderName.RTEUpload, true);
            Editor1.SetSecurity("Document", "newimagepath ", "StorageName", "Document Files");

            Editor1.SetSecurity("Template", "newimagepath", "AllowAccess", "true");
            Editor1.SetSecurity("Template", "newimagepath", "StoragePath", "~" + GlobalConst.FolderName.Storage + GlobalConst.ConstantChar.ForwardSlash + GlobalConst.FolderName.Org + HCRGCLIENT.OrganizationID + GlobalConst.ConstantChar.ForwardSlash + GlobalConst.FolderName.RTEUpload, true);
            Editor1.SetSecurity("Template", "newimagepath ", "StorageName", "Templates");


            Editor1.FullScreen    = false;
            Editor1.DisabledItems = "save, help";
            string content = Request.Form["Editor1"];

            Editor1.MvcInit();
            ViewData["Editor"] = Editor1.MvcGetString();
            Editor1.ResizeMode = RTEResizeMode.Disabled;

            Editor Editor2 = new Editor(System.Web.HttpContext.Current, "Editor2");

            Editor2.LoadFormData(decodedHTML2);
            Editor2.ClientFolder  = "/richtexteditor/";
            Editor2.Width         = Unit.Pixel(1050);
            Editor2.Height        = Unit.Pixel(660);
            Editor2.ResizeMode    = RTEResizeMode.Disabled;
            Editor2.FullScreen    = false;
            Editor2.DisabledItems = "save, help";
            string content2 = Request.Form["Editor2"];

            Editor2.MvcInit();
            ViewData["Editor2"] = Editor2.MvcGetString();
            Editor2.ResizeMode  = RTEResizeMode.Disabled;

            return(View());
        }
Beispiel #19
0
        private void ClientThread(Socket client)
        {
            Console.WriteLine("Client thread started");
            while (true)
            {
                //read
                byte[] rcvLenBytes = new byte[4];
                client.Receive(rcvLenBytes);
                int    rcvLen         = BitConverter.ToInt32(rcvLenBytes, 0);
                byte[] dataFromClient = new byte[rcvLen];
                client.Receive(dataFromClient);
                string message = Encoding.ASCII.GetString(dataFromClient, 0, rcvLen);
                Console.WriteLine(message);
                Request request =
                    JsonSerializer.Deserialize <Request>(Encoding.ASCII.GetString(dataFromClient, 0, rcvLen));
                if (message.Equals("stop"))
                {
                    Console.WriteLine(message);
                    break;
                }
                //respond
                switch (request.Type)
                {
                case RequestType.AddPost:

                    AddPostRequest addPostRequest         = JsonSerializer.Deserialize <AddPostRequest>(message);
                    Post           newPost                = DbPersistence.AddPost(addPostRequest.Post);
                    string         responseMessageAddPost = JsonSerializer.Serialize(new AddPostRequest(newPost));
                    int            toSendLenAddPost       = Encoding.ASCII.GetByteCount(responseMessageAddPost);
                    byte[]         toSendBytesAddPost     = Encoding.ASCII.GetBytes(responseMessageAddPost);
                    byte[]         toSendLenBytesAddPost  = BitConverter.GetBytes(toSendLenAddPost);
                    client.Send(toSendLenBytesAddPost);
                    client.Send(toSendBytesAddPost);
                    break;

                case RequestType.DeletePost:

                    DeletePostRequest deletePostRequest = JsonSerializer.Deserialize <DeletePostRequest>(message);
                    DbPersistence.DeletePost(deletePostRequest.PostId);
                    int    toSendDelPost         = Encoding.ASCII.GetByteCount(message);
                    byte[] toSendBytesDelPost    = Encoding.ASCII.GetBytes(message);
                    byte[] toSendLenBytesDelPost = BitConverter.GetBytes(toSendDelPost);
                    client.Send(toSendLenBytesDelPost);
                    client.Send(toSendBytesDelPost);
                    break;

                case RequestType.DeleteUser:

                    DeleteUserRequest deleteUserRequest = JsonSerializer.Deserialize <DeleteUserRequest>(message);
                    DbPersistence.DeleteUser(deleteUserRequest.UserId);
                    int    toSendDelUser         = Encoding.ASCII.GetByteCount(message);
                    byte[] toSendBytesDelUser    = Encoding.ASCII.GetBytes(message);
                    byte[] toSendLenBytesDelUser = BitConverter.GetBytes(toSendDelUser);
                    client.Send(toSendLenBytesDelUser);
                    client.Send(toSendBytesDelUser);
                    break;

                case RequestType.GetPosts:
                    List <Post> posts = DbPersistence.GetPosts();
                    if (posts == null)
                    {
                        posts = new List <Post>();
                    }
                    string getPostsResponseMessage = JsonSerializer.Serialize(new GetPostsResponse(posts));
                    int    toGetPosts           = Encoding.ASCII.GetByteCount(getPostsResponseMessage);
                    byte[] toSendLenGetPosts    = BitConverter.GetBytes(toGetPosts);
                    byte[] dataToClientGetPosts = Encoding.ASCII.GetBytes(getPostsResponseMessage);
                    client.Send(toSendLenGetPosts);
                    client.Send(dataToClientGetPosts);
                    break;

                case RequestType.GetUsers:
                    List <User> users = DbPersistence.GetUsers();
                    if (users == null)
                    {
                        users = new List <User>();
                    }
                    string getUsersResponseMessage = JsonSerializer.Serialize(new GetUsersResponse(users));
                    int    toGetUsers           = Encoding.ASCII.GetByteCount(getUsersResponseMessage);
                    byte[] toSendLenGetUsers    = BitConverter.GetBytes(toGetUsers);
                    byte[] dataToClientGetUsers = Encoding.ASCII.GetBytes(getUsersResponseMessage);
                    client.Send(toSendLenGetUsers);
                    client.Send(dataToClientGetUsers);
                    break;

                case RequestType.PostUser:
                    PostUserRequest postUserRequest         = JsonSerializer.Deserialize <PostUserRequest>(message);
                    User            newUser                 = DbPersistence.AddUser(postUserRequest.User);
                    string          responseMessagePostUser = JsonSerializer.Serialize(new PostUserRequest(newUser));
                    int             toSendPostUser          = Encoding.ASCII.GetByteCount(responseMessagePostUser);
                    byte[]          toSendBytesPostUser     = Encoding.ASCII.GetBytes(responseMessagePostUser);
                    byte[]          toSendLenBytesPostUser  = BitConverter.GetBytes(toSendPostUser);
                    client.Send(toSendLenBytesPostUser);
                    client.Send(toSendBytesPostUser);
                    break;

                case RequestType.UpdatePost:
                    UpdatePostRequest updatePostRequest = JsonSerializer.Deserialize <UpdatePostRequest>(message);
                    DbPersistence.UpdatePost(updatePostRequest.Post);
                    int    toSendUpdatePost         = Encoding.ASCII.GetByteCount(message);
                    byte[] toSendBytesUpdatePost    = Encoding.ASCII.GetBytes(message);
                    byte[] toSendLenBytesUpdatePost = BitConverter.GetBytes(toSendUpdatePost);
                    client.Send(toSendLenBytesUpdatePost);
                    client.Send(toSendBytesUpdatePost);
                    break;

                case RequestType.UpdateUser:
                    UpdateUserRequest updateUserRequest = JsonSerializer.Deserialize <UpdateUserRequest>(message);
                    DbPersistence.UpdateUser(updateUserRequest.User);
                    int    toSendUpdateUser         = Encoding.ASCII.GetByteCount(message);
                    byte[] toSendBytesUpdateUser    = Encoding.ASCII.GetBytes(message);
                    byte[] toSendLenBytesUpdateUser = BitConverter.GetBytes(toSendUpdateUser);
                    client.Send(toSendLenBytesUpdateUser);
                    client.Send(toSendBytesUpdateUser);
                    break;

                case RequestType.AddComment:
                    AddCommentRequest addCommentRequest         = JsonSerializer.Deserialize <AddCommentRequest>(message);
                    Comment           newComment                = DbPersistence.AddComment(addCommentRequest.Comment);
                    string            responseMessageAddComment = JsonSerializer.Serialize(new AddCommentRequest(newComment));
                    int    toSendAddComment         = Encoding.ASCII.GetByteCount(responseMessageAddComment);
                    byte[] toSendBytesAddComment    = Encoding.ASCII.GetBytes(responseMessageAddComment);
                    byte[] toSendLenBytesAddComment = BitConverter.GetBytes(toSendAddComment);
                    client.Send(toSendLenBytesAddComment);
                    client.Send(toSendBytesAddComment);
                    break;

                case RequestType.SendMessage:
                    SendMessageRequest sendMessageRequest         = JsonSerializer.Deserialize <SendMessageRequest>(message);
                    Message            newMessage                 = DbPersistence.SendMessage(sendMessageRequest.Message);
                    string             responseMessageSendMessage =
                        JsonSerializer.Serialize(new SendMessageRequest(newMessage));
                    int    toSendMessage         = Encoding.ASCII.GetByteCount(responseMessageSendMessage);
                    byte[] toSendBytesMessage    = Encoding.ASCII.GetBytes(responseMessageSendMessage);
                    byte[] toSendLenBytesMessage = BitConverter.GetBytes(toSendMessage);
                    client.Send(toSendLenBytesMessage);
                    client.Send(toSendBytesMessage);
                    break;

                case RequestType.AddConversation:
                    AddConversationRequest addConversation = JsonSerializer.Deserialize <AddConversationRequest>(message);
                    List <UserConversation
                          > newUserConversations           = DbPersistence.AddConversation(addConversation.Conversation, addConversation.CreatorId, addConversation.WithWhomId);
                    string  responseMessageAddConversation =
                        JsonSerializer.Serialize(new AddConversationResponse(newUserConversations));
                    int    toSendAddConversation      = Encoding.ASCII.GetByteCount(responseMessageAddConversation);
                    byte[] toSendBytesAddConversation = Encoding.ASCII.GetBytes(responseMessageAddConversation);
                    byte[] toSendLenBytesConversation = BitConverter.GetBytes(toSendAddConversation);
                    client.Send(toSendLenBytesConversation);
                    client.Send(toSendBytesAddConversation);
                    break;

                case RequestType.DeleteComment:
                    DeleteCommentRequest deleteCommentRequest = JsonSerializer.Deserialize <DeleteCommentRequest>(message);
                    int    deletedCommentId             = DbPersistence.DeleteComment(deleteCommentRequest.CommentId);
                    string responseMessageDeleteComment =
                        JsonSerializer.Serialize(new DeleteCommentRequest(deletedCommentId));
                    int    toSendDeleteComment         = Encoding.ASCII.GetByteCount(responseMessageDeleteComment);
                    byte[] toSendBytesDeleteComment    = Encoding.ASCII.GetBytes(responseMessageDeleteComment);
                    byte[] toSendLenBytesDeleteComment = BitConverter.GetBytes(toSendDeleteComment);
                    client.Send(toSendLenBytesDeleteComment);
                    client.Send(toSendBytesDeleteComment);
                    break;

                case RequestType.MakeFriendRequest:
                    MakeFriendRequest         makeFriendRequest         = JsonSerializer.Deserialize <MakeFriendRequest>(message);
                    FriendRequestNotification friendRequestNotification = DbPersistence.MakeFriendRequestNotification(makeFriendRequest.FriendRequestNotification);
                    Console.WriteLine(friendRequestNotification.FriendRequestId);
                    string responseMakeFriendRequest =
                        JsonSerializer.Serialize(new MakeFriendRequest(friendRequestNotification));
                    int    toSendMakeFriends               = Encoding.ASCII.GetByteCount(responseMakeFriendRequest);
                    byte[] toSendBytesMakeFriendRequest    = Encoding.ASCII.GetBytes(responseMakeFriendRequest);
                    byte[] toSendLenBytesMakeFriendRequest = BitConverter.GetBytes(toSendMakeFriends);
                    client.Send(toSendLenBytesMakeFriendRequest);
                    client.Send(toSendBytesMakeFriendRequest);
                    break;

                case RequestType.RespondToFriendRequest:
                    RespondToFriendRequest respondToFriendRequest = JsonSerializer.Deserialize <RespondToFriendRequest>(message);
                    List <UserFriend>      userFriends            = DbPersistence.RespondToFriendRequest(respondToFriendRequest.RespondStatus, respondToFriendRequest.FriendRequestNotification);
                    string responseToFriendResponse =
                        JsonSerializer.Serialize(new RespondToFriendResponse(userFriends));
                    int    toSendRespondFriend         = Encoding.ASCII.GetByteCount(responseToFriendResponse);
                    byte[] toSendBytesRespondFriend    = Encoding.ASCII.GetBytes(responseToFriendResponse);
                    byte[] toSendLenBytesRespondFriend = BitConverter.GetBytes(toSendRespondFriend);
                    client.Send(toSendLenBytesRespondFriend);
                    client.Send(toSendBytesRespondFriend);
                    break;

                case RequestType.SubscribeToUser:
                    SubscribeToUserRequest subscribeToUserRequest = JsonSerializer.Deserialize <SubscribeToUserRequest>(message);
                    UserSubscription       userSubscription       = DbPersistence.SubscribeToUser(subscribeToUserRequest.UserSubscription);
                    string responseToSubscribeToUser =
                        JsonSerializer.Serialize(new SubscribeToUserRequest(userSubscription));
                    int    toSendSubscribeToUser         = Encoding.ASCII.GetByteCount(responseToSubscribeToUser);
                    byte[] toSendBytesSubscribeToUser    = Encoding.ASCII.GetBytes(responseToSubscribeToUser);
                    byte[] toSendLenBytesSubscribeToUser = BitConverter.GetBytes(toSendSubscribeToUser);
                    client.Send(toSendLenBytesSubscribeToUser);
                    client.Send(toSendBytesSubscribeToUser);
                    break;

                case RequestType.UnsubscribeRequest:
                    UnsubscribeRequest unsubscribeRequest = JsonSerializer.Deserialize <UnsubscribeRequest>(message);
                    int    unSubIndex          = DbPersistence.UnsubscribeFromUser(unsubscribeRequest.SubscriptionId);
                    string responseUnsubscribe =
                        JsonSerializer.Serialize(new UnsubscribeRequest(unSubIndex));
                    int    toSendUnSub               = Encoding.ASCII.GetByteCount(responseUnsubscribe);
                    byte[] toSendBytesUnsubscribe    = Encoding.ASCII.GetBytes(responseUnsubscribe);
                    byte[] toSendLenBytesUnsubscribe = BitConverter.GetBytes(toSendUnSub);
                    client.Send(toSendLenBytesUnsubscribe);
                    client.Send(toSendBytesUnsubscribe);
                    break;

                case RequestType.DeleteFriendRequest:
                    DeleteFriendRequest deleteFriendRequest =
                        JsonSerializer.Deserialize <DeleteFriendRequest>(message);
                    int    deleteFriendIndex    = DbPersistence.DeleteFriend(deleteFriendRequest.UserFriendId);
                    string responseDeleteFriend =
                        JsonSerializer.Serialize(new DeleteFriendRequest(deleteFriendIndex));
                    int    toSendDeleteFriend                = Encoding.ASCII.GetByteCount(responseDeleteFriend);
                    byte[] toSendBytesDeleteFriendRequest    = Encoding.ASCII.GetBytes(responseDeleteFriend);
                    byte[] toSendBytesLenDeleteFriendRequest = BitConverter.GetBytes(toSendDeleteFriend);
                    client.Send(toSendBytesLenDeleteFriendRequest);
                    client.Send(toSendBytesDeleteFriendRequest);
                    break;

                case RequestType.MakeReactionRequest:
                    MakeReactionRequest makeReactionRequest =
                        JsonSerializer.Deserialize <MakeReactionRequest>(message);
                    PostReaction postReactionResult =
                        DbPersistence.MakePostReaction(makeReactionRequest.PostReaction);
                    string responseMakePostReaction =
                        JsonSerializer.Serialize(new MakeReactionRequest(postReactionResult));
                    int    toSendMakePostReaction         = Encoding.ASCII.GetByteCount(responseMakePostReaction);
                    byte[] toSendBytesMakePostReaction    = Encoding.ASCII.GetBytes(responseMakePostReaction);
                    byte[] toSendBytesLenMakePostReaction = BitConverter.GetBytes(toSendMakePostReaction);
                    client.Send(toSendBytesLenMakePostReaction);
                    client.Send(toSendBytesMakePostReaction);
                    break;

                case RequestType.DeleteReactionRequest:
                    DeleteReactionRequest deleteReactionRequest =
                        JsonSerializer.Deserialize <DeleteReactionRequest>(message);
                    int deleteReactionResult =
                        DbPersistence.DeleteReaction(deleteReactionRequest.PostReactionId);
                    string responseDeletePostReaction =
                        JsonSerializer.Serialize(new DeleteReactionRequest(deleteReactionResult));
                    int    toSendDeletePostReaction         = Encoding.ASCII.GetByteCount(responseDeletePostReaction);
                    byte[] toSendBytesMakeDeleteReaction    = Encoding.ASCII.GetBytes(responseDeletePostReaction);
                    byte[] toSendBytesLenMakeDeleteReaction = BitConverter.GetBytes(toSendDeletePostReaction);
                    client.Send(toSendBytesLenMakeDeleteReaction);
                    client.Send(toSendBytesMakeDeleteReaction);
                    break;

                case RequestType.UpdateReactionRequest:
                    UpdateReactionRequest updateReactionRequest =
                        JsonSerializer.Deserialize <UpdateReactionRequest>(message);
                    PostReaction postReactionResultFromUpdating =
                        DbPersistence.UpdatePostReaction(updateReactionRequest.PostReaction);
                    string updateReactionResponse =
                        JsonSerializer.Serialize(new UpdateReactionRequest(postReactionResultFromUpdating));
                    int    toSendUpdateBytes                = Encoding.ASCII.GetByteCount(updateReactionResponse);
                    byte[] toSendBytesMakeUpdateReaction    = Encoding.ASCII.GetBytes(updateReactionResponse);
                    byte[] toSendLenBytesMakeUpdateReaction = BitConverter.GetBytes(toSendUpdateBytes);
                    client.Send(toSendLenBytesMakeUpdateReaction);
                    client.Send(toSendBytesMakeUpdateReaction);
                    break;
                }
            }
            // close connection
            client.Close();
        }