public void TestHandleBuildNotification()
        {
            UserCache userCache = null;
            NotificationManager notificationManager = null;
            try
            {
                userCache = new UserCache();
                notificationManager = new NotificationManager(0, 0, userCache, false);
                string username = "******";
                string[] recipients = { username };
                BuildServerNotificationType notificationType = BuildServerNotificationType.BuildBuilding;
                string projectId = "project1";
                string buildConfigId = "buildconfig1";
                IBuildServerNotification buildServerNotification = new BuildNotification(notificationType, projectId, buildConfigId, recipients);
                string buildKey = Utils.CreateBuildKey(buildServerNotification);
                notificationManager.HandleCommand(buildServerNotification, EventArgs.Empty);
                User user = userCache.GetUser(username);
                Assert.That(user.Username, Is.EqualTo(username));
                Assert.That(user.ActiveBuilds.Contains(buildKey));
            }
            finally
            {
                if (notificationManager != null)
                {
                    notificationManager.Dispose();
                }

                if (userCache != null)
                {
                    userCache.Dispose();
                }
            }
        }
        /// <summary>
        /// The main method. 
        /// </summary>
        private static void Main()
        {
            UserCache userCache = null;
            NotificationManager notificationManager = null;
            try
            {
                userCache = new UserCache(5000, new TimeSpan(0, 5, 0));
                notificationManager = new NotificationManager(Config.GetNotificationManagerPort(), Config.GetLightsManagerPort(), userCache, Config.GetInitializationEnabled());
                Thread thread = new Thread(notificationManager.Start);
                thread.Start();
                Console.WriteLine("Press any key to terminate...");
                Console.ReadKey(true);
                notificationManager.Stop();
                thread.Join();
                Console.WriteLine("Press any key to close...");
                Console.ReadKey(true);
            }
            catch (Exception e)
            {
                Console.Error.WriteLine(e);
                Console.ReadKey(true);
            }
            finally
            {
                if (notificationManager != null)
                {
                    notificationManager.Dispose();
                }

                if (userCache != null)
                {
                    userCache.Dispose();
                }
            }
        }
 public void TestGetRegisteredUsers()
 {
     UserCache userCache = null;
     try
     {
         userCache = new UserCache();
         List<User> userList = new List<User>(userCache.GetRegisteredUsers());
         Assert.That(userList.Count, NUnit.Framework.Is.EqualTo(0));
         string username1 = "user1";
         string hostname1 = username1 + "-ws";
         string username2 = "user2";
         string hostname2 = string.Empty;
         RegistrationRequest request1 = new RegistrationRequest(hostname1, username1);
         RegistrationRequest request2 = new RegistrationRequest(hostname2, username2);
         userCache.Register(request1);
         userCache.Register(request2);
         userList = new List<User>(userCache.GetRegisteredUsers());
         Assert.That(userList.Count, NUnit.Framework.Is.EqualTo(1));
         User user = userList[0];
         Assert.That(user.Hostname, NUnit.Framework.Is.EqualTo(hostname1));
         Assert.That(user.Username, NUnit.Framework.Is.EqualTo(username1));
     }
     finally
     {
         if (userCache != null)
         {
             userCache.Dispose();
         }
     }
 }
예제 #4
0
파일: Cart.cs 프로젝트: fengyu25/comp5348
        public void SubmitOrderAndClearCart(UserCache pUserCache)
        {
            Order lOrder = new Order();
            lOrder.OrderDate = DateTime.Now;
            lOrder.Customer = pUserCache.Model;
            // NEWLY ADDED 
            lOrder.UserId = pUserCache.Model.Id;

            lOrder.Status = 0;

            foreach(OrderItem lItem in mOrderItems)
            {
                // NEWLY ADDED
                lItem.order_Id = lOrder.ExternalOrderId;
                lItem.MediaId = lItem.Media.Id;
                lItem.Media.Stocks.setMediaId(lItem.Media.Id);

                lOrder.OrderItems.Add(lItem);
            }

            OrderService.OrderServiceClient lOrderService = new OrderService.OrderServiceClient();

            lOrderService.SubmitOrder(lOrder);
            pUserCache.UpdateUserCache();
            Clear();
        }
예제 #5
0
 public RealTest(string title, List<string> headers, UserCache userCache)
 {
     this.title = title;
     this.headers = headers;
     UserCache = userCache;
     DataCache = new DataCache();
     testResults = new List<RowResult>();
     ChildInstructions = new List<IInstruction>();
 }
예제 #6
0
        public ScenarioResult Test(RawTest[] rawTests, IResultsWriter resultsWriter)
        {
            var results = new ScenarioResult(name);
            resultsWriter.Begin(results);

            UserCache cache = new UserCache();
            foreach (RawTest rawTest in rawTests)
            {
                var realTest = rawTest.CreateRealTest(assemblies, cache);
                results.Add(realTest.Test(resultsWriter));
            }
            resultsWriter.End(results);
            return results;
        }
예제 #7
0
파일: Cart.cs 프로젝트: agaw/aurora
        public void SubmitOrderAndClearCart(UserCache pUserCache)
        {
            Order lOrder = new Order();
            lOrder.OrderDate = DateTime.Now;
            lOrder.Customer = pUserCache.Model;
            foreach(OrderItem lItem in mOrderItems)
            {
                lOrder.OrderItems.Add(lItem);
            }
            lOrder.Total = Convert.ToDouble(ComputeTotalValue());

            OrderService.OrderServiceClient lOrderService = new OrderService.OrderServiceClient();

            lOrderService.SubmitOrder(lOrder);
            pUserCache.UpdateUserCache();
            Clear();
        }
예제 #8
0
        public void SubmitOrderAndClearCart(UserCache pUserCache)
        {
            Order lOrder = new Order();
            lOrder.OrderDate = DateTime.Now;
            lOrder.Customer = pUserCache.Model;
            lOrder.Status = 0;
            foreach(OrderItem lItem in mOrderItems)
            {
                lOrder.OrderItems.Add(lItem);
            }

            OrderService.OrderServiceClient lOrderService = new OrderService.OrderServiceClient();

            lOrderService.SubmitOrder(lOrder);
            pUserCache.UpdateUserCache();
            Clear();
        }
예제 #9
0
        private List <ValidationItemVM> getValidationItemsFromCache(DateTime period)
        {
            var key = getValidationItemsCacheKey(period);

            return(UserCache.GetItem(key) as List <ValidationItemVM>);
        }
예제 #10
0
        public static void GenerateExtradata(Item Item, ServerPacket Message)
        {
            switch (Item.GetBaseItem().InteractionType)
            {
            default:
                Message.WriteInteger(1);
                Message.WriteInteger(0);
                Message.WriteString(Item.GetBaseItem().InteractionType != InteractionType.FOOTBALL_GATE ? Item.ExtraData : string.Empty);
                break;

            case InteractionType.wired_score_board:
                string username;
                string name = Item.GetBaseItem().ItemName;
                string type = name.Split('*')[1];

                if (type != null)
                {
                    Dictionary <int, KeyValuePair <int, string> > ScoreBordata = new Dictionary <int, KeyValuePair <int, string> >();
                    Message.WriteInteger(0);
                    Message.WriteInteger(6);
                    Message.WriteString("1");
                    Message.WriteInteger(1);


                    if (Item.GetRoom() != null)
                    {
                        switch (type)
                        {
                        case "2":
                            Message.WriteInteger(1);
                            Message.WriteInteger(Item.GetRoom().WiredScoreBordDay.Count);
                            ScoreBordata = Item.GetRoom().WiredScoreBordDay;
                            break;

                        case "3":
                            Message.WriteInteger(2);
                            Message.WriteInteger(Item.GetRoom().WiredScoreBordWeek.Count);
                            ScoreBordata = Item.GetRoom().WiredScoreBordWeek;
                            break;


                        case "4":
                            Message.WriteInteger(3);
                            Message.WriteInteger(Item.GetRoom().WiredScoreBordMonth.Count);
                            ScoreBordata = Item.GetRoom().WiredScoreBordMonth;
                            break;

                        default:
                            Message.WriteInteger(1);
                            Message.WriteInteger(0);
                            ScoreBordata = null;
                            break;
                        }
                    }
                    else
                    {
                        Message.WriteInteger(1);
                        Message.WriteInteger(1);
                        Message.WriteInteger(0);
                        Message.WriteInteger(1);
                        Message.WriteString("Dit Scorebord werkt nog niet :(");
                    }

                    if (ScoreBordata.Count != 0)
                    {
                        foreach (KeyValuePair <int, string> value in (
                                     from i in ScoreBordata
                                     orderby i.Value.Key descending
                                     select i).ToDictionary <KeyValuePair <int, KeyValuePair <int, string> >, int, KeyValuePair <int, string> >((KeyValuePair <int, KeyValuePair <int, string> > i) => i.Key, (KeyValuePair <int, KeyValuePair <int, string> > i) => i.Value).Values)
                        {
                            username = value.Value;
                            Message.WriteInteger(value.Key);
                            Message.WriteInteger(1);
                            Message.WriteString((string.IsNullOrEmpty(username) ? string.Empty : username));
                        }
                    }
                }
                break;

            case InteractionType.MUSIC_DISC:
                int issx = 0;
                int.TryParse(Item.ExtraData, out issx);
                Message.WriteInteger(issx);
                Message.WriteInteger(0);
                Message.WriteString(Item.ExtraData);
                break;

            case InteractionType.GNOME_BOX:
                Message.WriteInteger(0);
                Message.WriteInteger(0);
                Message.WriteString("");
                break;

            case InteractionType.PET_BREEDING_BOX:
            case InteractionType.PURCHASABLE_CLOTHING:
                Message.WriteInteger(0);
                Message.WriteInteger(0);
                Message.WriteString("0");
                break;

            case InteractionType.STACKTOOL:
                Message.WriteInteger(0);
                Message.WriteInteger(0);
                Message.WriteString("");
                break;

            case InteractionType.WALLPAPER:
                Message.WriteInteger(2);
                Message.WriteInteger(0);
                Message.WriteString(Item.ExtraData);

                break;

            case InteractionType.FLOOR:
                Message.WriteInteger(3);
                Message.WriteInteger(0);
                Message.WriteString(Item.ExtraData);
                break;

            case InteractionType.LANDSCAPE:
                Message.WriteInteger(4);
                Message.WriteInteger(0);
                Message.WriteString(Item.ExtraData);
                break;

            case InteractionType.GUILD_ITEM:
            case InteractionType.GUILD_GATE:
            case InteractionType.GUILD_FORUM:
                Group Group = null;
                if (!CloudServer.GetGame().GetGroupManager().TryGetGroup(Item.GroupId, out Group))
                {
                    Message.WriteInteger(1);
                    Message.WriteInteger(0);
                    Message.WriteString(Item.ExtraData);
                }
                else
                {
                    Message.WriteInteger(0);
                    Message.WriteInteger(2);
                    Message.WriteInteger(5);
                    Message.WriteString(Item.ExtraData);
                    Message.WriteString(Group.Id.ToString());
                    Message.WriteString(Group.Badge);
                    Message.WriteString(CloudServer.GetGame().GetGroupManager().GetColourCode(Group.Colour1, true));
                    Message.WriteString(CloudServer.GetGame().GetGroupManager().GetColourCode(Group.Colour2, false));
                }
                break;

            case InteractionType.BACKGROUND:
                Message.WriteInteger(0);
                Message.WriteInteger(1);
                if (!String.IsNullOrEmpty(Item.ExtraData))
                {
                    Message.WriteInteger(Item.ExtraData.Split(Convert.ToChar(9)).Length / 2);

                    for (int i = 0; i <= Item.ExtraData.Split(Convert.ToChar(9)).Length - 1; i++)
                    {
                        Message.WriteString(Item.ExtraData.Split(Convert.ToChar(9))[i]);
                    }
                }
                else
                {
                    Message.WriteInteger(0);
                }
                break;

            case InteractionType.GIFT:
            {
                string[] ExtraData = Item.ExtraData.Split(Convert.ToChar(5));
                if (ExtraData.Length != 7)
                {
                    Message.WriteInteger(0);
                    Message.WriteInteger(0);
                    Message.WriteString(Item.ExtraData);
                }
                else
                {
                    int Style = int.Parse(ExtraData[6]) * 1000 + int.Parse(ExtraData[6]);

                    UserCache Purchaser = CloudServer.GetGame().GetCacheManager().GenerateUser(Convert.ToInt32(ExtraData[2]));
                    if (Purchaser == null)
                    {
                        Message.WriteInteger(0);
                        Message.WriteInteger(0);
                        Message.WriteString(Item.ExtraData);
                    }
                    else
                    {
                        Message.WriteInteger(Style);
                        Message.WriteInteger(1);
                        Message.WriteInteger(6);
                        Message.WriteString("EXTRA_PARAM");
                        Message.WriteString("");
                        Message.WriteString("MESSAGE");
                        Message.WriteString(ExtraData[1]);
                        Message.WriteString("PURCHASER_NAME");
                        Message.WriteString(Purchaser.Username);
                        Message.WriteString("PURCHASER_FIGURE");
                        Message.WriteString(Purchaser.Look);
                        Message.WriteString("PRODUCT_CODE");
                        Message.WriteString("A1 KUMIANKKA");
                        Message.WriteString("state");
                        Message.WriteString(Item.MagicRemove == true ? "1" : "0");
                    }
                }
            }
            break;

            case InteractionType.MANNEQUIN:
                Message.WriteInteger(0);
                Message.WriteInteger(1);
                Message.WriteInteger(3);
                if (Item.ExtraData.Contains(Convert.ToChar(5).ToString()))
                {
                    string[] Stuff = Item.ExtraData.Split(Convert.ToChar(5));
                    Message.WriteString("GENDER");
                    Message.WriteString(Stuff[0]);
                    Message.WriteString("FIGURE");
                    Message.WriteString(Stuff[1]);
                    Message.WriteString("OUTFIT_NAME");
                    Message.WriteString(Stuff[2]);
                }
                else
                {
                    Message.WriteString("GENDER");
                    Message.WriteString("");
                    Message.WriteString("FIGURE");
                    Message.WriteString("");
                    Message.WriteString("OUTFIT_NAME");
                    Message.WriteString("");
                }
                break;

            case InteractionType.TONER:
                if (Item.RoomId != 0)
                {
                    if (Item.GetRoom().TonerData == null)
                    {
                        Item.GetRoom().TonerData = new TonerData(Item.Id);
                    }

                    Message.WriteInteger(0);
                    Message.WriteInteger(5);
                    Message.WriteInteger(4);
                    Message.WriteInteger(Item.GetRoom().TonerData.Enabled);
                    Message.WriteInteger(Item.GetRoom().TonerData.Hue);
                    Message.WriteInteger(Item.GetRoom().TonerData.Saturation);
                    Message.WriteInteger(Item.GetRoom().TonerData.Lightness);
                }
                else
                {
                    Message.WriteInteger(0);
                    Message.WriteInteger(0);
                    Message.WriteString(string.Empty);
                }
                break;

            case InteractionType.BADGE_DISPLAY:
                Message.WriteInteger(0);
                Message.WriteInteger(2);
                Message.WriteInteger(4);

                string[] BadgeData = Item.ExtraData.Split(Convert.ToChar(9));
                if (Item.ExtraData.Contains(Convert.ToChar(9).ToString()))
                {
                    Message.WriteString("0");          //No idea
                    Message.WriteString(BadgeData[0]); //Badge name
                    Message.WriteString(BadgeData[1]); //Owner
                    Message.WriteString(BadgeData[2]); //Date
                }
                else
                {
                    Message.WriteString("0");          //No idea
                    Message.WriteString("DEV");        //Badge name
                    Message.WriteString("Sledmore");   //Owner
                    Message.WriteString("13-13-1337"); //Date
                }
                break;

            case InteractionType.TELEVISION:
                Message.WriteInteger(0);
                Message.WriteInteger(1);
                Message.WriteInteger(1);
                Message.WriteString("THUMBNAIL_URL");
                Message.WriteString(ExtraSettings.YOUTUBE_THUMBNAIL_SUBURL + "=" + CloudServer.GetGame().GetTelevisionManager().TelevisionList.OrderBy(x => Guid.NewGuid()).FirstOrDefault().YouTubeId);
                break;

            case InteractionType.TRAX:
                break;

            case InteractionType.LOVELOCK:
                if (Item.ExtraData.Contains(Convert.ToChar(5).ToString()))
                {
                    var EData = Item.ExtraData.Split((char)5);
                    int I     = 0;
                    Message.WriteInteger(0);
                    Message.WriteInteger(2);
                    Message.WriteInteger(EData.Length);
                    while (I < EData.Length)
                    {
                        Message.WriteString(EData[I]);
                        I++;
                    }
                }
                else
                {
                    Message.WriteInteger(0);
                    Message.WriteInteger(0);
                    Message.WriteString("0");
                }
                break;

            case InteractionType.MONSTERPLANT_SEED:
                Message.WriteInteger(0);
                Message.WriteInteger(1);
                Message.WriteInteger(1);

                Message.WriteString("rarity");
                Message.WriteString("1");    //Leve should be dynamic.
                break;
            }
        }
예제 #11
0
        public void Parse(HabboHotel.GameClients.GameClient Session, ClientPacket Packet)
        {
            if (Session == null || Session.GetHabbo() == null || !Session.GetHabbo().InRoom)
            {
                return;
            }

            Room Room = Session.GetHabbo().CurrentRoom;

            if (Room == null)
            {
                return;
            }

            int  PresentId = Packet.PopInt();
            Item Present   = Room.GetRoomItemHandler().GetItem(PresentId);

            if (Present == null)
            {
                return;
            }

            if (Present.UserID != Session.GetHabbo().Id)
            {
                return;
            }

            DataRow Data = null;

            using (IQueryAdapter dbClient = NeonEnvironment.GetDatabaseManager().GetQueryReactor())
            {
                dbClient.SetQuery("SELECT `base_id`,`extra_data` FROM `user_presents` WHERE `item_id` = '" + Present.Id + "' LIMIT 1");
                Data = dbClient.getRow();
            }

            if (Data == null)
            {
                Session.SendNotification("Oops! al parecer hay un error con este regalo.\nNosotros nos encargaremos de deshacernos de este regalo.");
                Room.GetRoomItemHandler().RemoveFurniture(null, Present.Id, false);

                using (IQueryAdapter dbClient = NeonEnvironment.GetDatabaseManager().GetQueryReactor())
                {
                    dbClient.RunQuery("DELETE FROM `items` WHERE `id` = '" + Present.Id + "' LIMIT 1");
                    dbClient.RunQuery("DELETE FROM `user_presents` WHERE `item_id` = '" + Present.Id + "' LIMIT 1");
                }

                Session.GetHabbo().GetInventoryComponent().RemoveItem(Present.Id);
                return;
            }

            int PurchaserId = 0;

            if (Present.GetBaseItem().ItemName == "matic_box")
            {
                PurchaserId = Session.GetHabbo().Id;
            }
            else
            {
                if (!int.TryParse(Present.ExtraData.Split(Convert.ToChar(5))[2], out PurchaserId))
                {
                    Session.SendNotification("Oops! al parecer hay un error con este regalo.\nNosotros nos encargaremos de deshacernos de este regalo.");
                    Room.GetRoomItemHandler().RemoveFurniture(null, Present.Id, false);

                    using (IQueryAdapter dbClient = NeonEnvironment.GetDatabaseManager().GetQueryReactor())
                    {
                        dbClient.RunQuery("DELETE FROM `items` WHERE `id` = '" + Present.Id + "' LIMIT 1");
                        dbClient.RunQuery("DELETE FROM `user_presents` WHERE `item_id` = '" + Present.Id + "' LIMIT 1");
                    }
                    Session.GetHabbo().GetInventoryComponent().RemoveItem(Present.Id);

                    return;
                }
            }

            UserCache Purchaser = NeonEnvironment.GetGame().GetCacheManager().GenerateUser(PurchaserId);

            if (Purchaser == null)
            {
                Session.SendNotification("Oops! al parecer hay un error con este regalo.\nNosotros nos encargaremos de deshacernos de este regalo..");
                Room.GetRoomItemHandler().RemoveFurniture(null, Present.Id, false);

                using (IQueryAdapter dbClient = NeonEnvironment.GetDatabaseManager().GetQueryReactor())
                {
                    dbClient.RunQuery("DELETE FROM `items` WHERE `id` = '" + Present.Id + "' LIMIT 1");
                    dbClient.RunQuery("DELETE FROM `user_presents` WHERE `item_id` = '" + Present.Id + "' LIMIT 1");
                }

                Session.GetHabbo().GetInventoryComponent().RemoveItem(Present.Id);
                return;
            }

            if (!NeonEnvironment.GetGame().GetItemManager().GetItem(Convert.ToInt32(Data["base_id"]), out ItemData BaseItem))
            {
                Session.SendNotification("Oops, al parecer este regalo ya no existe!");
                Room.GetRoomItemHandler().RemoveFurniture(null, Present.Id, false);

                using (IQueryAdapter dbClient = NeonEnvironment.GetDatabaseManager().GetQueryReactor())
                {
                    dbClient.RunQuery("DELETE FROM `items` WHERE `id` = '" + Present.Id + "' LIMIT 1");
                    dbClient.RunQuery("DELETE FROM `user_presents` WHERE `item_id` = '" + Present.Id + "' LIMIT 1");
                }

                Session.GetHabbo().GetInventoryComponent().RemoveItem(Present.Id);
                return;
            }


            Present.MagicRemove = true;
            Room.SendMessage(new ObjectUpdateComposer(Present, Convert.ToInt32(Session.GetHabbo().Id)));

            Thread thread = new Thread(() => FinishOpenGift(Session, BaseItem, Present, Room, Data));

            thread.Start();
        }
예제 #12
0
 public RealTestFactory(Assemblies assemblies, UserCache userCache)
 {
     this.assemblies = assemblies;
     this.userCache = userCache;
 }
예제 #13
0
        private void setValidateItemsCache(List <ValidationItemVM> items, DateTime period)
        {
            var key = getValidationItemsCacheKey(period);

            UserCache.AddItem(key, items);
        }
예제 #14
0
        public bool RequestBuddy(string UserQuery)
        {
            int  userID;
            bool hasFQDisabled;

            GameClient client = PlusEnvironment.GetGame().GetClientManager().GetClientByUsername(UserQuery);

            if (client == null)
            {
                DataRow Row = null;
                using (IQueryAdapter dbClient = PlusEnvironment.GetDatabaseManager().GetQueryReactor())
                {
                    dbClient.SetQuery("SELECT `id`,`block_newfriends` FROM `users` WHERE `username` = @query LIMIT 1");
                    dbClient.AddParameter("query", UserQuery.ToLower());
                    Row = dbClient.GetRow();
                }

                if (Row == null)
                {
                    return(false);
                }

                userID        = Convert.ToInt32(Row["id"]);
                hasFQDisabled = PlusEnvironment.EnumToBool(Row["block_newfriends"].ToString());
            }
            else
            {
                userID        = client.GetHabbo().Id;
                hasFQDisabled = client.GetHabbo().AllowFriendRequests;
            }

            if (hasFQDisabled)
            {
                GetClient().SendPacket(new MessengerErrorComposer(39, 3));
                return(false);
            }

            int ToId = userID;

            if (RequestExists(ToId))
            {
                return(true);
            }

            using (IQueryAdapter dbClient = PlusEnvironment.GetDatabaseManager().GetQueryReactor())
            {
                dbClient.RunQuery("REPLACE INTO `messenger_requests` (`from_id`,`to_id`) VALUES ('" + _userId + "','" + ToId + "')");
            }

            PlusEnvironment.GetGame().GetQuestManager().ProgressUserQuest(GetClient(), QuestType.ADD_FRIENDS);

            GameClient ToUser = PlusEnvironment.GetGame().GetClientManager().GetClientByUserID(ToId);

            if (ToUser == null || ToUser.GetHabbo() == null)
            {
                return(true);
            }

            MessengerRequest Request = new MessengerRequest(ToId, _userId, PlusEnvironment.GetGame().GetClientManager().GetNameById(_userId));

            ToUser.GetHabbo().GetMessenger().OnNewRequest(_userId);

            UserCache ThisUser = PlusEnvironment.GetGame().GetCacheManager().GenerateUser(_userId);

            if (ThisUser != null)
            {
                ToUser.SendPacket(new NewBuddyRequestComposer(ThisUser));
            }

            _requests.Add(ToId, Request);
            return(true);
        }
        public int ApiCardDetails(string json)
        {
            Session session = new Session(json);

            session.CaptureOn = getCaptureDate(LkpDetails["Card"], session.DateStamp, session.CancelationDate);
            int Response = 0;

            if (TempData["TutorModel"] != null)
            {
                UserCache   userCache = JsonConvert.DeserializeObject <UserCache>(TempData["TutorModel"].ToString());
                string      Learner   = String.Concat(userCache.FirstName, userCache.LastName);
                BillingInfo bl        = PaymentDB.GetBillingInfo(userCache.UserId, GetConfiguration().GetConnectionString(DEFAULT_CONNECTION));
                //Build API Request
                object jsonParameters = new
                {
                    source = new
                    {
                        type = "id",
                        id   = bl.CardId
                    },
                    amount     = session.Amount * 100,
                    reference  = "Session-" + session.Id,
                    currency   = session.Currency,
                    capture_on = session.CaptureOn
                };
                Console.WriteLine(jsonParameters);
                var     requestUrl     = "https://api.sandbox.checkout.com/payments/";
                string  responseString = ApiRequest(jsonParameters, requestUrl);
                dynamic jObj           = (JObject)JsonConvert.DeserializeObject(responseString);
                //if the API request success add operations to DB
                if (jObj != null)
                {
                    //Operation 1 : Record Learner Payment
                    Operation Op = new Operation
                    {
                        UID             = userCache.UserId,
                        RelationId      = session.Id,
                        RelationEntity  = "Event",
                        Amount          = session.Amount,
                        Currency        = session.Currency,
                        RespDate        = (DateTime)jObj.processed_on,
                        RespDetails     = responseString.Replace("\"", string.Empty),
                        CaptureOn       = getCaptureDate(LkpDetails["Card"], session.DateStamp, session.CancelationDate),
                        Auto            = 0,
                        Description     = session.Title,
                        ServiceId       = session.Service == "F2F" ? LkpDetails["F2F"] : LkpDetails["Online"],
                        RespId          = jObj.id,
                        OprTypeId       = LkpDetails["Payment"],
                        PaymentMethodId = LkpDetails["Card"],
                        SerialId        = Serials["PB"],
                        ObjEntityId     = 1,//Nabih get user Entity id
                        CancelationDate = session.CancelationDate,
                        TutorId         = session.TutorId,
                        TutorName       = session.TutorName
                    };
                    if (Op.CaptureOn != session.DateStamp)
                    {
                        Op.Captured = 1;
                    }
                    Response = PaymentDB.SubmitOperation(Op, GetConfiguration().GetConnectionString(DEFAULT_CONNECTION));

                    if (Response != 0)
                    {
                        Op.LinkedOprId = Response;
                        SendNotification(DateTime.Now, Learner, "Card Pymt", session.Amount, Op.Captured);
                        //Operation 2 : Add tutor Revenue

                        decimal revenue = Convert.ToDecimal(Perc["TutorPercentage"]);
                        AddTutorRevenue(Op, session.TutorId, session.TutorName, revenue);
                        //Operation 3 : Subtract Checkout Fees
                        decimal fee = Convert.ToDecimal(Perc["CheckoutFees"]);
                        decimal Per = Convert.ToDecimal(Perc["CheckoutPercentage"]);
                        SubtractFees(Op, "Checkout Fees", fee, Per, Serials["FC"]);
                    }
                    TempData.Keep("TutorModel");
                    return(Response);
                }
            }
            return(Response);
        }
예제 #16
0
 static CacheFactory()
 {
     USER_CACHE = new UserCache();
     HALL_CACHE = new HallCache();
     ROOM_CACHE = new RoomCache();
 }
 public CacheUserFullNameResolver(UserCache <ApplicationUser> cache)
 {
     _cache = cache;
 }
        public int ApiRequestPayment(string json)
        {
            Session session = new Session(json);

            //if (session.AutoCapture == true) { session.CaptureOn = DateTime.Now; }
            session.CaptureOn = getCaptureDate(LkpDetails["Card"], session.DateStamp, session.CancelationDate);
            int Response = 0;

            if (TempData["TutorModel"] != null)
            {
                UserCache userCache = JsonConvert.DeserializeObject <UserCache>(TempData["TutorModel"].ToString());
                string    Learner   = String.Concat(userCache.FirstName, userCache.LastName);
                //Build API Request
                object jsonParameters = new
                {
                    source = new
                    {
                        type  = "token",
                        token = session.Token
                    },
                    customer = new
                    {
                        email = userCache.Email,
                        name  = Learner
                    },
                    description = session.Title,
                    amount      = session.Amount * 100,
                    currency    = session.Currency,
                    approved    = true,
                    reference   = "Session-" + session.Id,
                    capture_on  = session.CaptureOn
                };
                string  responseString = ApiRequest(jsonParameters, "https://api.sandbox.checkout.com/payments");
                dynamic jObj           = (JObject)JsonConvert.DeserializeObject(responseString);

                //if the API request success add operations to DB
                if (jObj != null && jObj.status == "Authorized")
                {
                    //Operation 1 : Record Learner Payment
                    Operation Op = new Operation
                    {
                        UID             = userCache.UserId,
                        RelationId      = session.Id,
                        RelationEntity  = "Event",
                        Amount          = session.Amount,
                        Currency        = session.Currency,
                        RespDate        = (DateTime)jObj.processed_on,
                        RespDetails     = responseString.Replace("\"", string.Empty),
                        CaptureOn       = getCaptureDate(LkpDetails["Card"], session.DateStamp, session.CancelationDate),
                        Auto            = 0,
                        Description     = session.Title,
                        ServiceId       = session.Service == "F2F" ? LkpDetails["F2F"] : LkpDetails["Online"],
                        RespId          = jObj.id,
                        OprTypeId       = LkpDetails["Payment"],
                        PaymentMethodId = LkpDetails["Card"],
                        SerialId        = Serials["PB"],
                        ObjEntityId     = 1,//Nabih get user Entity id
                        CancelationDate = session.CancelationDate,
                        TutorId         = session.TutorId,
                        TutorName       = session.TutorName,
                        billingInfo     = new BillingInfo()
                        {
                            UID          = userCache.UserId,
                            ObjEntityId  = 1,//Nabih get user Entity id
                            CardId       = jObj.source.id,
                            CardType     = jObj.source.scheme,
                            CardExpYear  = jObj.source.expiry_year,
                            CardLast4dig = jObj.source.last4,
                            CardExpMnth  = jObj.source.expiry_month
                        }
                    };
                    if (Op.CaptureOn != session.DateStamp)
                    {
                        Op.Captured = 1;
                    }
                    Response = PaymentDB.SubmitOperation(Op, GetConfiguration().GetConnectionString(DEFAULT_CONNECTION));
                    if (Response != 0)
                    {
                        Op.LinkedOprId = Response;
                        SendNotification(DateTime.Now, Learner, "Card Pymt", session.Amount, Op.Captured);

                        //Operation 2 : Add tutor Revenue
                        decimal revenue = Convert.ToDecimal(Perc["TutorPercentage"]);
                        AddTutorRevenue(Op, session.TutorId, session.TutorName, revenue);
                        //Operation 3 : Subtract Checkout Fees
                        decimal fee = Convert.ToDecimal(Perc["CheckoutFees"]);
                        decimal Per = Convert.ToDecimal(Perc["CheckoutPercentage"]);
                        SubtractFees(Op, "Checkout Fees", fee, Per, Serials["FC"]);
                    }
                    TempData.Keep("TutorModel");
                    return(Response);
                }
                else
                {
                    if (jObj.response_code == 20087)
                    {
                        Response = -1;                             // Invalid card cvv or exp date
                    }
                }
            }
            return(Response);
        }
예제 #19
0
        public void Parse(GameClient session, ClientPacket packet)
        {
            int groupId = packet.PopInt();
            int userId  = packet.PopInt();

            if (!PlusEnvironment.GetGame().GetGroupManager().TryGetGroup(groupId, out Group group))
            {
                return;
            }

            if (userId == session.GetHabbo().Id)
            {
                if (group.IsMember(userId))
                {
                    group.DeleteMember(userId);
                }

                if (group.IsAdmin(userId))
                {
                    if (group.IsAdmin(userId))
                    {
                        group.TakeAdmin(userId);
                    }

                    if (!PlusEnvironment.GetGame().GetRoomManager().TryGetRoom(group.RoomId, out Room room))
                    {
                        return;
                    }

                    RoomUser user = room.GetRoomUserManager().GetRoomUserByHabbo(session.GetHabbo().Id);
                    if (user != null)
                    {
                        user.RemoveStatus("flatctrl 1");
                        user.UpdateNeeded = true;

                        if (user.GetClient() != null)
                        {
                            user.GetClient().SendPacket(new YouAreControllerComposer(0));
                        }
                    }
                }

                using (IQueryAdapter dbClient = PlusEnvironment.GetDatabaseManager().GetQueryReactor())
                {
                    dbClient.SetQuery(
                        "DELETE FROM `group_memberships` WHERE `group_id` = @GroupId AND `user_id` = @UserId");
                    dbClient.AddParameter("GroupId", groupId);
                    dbClient.AddParameter("UserId", userId);
                    dbClient.RunQuery();
                }

                session.SendPacket(new GroupInfoComposer(group, session));
                if (session.GetHabbo().GetStats().FavouriteGroupId == groupId)
                {
                    session.GetHabbo().GetStats().FavouriteGroupId = 0;
                    using (IQueryAdapter dbClient = PlusEnvironment.GetDatabaseManager().GetQueryReactor())
                    {
                        dbClient.SetQuery("UPDATE `user_stats` SET `groupid` = '0' WHERE `id` = @userId LIMIT 1");
                        dbClient.AddParameter("userId", userId);
                        dbClient.RunQuery();
                    }

                    if (group.AdminOnlyDeco == 0)
                    {
                        if (!PlusEnvironment.GetGame().GetRoomManager().TryGetRoom(group.RoomId, out Room room))
                        {
                            return;
                        }

                        RoomUser user = room.GetRoomUserManager().GetRoomUserByHabbo(session.GetHabbo().Id);
                        if (user != null)
                        {
                            user.RemoveStatus("flatctrl 1");
                            user.UpdateNeeded = true;

                            if (user.GetClient() != null)
                            {
                                user.GetClient().SendPacket(new YouAreControllerComposer(0));
                            }
                        }
                    }

                    if (session.GetHabbo().InRoom&& session.GetHabbo().CurrentRoom != null)
                    {
                        RoomUser user = session.GetHabbo().CurrentRoom.GetRoomUserManager()
                                        .GetRoomUserByHabbo(session.GetHabbo().Id);
                        if (user != null)
                        {
                            session.GetHabbo().CurrentRoom
                            .SendPacket(new UpdateFavouriteGroupComposer(group, user.VirtualId));
                        }
                        session.GetHabbo().CurrentRoom
                        .SendPacket(new RefreshFavouriteGroupComposer(session.GetHabbo().Id));
                    }
                    else
                    {
                        session.SendPacket(new RefreshFavouriteGroupComposer(session.GetHabbo().Id));
                    }
                }

                return;
            }

            if (group.CreatorId == session.GetHabbo().Id || group.IsAdmin(session.GetHabbo().Id))
            {
                if (!group.IsMember(userId))
                {
                    return;
                }

                if (group.IsAdmin(userId) && group.CreatorId != session.GetHabbo().Id)
                {
                    session.SendNotification(
                        "Sorry, only group creators can remove other administrators from the group.");
                    return;
                }

                if (group.IsAdmin(userId))
                {
                    group.TakeAdmin(userId);
                }

                if (group.IsMember(userId))
                {
                    group.DeleteMember(userId);
                }

                List <UserCache> members   = new List <UserCache>();
                List <int>       memberIds = group.GetAllMembers;
                foreach (int id in memberIds.ToList())
                {
                    UserCache groupMember = PlusEnvironment.GetGame().GetCacheManager().GenerateUser(id);
                    if (groupMember == null)
                    {
                        continue;
                    }

                    if (!members.Contains(groupMember))
                    {
                        members.Add(groupMember);
                    }
                }


                int finishIndex  = 14 < members.Count ? 14 : members.Count;
                int membersCount = members.Count;

                session.SendPacket(new GroupMembersComposer(group, members.Take(finishIndex).ToList(), membersCount, 1,
                                                            (group.CreatorId == session.GetHabbo().Id || group.IsAdmin(session.GetHabbo().Id)), 0, ""));
            }
        }
예제 #20
0
 public AccountController(ApplicationUserManager userManager, ApplicationSignInManager signInManager)
 {
     UserManager   = userManager;
     SignInManager = signInManager;
     _appUserCache = new UserCache(CreateRedisCache());
 }
예제 #21
0
 public AccountController()
 {
     _appUserCache = new UserCache(CreateRedisCache());
 }
        public void TestUpdateNotificationForActiveBuild()
        {
            UserCache userCache = null;
            try
            {
                // Setup
                userCache = new UserCache();
                ConcurrentDictionary<string, User> userDictionary = new ConcurrentDictionary<string, User>();
                userCache.OnUpdate += delegate(object sender, EventArgs args)
                {
                    User user = (User)sender;
                    userDictionary[user.Username] = user;
                };
                BuildServerNotificationType notificationType = BuildServerNotificationType.BuildBuilding;
                string projectId = "project1";
                string buildConfigId = "buildconfig1";
                string username1 = "user11";
                string username2 = "user21";
                string[] recipients = { username1, username2 };
                IBuildServerNotification expectedNotification = new BuildNotification(notificationType, projectId, buildConfigId, recipients);

                // Execute
                userCache.Update(expectedNotification);

                // Test
                foreach (string recipient in recipients)
                {
                    Assert.That(userDictionary.ContainsKey(recipient));
                    User actualUser = userDictionary[recipient];
                    Assert.That(actualUser.Username, NUnit.Framework.Is.EqualTo(recipient));
                    Assert.That(actualUser.IsBuildActive(), NUnit.Framework.Is.True);
                    Assert.That(actualUser.IsAttentionRequired(), NUnit.Framework.Is.False);
                }
            }
            catch (AggregateException ex)
            {
                if (ex.InnerExceptions != null)
                {
                    foreach (Exception exception in ex.InnerExceptions)
                    {
                        Console.WriteLine(exception.Message);
                        Console.WriteLine(exception.StackTrace);
                    }
                }

                throw;
            }
            finally
            {
                if (userCache != null)
                {
                    userCache.Dispose();
                }
            }
        }
        public void TestUpdateUserBothResponsibleAndHasActiveBuild()
        {
            UserCache userCache = null;
            try
            {
                // Setup
                userCache = new UserCache();
                User actualUser = null;
                userCache.OnUpdate += delegate(object sender, EventArgs args) { actualUser = (User)sender; };
                string username = "******";
                string projectId = "project1";

                // First notification
                BuildServerNotificationType notificationType1 = BuildServerNotificationType.BuildResponsibilityAssigned;
                string buildConfigId1 = "buildconfig1";
                string state = BuildServerResponsibilityState.Taken;
                IBuildServerNotification notification1 = new ResponsibilityNotification(notificationType1, projectId, buildConfigId1, username, state);
                userCache.Update(notification1);

                // Second notification
                BuildServerNotificationType notificationType2 = BuildServerNotificationType.BuildBuilding;
                string buildConfigId2 = "buildconfig2";
                string[] recipients = { username };
                IBuildServerNotification notification2 = new BuildNotification(notificationType2, projectId, buildConfigId2, recipients);
                userCache.Update(notification2);

                // Test
                Assert.That(actualUser, NUnit.Framework.Is.Not.Null);
                Assert.That(actualUser.Username, NUnit.Framework.Is.EqualTo(username));
                Assert.That(actualUser.IsBuildActive(), NUnit.Framework.Is.True);
                Assert.That(actualUser.IsAttentionRequired(), NUnit.Framework.Is.True);
            }
            finally
            {
                if (userCache != null)
                {
                    userCache.Dispose();
                }
            }
        }
        public void TestUpdateNotificationForResponsibleForBuild()
        {
            UserCache userCache = null;
            try
            {
                // Setup
                userCache = new UserCache();
                User actualUser = null;
                userCache.OnUpdate += delegate(object sender, EventArgs args) { actualUser = (User)sender; };
                BuildServerNotificationType notificationType = BuildServerNotificationType.BuildResponsibilityAssigned;
                string projectId = "project1";
                string buildConfigId = "buildconfig1";
                string username = "******";
                string state = BuildServerResponsibilityState.Taken;
                IBuildServerNotification expectedNotification = new ResponsibilityNotification(notificationType, projectId, buildConfigId, username, state);

                // Execute
                userCache.Update(expectedNotification);

                // Test
                Assert.That(actualUser, NUnit.Framework.Is.Not.Null);
                Assert.That(actualUser.Username, NUnit.Framework.Is.EqualTo(username));
                Assert.That(actualUser.IsBuildActive(), NUnit.Framework.Is.False);
                Assert.That(actualUser.IsAttentionRequired(), NUnit.Framework.Is.True);
            }
            finally
            {
                if (userCache != null)
                {
                    userCache.Dispose();
                }
            }
        }
 public void TestUpdateWithBuildFailingNotification([Values(BuildServerNotificationType.BuildFailed, BuildServerNotificationType.BuildFailedToStart, BuildServerNotificationType.BuildFailing, BuildServerNotificationType.BuildHanging)] BuildServerNotificationType notificationType)
 {
     UserCache userCache = null;
     try
     {
         string projectId = "project1";
         string buildConfigId = "buildconfig1";
         string username = "******";
         string[] recipients = { username };
         IBuildServerNotification notification = new BuildNotification(notificationType, projectId, buildConfigId, recipients);
         userCache = new UserCache();
         userCache.Update(notification);
         User user = userCache.GetUser(username);
         Assert.That(user.IsAttentionRequired());
     }
     finally
     {
         if (userCache != null)
         {
             userCache.Dispose();
         }
     }
 }
        public void TestUpdateSameUserMadeResponsibleTwiceForSameBuild()
        {
            UserCache userCache = null;
            try
            {
                // Shared
                string projectId = "project1";
                string buildConfigId = "buildconfig1";
                userCache = new UserCache();

                // Events
                BuildServerNotificationType notificationType = BuildServerNotificationType.BuildResponsibilityAssigned;
                string username = "******";
                IBuildServerNotification notification = new ResponsibilityNotification(notificationType, projectId, buildConfigId, username, BuildServerResponsibilityState.Taken);
                string buildKey = Utils.CreateBuildKey(notification);
                userCache.Update(notification);
                userCache.Update(notification);

                // Test
                Assert.That(userCache.GetUser(username).BuildsResponsibleFor.Count, NUnit.Framework.Is.EqualTo(1));
                Assert.That(userCache.GetUser(username).BuildsResponsibleFor.Contains(buildKey));
            }
            finally
            {
                if (userCache != null)
                {
                    userCache.Dispose();
                }
            }
        }
예제 #27
0
        /// <summary>
        /// Called for each time the timer ticks.
        /// </summary>
        /// <param name="State"></param>
        public void Run(object State)
        {
            try
            {
                if (this._disabled)
                {
                    return;
                }

                if (this._timerRunning)
                {
                    this._timerLagging = true;
                    return;
                }

                this._resetEvent.Reset();

                // BEGIN CODE
                List <UserCache> CacheList = PlusEnvironment.GetGame().GetCacheManager().GetUserCache().ToList();
                if (CacheList.Count > 0)
                {
                    foreach (UserCache Cache in CacheList)
                    {
                        try
                        {
                            if (Cache == null)
                            {
                                continue;
                            }

                            UserCache Temp = null;

                            if (Cache.isExpired())
                            {
                                PlusEnvironment.GetGame().GetCacheManager().TryRemoveUser(Cache.Id, out Temp);
                            }

                            Temp = null;
                        }
                        catch (Exception e)
                        {
                            Logging.LogCacheException(e.ToString());
                        }
                    }
                }

                CacheList = null;

                List <Habbo> CachedUsers = PlusEnvironment.GetUsersCached().ToList();
                if (CachedUsers.Count > 0)
                {
                    foreach (Habbo Data in CachedUsers)
                    {
                        try
                        {
                            if (Data == null)
                            {
                                continue;
                            }

                            Habbo Temp = null;

                            if (Data.CacheExpired())
                            {
                                PlusEnvironment.RemoveFromCache(Data.Id, out Temp);
                            }

                            if (Temp != null)
                            {
                                Temp.Dispose();
                            }

                            Temp = null;
                        }
                        catch (Exception e)
                        {
                            Logging.LogCacheException(e.ToString());
                        }
                    }
                }

                CachedUsers = null;
                // END CODE

                // Reset the values
                this._timerRunning = false;
                this._timerLagging = false;

                this._resetEvent.Set();
            }
            catch (Exception e) { Logging.LogCacheException(e.ToString()); }
        }
 public void TestUpdateWithBuildBuildingNotificationForSingleUserDoesNotExist()
 {
     UserCache userCache = null;
     try
     {
         BuildServerNotificationType notificationType = BuildServerNotificationType.BuildBuilding;
         string projectId = "project1";
         string buildConfigId = "buildconfig1";
         string username = "******";
         string[] recipients = { username };
         IBuildServerNotification notification = new BuildNotification(notificationType, projectId, buildConfigId, recipients);
         userCache = new UserCache();
         userCache.Update(notification);
         User user = userCache.GetUser(username);
         Assert.That(user.IsBuildActive());
     }
     finally
     {
         if (userCache != null)
         {
             userCache.Dispose();
         }
     }
 }
예제 #29
0
 public ActionResult CheckOut(Cart pCart, UserCache pUser)
 {
     pCart.SubmitOrderAndClearCart(pUser);
     return View(pUser.Model);
 }
 public void TestUpdateWithResponsibilityTaken([Values(BuildServerNotificationType.BuildResponsibilityAssigned, BuildServerNotificationType.TestResponsibilityAssigned)] BuildServerNotificationType notificationType)
 {
     UserCache userCache = null;
     try
     {
         string projectId = "project1";
         string buildConfigId = "buildconfig1";
         string username = "******";
         string recipients = username;
         string state = "TAKEN";
         IBuildServerNotification notification = new ResponsibilityNotification(notificationType, projectId, buildConfigId, recipients, state);
         userCache = new UserCache();
         userCache.Update(notification);
         User user = userCache.GetUser(username);
         Assert.That(user.IsAttentionRequired());
     }
     finally
     {
         if (userCache != null)
         {
             userCache.Dispose();
         }
     }
 }
예제 #31
0
        public ActionResult UpdateAccountDetails(UserCache pCache, UserViewModel pUpdatedModel)
        {
            try
            {
                pUpdatedModel.UpdateUser(pCache.Model);
            }
            catch (Exception)
            {
                return RedirectToAction("UpdateAccountDetailsFailure");
            }
            finally
            {
                pCache.UpdateUserCache();
            }

            return RedirectToAction("UpdateAccountDetailsSuccess");
        }
예제 #32
0
 public RealTest CreateRealTest(Assemblies assemblies, UserCache cache)
 {
     RealTestFactory testFactory = new RealTestFactory(assemblies, cache);
     return testFactory.CreateRealTestFrom(this);
 }
        public void TestHandleRegistrationRequestAfterBuildNotification()
        {
            UserCache userCache = null;
            NotificationManager notificationManager = null;
            try
            {
                // Setup
                userCache = new UserCache();
                notificationManager = new NotificationManager(0, 0, userCache, false);
                string username = "******";
                string[] recipients = { username };
                BuildServerNotificationType notificationType = BuildServerNotificationType.BuildBuilding;
                string projectId = "project1";
                string buildConfigId = "buildconfig1";
                IBuildServerNotification buildServerNotification = new BuildNotification(notificationType, projectId, buildConfigId, recipients);
                string buildKey = Utils.CreateBuildKey(buildServerNotification);

                // Check that the user doesn't exist prior to the notification
                try
                {
                    userCache.GetUser(username);
                    Assert.Fail();
                }
                catch (KeyNotFoundException)
                {
                    // Expected
                }

                // This will create a user in the cache, but without a hostname
                notificationManager.HandleCommand(buildServerNotification, EventArgs.Empty);
                User user = userCache.GetUser(username);
                Assert.That(user.Username, Is.EqualTo(username));
                Assert.That(user.ActiveBuilds.Contains(buildKey));
                Assert.That(string.IsNullOrEmpty(user.Hostname));

                // Now we create a registration request, which should update the existing user with a hostname
                string hostname = username + "-ws";
                IRequest registrationRequest = new RegistrationRequest(hostname, username);
                notificationManager.HandleCommand(registrationRequest, EventArgs.Empty);
                user = userCache.GetUser(username);
                Assert.That(user.Username, Is.EqualTo(username));
                Assert.That(user.Hostname, Is.EqualTo(hostname));
            }
            finally
            {
                if (notificationManager != null)
                {
                    notificationManager.Dispose();
                }

                if (userCache != null)
                {
                    userCache.Dispose();
                }
            }
        }
        public void TestHandleUpdate()
        {
            NotificationManager notificationManager = null;
            UserCache userCache = null;
            try
            {
                // Setup the basics
                object syncRoot = new object();
                int serverPort = 30001;
                int clientPort = 30002;
                userCache = new UserCache();
                notificationManager = new NotificationManager(serverPort, clientPort, userCache, false);
                string buildKey1 = "buildkey1";
                string buildKey2 = "buildkey2";
                string username = "******";
                string hostname = "localhost";

                // Create a user that has one build building and is responsible for one other build
                User user = new User(username) {
                                                       Hostname = hostname
                                               };
                user.ActiveBuilds.Add(buildKey1);
                user.BuildsResponsibleFor.Add(buildKey2);

                // A dummy client which the notification manager will notify
                Listener listener = new Listener(IPAddress.Any, clientPort);
                Dictionary<RequestType, IRequest> requests = new Dictionary<RequestType, IRequest>();
                listener.OnCommandReceived += (sender, args) =>
                {
                    requests.Add(((IRequest)sender).Type, (IRequest)sender);
                    lock (syncRoot)
                    {
                        Monitor.Pulse(syncRoot);
                    }
                };
                listener.Start();
                Assert.That(listener.Running, Is.True);

                // Raise an update for this user and wait until all events caused have been raised
                lock (syncRoot)
                {
                    notificationManager.HandleUpdate(user, EventArgs.Empty);
                    ////Monitor.Wait(syncRoot, 5000);
                    Monitor.Wait(syncRoot, 5000);
                }

                listener.Stop();
                Assert.That(listener.Running, Is.False);

                // Test
                Assert.That(requests.ContainsKey(RequestType.BuildActive));
                BuildActiveRequest buildActiveRequest = (BuildActiveRequest)requests[RequestType.BuildActive];
                Assert.That(buildActiveRequest.IsBuildsActive, Is.True);
            }
            finally
            {
                if (notificationManager != null)
                {
                    notificationManager.Dispose();
                }

                if (userCache != null)
                {
                    userCache.Dispose();
                }
            }
        }
예제 #35
0
 // **************************************
 // URL: /Account/UpdateAccountDetails
 // **************************************
 public ActionResult UpdateAccountDetails(UserCache pUser)
 {
     return(View(new UserViewModel(pUser.Model)));
 }
예제 #36
0
 // **************************************
 // URL: /Account/UpdateAccountDetails
 // **************************************
 public ActionResult UpdateAccountDetails(UserCache pUser)
 {
     return View(new UserViewModel(pUser.Model));
 }
        public void TestUpdateDuplicateBuildKeyForActiveBuildsOneMustRemainAfterTheOtherFinished()
        {
            UserCache userCache = null;
            try
            {
                // Shared
                string projectId = "project1";
                string buildConfigId = "buildconfig1";
                userCache = new UserCache();

                // Events
                BuildServerNotificationType notificationType = BuildServerNotificationType.BuildBuilding;
                string username = "******";
                string[] recipients = { username };
                IBuildServerNotification notification = new BuildNotification(notificationType, projectId, buildConfigId, recipients);
                string buildKey = Utils.CreateBuildKey(notification);
                userCache.Update(notification);
                userCache.Update(notification);
                notificationType = BuildServerNotificationType.BuildSuccessful;
                notification = new BuildNotification(notificationType, projectId, buildConfigId, recipients);
                userCache.Update(notification);

                // Test
                Assert.That(userCache.GetUser(username).ActiveBuilds.Contains(buildKey));
            }
            finally
            {
                if (userCache != null)
                {
                    userCache.Dispose();
                }
            }
        }
        public void TestHandleRegistrationRequest()
        {
            UserCache userCache = null;
            NotificationManager notificationManager = null;
            try
            {
                userCache = new UserCache();
                notificationManager = new NotificationManager(0, 0, userCache, false);
                string username = "******";
                string hostname = username + "-ws";
                IRequest registrationRequest = new RegistrationRequest(hostname, username);

                // Check that the user doesn't exist prior to the registration request
                try
                {
                    userCache.GetUser(username);
                    Assert.Fail();
                }
                catch (KeyNotFoundException)
                {
                }

                notificationManager.HandleCommand(registrationRequest, EventArgs.Empty);
                User user = userCache.GetUser(username);
                Assert.That(user.Username, Is.EqualTo(username));
                Assert.That(user.Hostname, Is.EqualTo(hostname));

                // Registering the same user a second time shouldn't fail
                notificationManager.HandleCommand(registrationRequest, EventArgs.Empty);
            }
            finally
            {
                if (notificationManager != null)
                {
                    notificationManager.Dispose();
                }

                if (userCache != null)
                {
                    userCache.Dispose();
                }
            }
        }
        public void TestUpdateDuplicateBuildKeyOnActiveBuildForResponsibleUser()
        {
            UserCache userCache = null;
            try
            {
                // Shared
                string projectId = "project1";
                string buildConfigId = "buildconfig1";
                userCache = new UserCache();

                // Events
                BuildServerNotificationType notificationType = BuildServerNotificationType.BuildFailed;
                string username = "******";
                string[] recipients = { username };
                IBuildServerNotification notification = new BuildNotification(notificationType, projectId, buildConfigId, recipients);
                string buildKey = Utils.CreateBuildKey(notification);
                userCache.Update(notification);
                userCache.Update(notification);

                // Test
                Assert.That(userCache.GetUser(username).BuildsResponsibleFor.Contains(buildKey));
            }
            finally
            {
                if (userCache != null)
                {
                    userCache.Dispose();
                }
            }
        }
        public void TestHandleResponsibilityNotification()
        {
            UserCache userCache = null;
            NotificationManager notificationManager = null;
            try
            {
                userCache = new UserCache();
                notificationManager = new NotificationManager(0, 0, userCache, false);
                string username = "******";
                BuildServerNotificationType notificationType = BuildServerNotificationType.BuildResponsibilityAssigned;
                string state = BuildServerResponsibilityState.Taken;
                string projectId = "project1";
                string buildConfigId = "buildconfig1";
                IBuildServerNotification buildServerNotification = new ResponsibilityNotification(notificationType, projectId, buildConfigId, username, state);
                string buildKey = Utils.CreateBuildKey(buildServerNotification);
                notificationManager.HandleCommand(buildServerNotification, EventArgs.Empty);
                User user = userCache.GetUser(username);
                Assert.That(user.Username, Is.EqualTo(username));
                Assert.That(user.BuildsResponsibleFor.Contains(buildKey));
            }
            finally
            {
                if (notificationManager != null)
                {
                    notificationManager.Dispose();
                }

                if (userCache != null)
                {
                    userCache.Dispose();
                }
            }
        }
        public void TestUpdateMultipleUsersMultipleBuildsOneBuildingOneSuccessful()
        {
            UserCache userCache = null;
            try
            {
                // Shared
                string projectId1 = "project1";
                string buildConfigId1 = "buildconfig1";
                string projectId2 = "project2";
                string buildConfigId2 = "buildconfig2";
                userCache = new UserCache();

                // Events -- all building
                BuildServerNotificationType notificationType = BuildServerNotificationType.BuildBuilding;
                string username1 = "user1";
                string username2 = "user2";
                string[] recipients = { username1, username2 };
                IBuildServerNotification notification1 = new BuildNotification(notificationType, projectId1, buildConfigId1, recipients);
                string buildKey1 = Utils.CreateBuildKey(notification1);
                userCache.Update(notification1);
                IBuildServerNotification notification2 = new BuildNotification(notificationType, projectId2, buildConfigId2, recipients);
                string buildKey2 = Utils.CreateBuildKey(notification2);
                userCache.Update(notification2);

                // Events -- one successful
                notificationType = BuildServerNotificationType.BuildSuccessful;
                notification1 = new BuildNotification(notificationType, projectId1, buildConfigId1, recipients);
                userCache.Update(notification1);

                // Both users must have only 1 build active
                User user1 = userCache.GetUser(username1);
                Assert.That(user1.IsBuildActive());
                Assert.That(user1.ActiveBuilds.Count, NUnit.Framework.Is.EqualTo(1));
                Assert.That(user1.ActiveBuilds.Contains(buildKey1), NUnit.Framework.Is.False);
                Assert.That(user1.ActiveBuilds.Contains(buildKey2));
                User user2 = userCache.GetUser(username2);
                Assert.That(user2.IsBuildActive());
                Assert.That(user2.ActiveBuilds.Count, NUnit.Framework.Is.EqualTo(1));
                Assert.That(user2.ActiveBuilds.Contains(buildKey1), NUnit.Framework.Is.False);
                Assert.That(user2.ActiveBuilds.Contains(buildKey2));
            }
            finally
            {
                if (userCache != null)
                {
                    userCache.Dispose();
                }
            }
        }
        public void TestInitialize()
        {
            UserCache userCache = null;
            NotificationManager notificationManager = null;
            try
            {
                userCache = new UserCache();
                notificationManager = new NotificationManager(0, 0, userCache, true);
                notificationManager.Start();
                Assert.That(notificationManager.Running, Is.True);
                notificationManager.Stop();
                Assert.That(notificationManager.Running, Is.False);
            }
            finally
            {
                if (notificationManager != null)
                {
                    notificationManager.Dispose();
                }

                if (userCache != null)
                {
                    userCache.Dispose();
                }
            }
        }
        public void TestUpdateNoMultipleUsersResponsibleForBuild()
        {
            UserCache userCache = null;
            try
            {
                // Shared
                string projectId = "project1";
                string buildConfigId = "buildconfig1";
                userCache = new UserCache();

                // User 1 gets assigned
                BuildServerNotificationType notificationType = BuildServerNotificationType.BuildResponsibilityAssigned;
                string username1 = "user1";
                IBuildServerNotification notification1 = new ResponsibilityNotification(notificationType, projectId, buildConfigId, username1, BuildServerResponsibilityState.Taken);
                userCache.Update(notification1);

                // User 2 gets assigned
                string username2 = "user2";
                IBuildServerNotification notification2 = new ResponsibilityNotification(notificationType, projectId, buildConfigId, username2, BuildServerResponsibilityState.Taken);
                userCache.Update(notification2);

                // User 2 but not user 1 must be responsible
                User user1 = userCache.GetUser(username1);
                Assert.That(user1.IsAttentionRequired(), NUnit.Framework.Is.False);
                User user2 = userCache.GetUser(username2);
                Assert.That(user2.IsAttentionRequired());
            }
            finally
            {
                if (userCache != null)
                {
                    userCache.Dispose();
                }
            }
        }
        public void TestHandleCommandForPriorityAttentionRequest()
        {
            UserCache userCache = null;
            NotificationManager notificationManager = null;

            try
            {
                // Setup the notification manager
                object syncRoot = new object();
                int serverPort = 20000;
                int clientPort = 20001;

                // If the timer's expiry (trigger) period is too fast, the test will fail in step 2.
                // We set this (hopefully) sufficiently slow so that we can properly test the
                // sequence of events.
                int priorityTimerPeriod = 10000;

                // Any user's attention required will immediately be set as a priority.
                TimeSpan priorityPeriod = TimeSpan.Zero;

                // Note: The cache's timer starts upon construction
                userCache = new UserCache(priorityTimerPeriod, priorityPeriod);
                notificationManager = new NotificationManager(serverPort, clientPort, userCache, false);

                // A dummy client which the notification manager will notify
                Listener listener = new Listener(IPAddress.Any, clientPort);

                // We only want the attention requests
                AttentionRequest attentionRequest = null;
                listener.OnCommandReceived += (sender, args) =>
                {
                    if (sender.GetType() == typeof(AttentionRequest))
                    {
                        attentionRequest = (AttentionRequest)sender;
                    }

                    lock (syncRoot)
                    {
                        Monitor.Pulse(syncRoot);
                    }
                };

                // Create the requests and notifications
                string username = "******";
                string hostname = "localhost";
                string projectId = "project1";
                string buildConfigId = "buildConfig1";
                string state = BuildServerResponsibilityState.Taken;
                RegistrationRequest registrationRequest = new RegistrationRequest(hostname, username);
                ResponsibilityNotification responsibilityNotification = new ResponsibilityNotification(BuildServerNotificationType.BuildResponsibilityAssigned, projectId, buildConfigId, username, state);

                // Start the server and the client
                notificationManager.Start();
                Assert.That(notificationManager.Running, Is.True);
                listener.Start();
                Assert.That(listener.Running, Is.True);

                // STEP 1
                // Register the dummy client with the server
                lock (syncRoot)
                {
                    // This will cause one attention request and one build active request
                    Utils.SendCommand(hostname, serverPort, Parser.Encode(registrationRequest));
                    Monitor.Wait(syncRoot);
                }

                Assert.That(attentionRequest, Is.Not.Null);
                Assert.That(attentionRequest.IsAttentionRequired, Is.False);
                Assert.That(attentionRequest.IsPriority, Is.False);

                // STEP 2
                attentionRequest = null;
                lock (syncRoot)
                {
                    // This will cause another attention request and another build active request
                    notificationManager.HandleCommand(responsibilityNotification, EventArgs.Empty);
                    Monitor.Wait(syncRoot);
                }

                Assert.That(attentionRequest, Is.Not.Null);
                Assert.That(attentionRequest != null && attentionRequest.IsAttentionRequired, Is.True);
                Assert.That(attentionRequest != null && attentionRequest.IsPriority, Is.False);

                // STEP 3
                // The next two pulses (again for an attention and a build active request) must
                // be because of the timer that expired
                attentionRequest = null;
                lock (syncRoot)
                {
                    Monitor.Wait(syncRoot);
                }

                // Shut down
                notificationManager.Stop();
                Assert.That(notificationManager.Running, Is.False);
                listener.Stop();
                Assert.That(listener.Running, Is.False);

                // Test
                Assert.That(attentionRequest, Is.Not.Null);
                Assert.That(attentionRequest != null && attentionRequest.IsAttentionRequired, Is.True);
                Assert.That(attentionRequest != null && attentionRequest.IsPriority, Is.True);
            }
            finally
            {
                if (notificationManager != null)
                {
                    notificationManager.Dispose();
                }

                if (userCache != null)
                {
                    userCache.Dispose();
                }
            }
        }
예제 #45
0
        public ApiStory ToApi()
        {
            Host host = HostCache.GetHost(this.HostID);

            return(new ApiStory(
                       this.Title, host.RootUrl + UrlFactory.CreateUrl(UrlFactory.PageName.ViewStory, this.StoryIdentifier, CategoryCache.GetCategory(this.CategoryID, this.HostID).CategoryIdentifier), this.Description,
                       this.CreatedOn, this.PublishedOn, this.IsPublishedToHomepage, this.KickCount, this.CommentCount, UserCache.GetUser(this.UserID).ToApi(host)));
        }