public void TestServices() {
			var settings = new Settings { Uri = new Uri("http://localhost/tp2"), Login = "******", DecryptedPassword = "******" };
			var webServices = new WebServices(settings);
			webServices.Authenticate();

			var assigments = webServices.GetMyAssigments();
			Assert.IsNotNull(assigments);
			foreach (var assignable in assigments.Assignables) {
				Console.WriteLine("assignable={0}", assignable);
			}

			{
				var assignables = webServices.GetAssignables();
				Assert.IsNotNull(assignables);
				foreach (var assignable in assignables) {
					Console.WriteLine("assignable={0}", assignable);
				}
			}
			{
				var assignables = webServices.GetAssignables(1, 2, 3, 4, 5);
				Assert.IsNotNull(assignables);
				foreach (var assignable in assignables) {
					Console.WriteLine("assignable={0}", assignable);
				}
			}
		}
 private void PopulateCategories()
 {
     WebServices s = new WebServices();
       Cursor = Cursors.WaitCursor;
       categories.DataSource = s.GetCategories(((FormattedEvent)winSplitsEvents.SelectedItem).Event.DatabaseId);
       Cursor = Cursors.Default;
       categories.DisplayMember = "Name";
 }
    public void CreateServiceWithUrlUserNamePassword(string url, string username, string password)
    {
        ICertificateValidator certificateValidator = new AlwaysValidCertificateValidator();
        ServicePointManager.ServerCertificateValidationCallback = certificateValidator.Validate;

        GeoMaestroServices = new WebServices
                                 {
                                     Url = url,
                                     Credentials = new NetworkCredential(username, password)
                                 };
    }
 public BookingModel(WebServices.Booking b)
 {
     this.ReferenceNumber = b.reference_number;
     this.FlightNumber = b.flight_number;
     this.TravelClassCode = b.travel_class_code;
     this.Confirmed = b.confirmed;
     this.Passengers = new PassengerModel[b.Passenger_Bookings.Count()];
     for (var i = 0; i < this.Passengers.Length; i++)
     {
         this.Passengers[i] = new PassengerModel(b.Passenger_Bookings[i].Passenger);
     }
 }
Esempio n. 5
0
		private static int Main2 (string [] arguments)
		{
			Lock process_lock;

			try {
				if (!Configuration.LoadConfiguration (arguments))
					return 1;

				if (!Configuration.VerifyBuildBotConfiguration ())
					return 1;

				process_lock = Lock.Create ("MonkeyWrench.Builder");
				if (process_lock == null) {
					Logger.Log ("Builder could not acquire lock. Exiting");
					return 1;
				}
				Logger.Log ("Builder lock aquired successfully.");
			} catch (Exception ex) {
				Logger.Log ("Could not aquire lock: {0}", ex.Message);
				return 1;
			}

			try {
				WebService = WebServices.Create ();
				WebService.CreateLogin (Configuration.Host, Configuration.WebServicePassword);

				response = WebService.GetBuildInfoMultiple (WebService.WebServiceLogin, Configuration.Host, true);

				if (!response.Host.enabled) {
					Logger.Log ("This host is disabled. Exiting.");
					return 0;
				}

				Logger.Log ("Builder will now build {0} lists of work items.", response.Work.Count);

				for (int i = 0; i < response.Work.Count; i++) {
					//foreach (var item in response.Work)
					Logger.Log ("Building list #{0}/{1}", i+ 1, response.Work.Count);
					Build (response.Work [i]);//item);
				}

				Logger.Log ("Builder finished successfully.");

				return 0;
			} catch (Exception ex) {
				Logger.Log ("An exception occurred: {0}", ex.ToString ());
				return 1;
			} finally {
				process_lock.Unlock ();
			}
		}
 private void PopulateEvents()
 {
     WebServices s = new WebServices();
       Cursor = Cursors.WaitCursor;
       FormattedEvent[] events = FormattedEvent.ToFormattedEvents(s.GetEvents(startDate.Value, endDate.Value));
       Cursor = Cursors.Default;
       updatingUiNow = true;
       Array.Reverse(events);
       winSplitsEvents.DataSource = events;
       if(winSplitsEvents.Items.Count > 0) winSplitsEvents.SelectedIndex = 0;
       PopulateCategories();
       PopulateRunners();
       updatingUiNow = false;
 }
 public ReservationModel(WebServices.Reservation r)
 {
     this.ReferenceNumber = r.reference_number;
     this.HotelCode = r.hotel_code;
     this.CheckIn = r.check_in;
     this.CheckOut = r.check_out;
     this.RoomTypeCode = r.room_type_code;
     this.Confirmed = r.confirmed;
     this.Passengers = new PassengerModel[r.Passenger_Reservations.Count()];
     for (var i = 0; i < this.Passengers.Length; i++)
     {
         this.Passengers[i] = new PassengerModel(r.Passenger_Reservations[i].Passenger);
     }
     this.RoomsRequested = r.rooms_requested;
 }
        public TestUtilityServices()
        {
            const string username = "******";
            const string password = "";

            geoWS = new WebServices
                        {
                            Url = "http://localhost/geonext/webservices/geonext.asmx",
                            Credentials = new System.Net.NetworkCredential(username, password)
                        };

            Console.WriteLine("*************************");
            Console.WriteLine("Initilize Successfull!");
            Console.WriteLine("Host:" + geoWS.Url);
            Console.WriteLine("Username:"******"Password:"******"*************************");
        }
Esempio n. 9
0
        internal LobbyLogic(Widget widget, ModData modData, WorldRenderer worldRenderer, OrderManager orderManager,
                            Action onExit, Action onStart, bool skirmishMode, Dictionary <string, MiniYaml> logicArgs)
        {
            map                = MapCache.UnknownMap;
            lobby              = widget;
            this.modData       = modData;
            this.orderManager  = orderManager;
            this.worldRenderer = worldRenderer;
            this.onStart       = onStart;
            this.onExit        = onExit;
            this.skirmishMode  = skirmishMode;

            // TODO: This needs to be reworked to support per-map tech levels, bots, etc.
            modRules      = modData.DefaultRules;
            shellmapWorld = worldRenderer.World;

            services = modData.Manifest.Get <WebServices>();

            orderManager.AddChatLine    += AddChatLine;
            Game.LobbyInfoChanged       += UpdateCurrentMap;
            Game.LobbyInfoChanged       += UpdatePlayerList;
            Game.LobbyInfoChanged       += UpdateDiscordStatus;
            Game.BeforeGameStart        += OnGameStart;
            Game.ConnectionStateChanged += ConnectionStateChanged;

            var name = lobby.GetOrNull <LabelWidget>("SERVER_NAME");

            if (name != null)
            {
                name.GetText = () => orderManager.LobbyInfo.GlobalSettings.ServerName;
            }

            var mapContainer = Ui.LoadWidget("MAP_PREVIEW", lobby.Get("MAP_PREVIEW_ROOT"), new WidgetArgs
            {
                { "orderManager", orderManager },
                { "getMap", (Func <MapPreview>)(() => map) },
                {
                    "onMouseDown", (Action <MapPreviewWidget, MapPreview, MouseInput>)((preview, mapPreview, mi) =>
                                                                                       LobbyUtils.SelectSpawnPoint(orderManager, preview, mapPreview, mi))
                },
                {
                    "getSpawnOccupants", (Func <MapPreview, Dictionary <CPos, SpawnOccupant> >)(mapPreview =>
                                                                                                LobbyUtils.GetSpawnOccupants(orderManager.LobbyInfo, mapPreview))
                },
                { "showUnoccupiedSpawnpoints", true },
            });

            mapContainer.IsVisible = () => panel != PanelType.Servers;

            UpdateCurrentMap();

            var playerBin = Ui.LoadWidget("LOBBY_PLAYER_BIN", lobby.Get("TOP_PANELS_ROOT"), new WidgetArgs());

            playerBin.IsVisible = () => panel == PanelType.Players;

            players = playerBin.Get <ScrollPanelWidget>("LOBBY_PLAYERS");
            editablePlayerTemplate       = players.Get("TEMPLATE_EDITABLE_PLAYER");
            nonEditablePlayerTemplate    = players.Get("TEMPLATE_NONEDITABLE_PLAYER");
            emptySlotTemplate            = players.Get("TEMPLATE_EMPTY");
            editableSpectatorTemplate    = players.Get("TEMPLATE_EDITABLE_SPECTATOR");
            nonEditableSpectatorTemplate = players.Get("TEMPLATE_NONEDITABLE_SPECTATOR");
            newSpectatorTemplate         = players.Get("TEMPLATE_NEW_SPECTATOR");
            colorPreview       = lobby.Get <ColorPreviewManagerWidget>("COLOR_MANAGER");
            colorPreview.Color = Game.Settings.Player.Color;

            foreach (var f in modRules.Actors["world"].TraitInfos <FactionInfo>())
            {
                factions.Add(f.InternalName, new LobbyFaction {
                    Selectable = f.Selectable, Name = f.Name, Side = f.Side, Description = f.Description
                });
            }

            var         gameStarting          = false;
            Func <bool> configurationDisabled = () => !Game.IsHost || gameStarting ||
                                                panel == PanelType.Kick || panel == PanelType.ForceStart ||
                                                !map.RulesLoaded || map.InvalidCustomRules ||
                                                orderManager.LocalClient == null || orderManager.LocalClient.IsReady;

            var mapButton = lobby.GetOrNull <ButtonWidget>("CHANGEMAP_BUTTON");

            if (mapButton != null)
            {
                mapButton.IsVisible  = () => panel != PanelType.Servers;
                mapButton.IsDisabled = () => gameStarting || panel == PanelType.Kick || panel == PanelType.ForceStart ||
                                       orderManager.LocalClient == null || orderManager.LocalClient.IsReady;
                mapButton.OnClick = () =>
                {
                    var onSelect = new Action <string>(uid =>
                    {
                        // Don't select the same map again
                        if (uid == map.Uid)
                        {
                            return;
                        }

                        orderManager.IssueOrder(Order.Command("map " + uid));
                        Game.Settings.Server.Map = uid;
                        Game.Settings.Save();
                    });

                    Ui.OpenWindow("MAPCHOOSER_PANEL", new WidgetArgs()
                    {
                        { "initialMap", map.Uid },
                        { "initialTab", MapClassification.System },
                        { "onExit", DoNothing },
                        { "onSelect", Game.IsHost ? onSelect : null },
                        { "filter", MapVisibility.Lobby },
                    });
                };
            }

            var slotsButton = lobby.GetOrNull <DropDownButtonWidget>("SLOTS_DROPDOWNBUTTON");

            if (slotsButton != null)
            {
                slotsButton.IsVisible  = () => panel != PanelType.Servers;
                slotsButton.IsDisabled = () => configurationDisabled() || panel != PanelType.Players ||
                                         (orderManager.LobbyInfo.Slots.Values.All(s => !s.AllowBots) &&
                                          orderManager.LobbyInfo.Slots.Count(s => !s.Value.LockTeam && orderManager.LobbyInfo.ClientInSlot(s.Key) != null) == 0);

                slotsButton.OnMouseDown = _ =>
                {
                    var botTypes = map.Rules.Actors["player"].TraitInfos <IBotInfo>().Select(t => t.Type);
                    var options  = new Dictionary <string, IEnumerable <DropDownOption> >();

                    var botController = orderManager.LobbyInfo.Clients.FirstOrDefault(c => c.IsAdmin);
                    if (orderManager.LobbyInfo.Slots.Values.Any(s => s.AllowBots))
                    {
                        var botOptions = new List <DropDownOption>()
                        {
                            new DropDownOption()
                            {
                                Title      = "Add",
                                IsSelected = () => false,
                                OnClick    = () =>
                                {
                                    foreach (var slot in orderManager.LobbyInfo.Slots)
                                    {
                                        var bot = botTypes.Random(Game.CosmeticRandom);
                                        var c   = orderManager.LobbyInfo.ClientInSlot(slot.Key);
                                        if (slot.Value.AllowBots == true && (c == null || c.Bot != null))
                                        {
                                            orderManager.IssueOrder(Order.Command("slot_bot {0} {1} {2}".F(slot.Key, botController.Index, bot)));
                                        }
                                    }
                                }
                            }
                        };

                        if (orderManager.LobbyInfo.Clients.Any(c => c.Bot != null))
                        {
                            botOptions.Add(new DropDownOption()
                            {
                                Title      = "Remove",
                                IsSelected = () => false,
                                OnClick    = () =>
                                {
                                    foreach (var slot in orderManager.LobbyInfo.Slots)
                                    {
                                        var c = orderManager.LobbyInfo.ClientInSlot(slot.Key);
                                        if (c != null && c.Bot != null)
                                        {
                                            orderManager.IssueOrder(Order.Command("slot_open " + slot.Value.PlayerReference));
                                        }
                                    }
                                }
                            });
                        }

                        options.Add("Configure Bots", botOptions);
                    }

                    var teamCount = (orderManager.LobbyInfo.Slots.Count(s => !s.Value.LockTeam && orderManager.LobbyInfo.ClientInSlot(s.Key) != null) + 1) / 2;
                    if (teamCount >= 1)
                    {
                        var teamOptions = Enumerable.Range(2, teamCount - 1).Reverse().Select(d => new DropDownOption
                        {
                            Title      = "{0} Teams".F(d),
                            IsSelected = () => false,
                            OnClick    = () => orderManager.IssueOrder(Order.Command("assignteams {0}".F(d.ToString())))
                        }).ToList();

                        if (orderManager.LobbyInfo.Slots.Any(s => s.Value.AllowBots))
                        {
                            teamOptions.Add(new DropDownOption
                            {
                                Title      = "Humans vs Bots",
                                IsSelected = () => false,
                                OnClick    = () => orderManager.IssueOrder(Order.Command("assignteams 1"))
                            });
                        }

                        teamOptions.Add(new DropDownOption
                        {
                            Title      = "Free for all",
                            IsSelected = () => false,
                            OnClick    = () => orderManager.IssueOrder(Order.Command("assignteams 0"))
                        });

                        options.Add("Configure Teams", teamOptions);
                    }

                    Func <DropDownOption, ScrollItemWidget, ScrollItemWidget> setupItem = (option, template) =>
                    {
                        var item = ScrollItemWidget.Setup(template, option.IsSelected, option.OnClick);
                        item.Get <LabelWidget>("LABEL").GetText = () => option.Title;
                        return(item);
                    };
                    slotsButton.ShowDropDown("LABEL_DROPDOWN_TEMPLATE", 175, options, setupItem);
                };
            }

            var optionsBin = Ui.LoadWidget("LOBBY_OPTIONS_BIN", lobby.Get("TOP_PANELS_ROOT"), new WidgetArgs()
            {
                { "orderManager", orderManager },
                { "getMap", (Func <MapPreview>)(() => map) },
                { "configurationDisabled", configurationDisabled }
            });

            optionsBin.IsVisible = () => panel == PanelType.Options;

            var musicBin = Ui.LoadWidget("LOBBY_MUSIC_BIN", lobby.Get("TOP_PANELS_ROOT"), new WidgetArgs
            {
                { "onExit", DoNothing },
                { "world", worldRenderer.World }
            });

            musicBin.IsVisible = () => panel == PanelType.Music;

            ServerListLogic serverListLogic = null;

            if (!skirmishMode)
            {
                Action <GameServer> doNothingWithServer = _ => { };

                var serversBin = Ui.LoadWidget("LOBBY_SERVERS_BIN", lobby.Get("TOP_PANELS_ROOT"), new WidgetArgs
                {
                    { "onJoin", doNothingWithServer },
                });

                serverListLogic      = serversBin.LogicObjects.Select(l => l as ServerListLogic).FirstOrDefault(l => l != null);
                serversBin.IsVisible = () => panel == PanelType.Servers;
            }

            var tabContainer = skirmishMode ? lobby.Get("SKIRMISH_TABS") : lobby.Get("MULTIPLAYER_TABS");

            tabContainer.IsVisible = () => true;

            var optionsTab = tabContainer.Get <ButtonWidget>("OPTIONS_TAB");

            optionsTab.IsHighlighted = () => panel == PanelType.Options;
            optionsTab.IsDisabled    = OptionsTabDisabled;
            optionsTab.OnClick       = () => panel = PanelType.Options;
            optionsTab.GetText       = () => !map.RulesLoaded ? "Loading..." : optionsTab.Text;

            var playersTab = tabContainer.Get <ButtonWidget>("PLAYERS_TAB");

            playersTab.IsHighlighted = () => panel == PanelType.Players;
            playersTab.IsDisabled    = () => panel == PanelType.Kick || panel == PanelType.ForceStart;
            playersTab.OnClick       = () => panel = PanelType.Players;

            var musicTab = tabContainer.Get <ButtonWidget>("MUSIC_TAB");

            musicTab.IsHighlighted = () => panel == PanelType.Music;
            musicTab.IsDisabled    = () => panel == PanelType.Kick || panel == PanelType.ForceStart;
            musicTab.OnClick       = () => panel = PanelType.Music;

            var serversTab = tabContainer.GetOrNull <ButtonWidget>("SERVERS_TAB");

            if (serversTab != null)
            {
                serversTab.IsHighlighted = () => panel == PanelType.Servers;
                serversTab.IsDisabled    = () => panel == PanelType.Kick || panel == PanelType.ForceStart;
                serversTab.OnClick       = () =>
                {
                    // Refresh the list when switching to the servers tab
                    if (serverListLogic != null && panel != PanelType.Servers)
                    {
                        serverListLogic.RefreshServerList();
                    }

                    panel = PanelType.Servers;
                };
            }

            // Force start panel
            Action startGame = () =>
            {
                gameStarting = true;
                orderManager.IssueOrder(Order.Command("startgame"));
            };

            var startGameButton = lobby.GetOrNull <ButtonWidget>("START_GAME_BUTTON");

            if (startGameButton != null)
            {
                startGameButton.IsDisabled = () => configurationDisabled() || map.Status != MapStatus.Available ||
                                             orderManager.LobbyInfo.Slots.Any(sl => sl.Value.Required && orderManager.LobbyInfo.ClientInSlot(sl.Key) == null) ||
                                             (!orderManager.LobbyInfo.GlobalSettings.EnableSingleplayer && orderManager.LobbyInfo.NonBotPlayers.Count() < 2);

                startGameButton.OnClick = () =>
                {
                    // Bots and admins don't count
                    if (orderManager.LobbyInfo.Clients.Any(c => c.Slot != null && !c.IsAdmin && c.Bot == null && !c.IsReady))
                    {
                        panel = PanelType.ForceStart;
                    }
                    else
                    {
                        startGame();
                    }
                };
            }

            var forceStartBin = Ui.LoadWidget("FORCE_START_DIALOG", lobby.Get("TOP_PANELS_ROOT"), new WidgetArgs());

            forceStartBin.IsVisible = () => panel == PanelType.ForceStart;
            forceStartBin.Get("KICK_WARNING").IsVisible               = () => orderManager.LobbyInfo.Clients.Any(c => c.IsInvalid);
            forceStartBin.Get <ButtonWidget>("OK_BUTTON").OnClick     = startGame;
            forceStartBin.Get <ButtonWidget>("CANCEL_BUTTON").OnClick = () => panel = PanelType.Players;

            var disconnectButton = lobby.Get <ButtonWidget>("DISCONNECT_BUTTON");

            disconnectButton.OnClick = () => { Ui.CloseWindow(); onExit(); };

            if (skirmishMode)
            {
                disconnectButton.Text = "Back";
            }

            var chatMode = lobby.Get <ButtonWidget>("CHAT_MODE");

            chatMode.GetText    = () => teamChat ? "Team" : "All";
            chatMode.OnClick    = () => teamChat ^= true;
            chatMode.IsDisabled = () => disableTeamChat;

            var chatTextField = lobby.Get <TextFieldWidget>("CHAT_TEXTFIELD");

            chatTextField.MaxLength = UnitOrders.ChatMessageMaxLength;

            chatTextField.TakeKeyboardFocus();
            chatTextField.OnEnterKey = () =>
            {
                if (chatTextField.Text.Length == 0)
                {
                    return(true);
                }

                // Always scroll to bottom when we've typed something
                lobbyChatPanel.ScrollToBottom();

                var teamNumber = 0U;
                if (teamChat && orderManager.LocalClient != null)
                {
                    teamNumber = orderManager.LocalClient.IsObserver ? uint.MaxValue : (uint)orderManager.LocalClient.Team;
                }

                orderManager.IssueOrder(Order.Chat(chatTextField.Text, teamNumber));
                chatTextField.Text = "";
                return(true);
            };

            chatTextField.OnTabKey = () =>
            {
                var previousText = chatTextField.Text;
                chatTextField.Text           = tabCompletion.Complete(chatTextField.Text);
                chatTextField.CursorPosition = chatTextField.Text.Length;

                if (chatTextField.Text == previousText)
                {
                    return(SwitchTeamChat());
                }
                else
                {
                    return(true);
                }
            };

            chatTextField.OnEscKey = () => { chatTextField.Text = ""; return(true); };

            lobbyChatPanel = lobby.Get <ScrollPanelWidget>("CHAT_DISPLAY");
            chatTemplate   = lobbyChatPanel.Get("CHAT_TEMPLATE");
            lobbyChatPanel.RemoveChildren();

            var settingsButton = lobby.GetOrNull <ButtonWidget>("SETTINGS_BUTTON");

            if (settingsButton != null)
            {
                settingsButton.OnClick = () => Ui.OpenWindow("SETTINGS_PANEL", new WidgetArgs
                {
                    { "onExit", DoNothing },
                    { "worldRenderer", worldRenderer }
                });
            }

            // Add a bot on the first lobbyinfo update
            if (skirmishMode)
            {
                addBotOnMapLoad = true;
            }

            MiniYaml yaml;

            if (logicArgs.TryGetValue("ChatLineSound", out yaml))
            {
                chatLineSound = yaml.Value;
            }
        }
Esempio n. 10
0
        protected void btnGetMoney_Click(object sender, EventArgs e)
        {
            double nFaucetReward = 10;

            List <Payment> p  = new List <Payment>();
            Payment        p1 = new Payment();

            p1.bbpaddress = txtAddress.Text;
            p1.amount     = nFaucetReward;
            p.Add(p1);
            string poolAccount = GetBMSConfigurationKeyValue("PoolPayAccount");
            string sValid      = WebServices.VerifyEmailAddress(txtEmail.Text, "");

            Log("Checking For Faucet " + txtEmail.Text + ": " + sValid);
            if (sValid != "deliverable")
            {
                MsgBox("Email Invalid", "Sorry, the e-mail address is invalid. ", this);
                return;
            }
            bool fBBPValid = BMS.ValidateAddress(txtAddress.Text, "BBP");

            if (!fBBPValid)
            {
                MsgBox("BBP Address Invalid", "Sorry, the address is invalid. ", this);
                return;
            }
            string sEmail = txtEmail.Text.Trim();
            string sIP    = (HttpContext.Current.Request.UserHostAddress ?? "").ToString();

            sIP = sIP.Replace("::ffff:", "");
            string sql   = "Select count(*) ct from Faucet where IPAddress='" + sIP + "' OR bbpaddress = '" + BMS.PurifySQL(txtAddress.Text, 250) + "' or EmailAddress='" + BMS.PurifySQL(sEmail, 200) + "'";
            double nDupe = gData.GetScalarDouble(sql, "ct");

            sql = "Select count(*) ct from Users where EmailAddress='" + BMS.PurifySQL(sEmail, 200) + "'";
            double nDupe2 = gData.GetScalarDouble(sql, "ct");
            double nDupe3 = 0;

            if (Session["Faucet"].ToNonNullString() == "1")
            {
                nDupe3 = 1;
            }
            if (nDupe > 0 || nDupe2 > 0 || nDupe3 > 0)
            {
                MsgBox("Duplicate withdrawal", "Sorry, this is a duplicate withdrawal. ", this);
                return;
            }

            // Update the amount
            string txid = SendMany(p, poolAccount, "Withdrawal");

            if (txid == "" || txid == null)
            {
                MsgBox("Withdrawal Failure", "Sorry, the withdrawal failed!  Please contact [email protected]. ", this);
                return;
            }
            else
            {
                sql = "insert into Faucet (id, BBPAddress, IPAddress, EmailAddress, Amount, Added) values (newid(), @address, @ipaddress, @emailaddress, @amount, getdate())";
                SqlCommand command = new SqlCommand(sql);
                command.Parameters.AddWithValue("@address", txtAddress.Text.Trim());
                command.Parameters.AddWithValue("@ipaddress", sIP);
                command.Parameters.AddWithValue("@emailaddress", sEmail);
                command.Parameters.AddWithValue("@amount", nFaucetReward);
                gData.ExecCmd(command);
                Session["Faucet"] = "1";

                string sNarr = "The withdrawal was successful; the TXID is <font color=green>" + txid.ToString() + "</font>.  <br><br><br> Thank you for using BiblePay! <br><br><h4>Click <a href=media.aspx?category=miscellaneous>here to see our Christian Videos. </a></h4><br> ";
                MsgBox("Success. ", sNarr, this);
                return;
            }
        }
Esempio n. 11
0
 public void Valid()
 {
     Debug.Log("Valid");
     WebServices.Login(LoginField.text, PasswordField.text, OnSuccess);
 }
Esempio n. 12
0
        internal LobbyLogic(Widget widget, ModData modData, WorldRenderer worldRenderer, OrderManager orderManager,
                            Action onExit, Action onStart, bool skirmishMode)
        {
            map               = MapCache.UnknownMap;
            lobby             = widget;
            this.modData      = modData;
            this.orderManager = orderManager;
            this.onStart      = onStart;
            this.onExit       = onExit;
            this.skirmishMode = skirmishMode;

            // TODO: This needs to be reworked to support per-map tech levels, bots, etc.
            this.modRules = modData.DefaultRules;
            shellmapWorld = worldRenderer.World;

            services = modData.Manifest.Get <WebServices>();

            orderManager.AddChatLine    += AddChatLine;
            Game.LobbyInfoChanged       += UpdateCurrentMap;
            Game.LobbyInfoChanged       += UpdatePlayerList;
            Game.BeforeGameStart        += OnGameStart;
            Game.ConnectionStateChanged += ConnectionStateChanged;

            var name = lobby.GetOrNull <LabelWidget>("SERVER_NAME");

            if (name != null)
            {
                name.GetText = () => orderManager.LobbyInfo.GlobalSettings.ServerName;
            }

            Ui.LoadWidget("MAP_PREVIEW", lobby.Get("MAP_PREVIEW_ROOT"), new WidgetArgs
            {
                { "orderManager", orderManager },
                { "getMap", (Func <MapPreview>)(() => map) },
                { "onMouseDown", (Action <MapPreviewWidget, MapPreview, MouseInput>)((preview, mapPreview, mi) =>
                                                                                     LobbyUtils.SelectSpawnPoint(orderManager, preview, mapPreview, mi)) },
                { "getSpawnOccupants", (Func <MapPreview, Dictionary <CPos, SpawnOccupant> >)(mapPreview => LobbyUtils.GetSpawnOccupants(orderManager.LobbyInfo, mapPreview)) },
                { "showUnoccupiedSpawnpoints", true },
            });

            UpdateCurrentMap();

            var playerBin = Ui.LoadWidget("LOBBY_PLAYER_BIN", lobby.Get("TOP_PANELS_ROOT"), new WidgetArgs());

            playerBin.IsVisible = () => panel == PanelType.Players;

            players = playerBin.Get <ScrollPanelWidget>("LOBBY_PLAYERS");
            editablePlayerTemplate       = players.Get("TEMPLATE_EDITABLE_PLAYER");
            nonEditablePlayerTemplate    = players.Get("TEMPLATE_NONEDITABLE_PLAYER");
            emptySlotTemplate            = players.Get("TEMPLATE_EMPTY");
            editableSpectatorTemplate    = players.Get("TEMPLATE_EDITABLE_SPECTATOR");
            nonEditableSpectatorTemplate = players.Get("TEMPLATE_NONEDITABLE_SPECTATOR");
            newSpectatorTemplate         = players.Get("TEMPLATE_NEW_SPECTATOR");
            colorPreview       = lobby.Get <ColorPreviewManagerWidget>("COLOR_MANAGER");
            colorPreview.Color = Game.Settings.Player.Color;

            foreach (var f in modRules.Actors["world"].TraitInfos <FactionInfo>())
            {
                factions.Add(f.InternalName, new LobbyFaction {
                    Selectable = f.Selectable, Name = f.Name, Side = f.Side, Description = f.Description
                });
            }

            var         gameStarting          = false;
            Func <bool> configurationDisabled = () => !Game.IsHost || gameStarting ||
                                                panel == PanelType.Kick || panel == PanelType.ForceStart ||
                                                !map.RulesLoaded || map.InvalidCustomRules ||
                                                orderManager.LocalClient == null || orderManager.LocalClient.IsReady;

            var mapButton = lobby.GetOrNull <ButtonWidget>("CHANGEMAP_BUTTON");

            if (mapButton != null)
            {
                mapButton.IsDisabled = () => gameStarting || panel == PanelType.Kick || panel == PanelType.ForceStart ||
                                       orderManager.LocalClient == null || orderManager.LocalClient.IsReady;
                mapButton.OnClick = () =>
                {
                    var onSelect = new Action <string>(uid =>
                    {
                        // Don't select the same map again
                        if (uid == map.Uid)
                        {
                            return;
                        }

                        orderManager.IssueOrder(Order.Command("map " + uid));
                        Game.Settings.Server.Map = uid;
                        Game.Settings.Save();
                    });

                    Ui.OpenWindow("MAPCHOOSER_PANEL", new WidgetArgs()
                    {
                        { "initialMap", map.Uid },
                        { "initialTab", MapClassification.System },
                        { "onExit", DoNothing },
                        { "onSelect", Game.IsHost ? onSelect : null },
                        { "filter", MapVisibility.Lobby },
                    });
                };
            }

            var slotsButton = lobby.GetOrNull <DropDownButtonWidget>("SLOTS_DROPDOWNBUTTON");

            if (slotsButton != null)
            {
                slotsButton.IsDisabled = () => configurationDisabled() || panel != PanelType.Players ||
                                         (orderManager.LobbyInfo.Slots.Values.All(s => !s.AllowBots) &&
                                          orderManager.LobbyInfo.Slots.Count(s => !s.Value.LockTeam && orderManager.LobbyInfo.ClientInSlot(s.Key) != null) == 0);

                slotsButton.OnMouseDown = _ =>
                {
                    var botTypes = map.Rules.Actors["player"].TraitInfos <IBotInfo>().Select(t => t.Type);
                    var options  = new Dictionary <string, IEnumerable <DropDownOption> >();

                    var botController = orderManager.LobbyInfo.Clients.FirstOrDefault(c => c.IsAdmin);
                    if (orderManager.LobbyInfo.Slots.Values.Any(s => s.AllowBots))
                    {
                        var botOptions = new List <DropDownOption>()
                        {
                            new DropDownOption()
                            {
                                Title      = "Add",
                                IsSelected = () => false,
                                OnClick    = () =>
                                {
                                    foreach (var slot in orderManager.LobbyInfo.Slots)
                                    {
                                        var bot = botTypes.Random(Game.CosmeticRandom);
                                        var c   = orderManager.LobbyInfo.ClientInSlot(slot.Key);
                                        if (slot.Value.AllowBots == true && (c == null || c.Bot != null))
                                        {
                                            orderManager.IssueOrder(Order.Command("slot_bot {0} {1} {2}".F(slot.Key, botController.Index, bot)));
                                        }
                                    }
                                }
                            }
                        };

                        if (orderManager.LobbyInfo.Clients.Any(c => c.Bot != null))
                        {
                            botOptions.Add(new DropDownOption()
                            {
                                Title      = "Remove",
                                IsSelected = () => false,
                                OnClick    = () =>
                                {
                                    foreach (var slot in orderManager.LobbyInfo.Slots)
                                    {
                                        var c = orderManager.LobbyInfo.ClientInSlot(slot.Key);
                                        if (c != null && c.Bot != null)
                                        {
                                            orderManager.IssueOrder(Order.Command("slot_open " + slot.Value.PlayerReference));
                                        }
                                    }
                                }
                            });
                        }

                        options.Add("Configure Bots", botOptions);
                    }

                    var teamCount = (orderManager.LobbyInfo.Slots.Count(s => !s.Value.LockTeam && orderManager.LobbyInfo.ClientInSlot(s.Key) != null) + 1) / 2;
                    if (teamCount >= 1)
                    {
                        var teamOptions = Enumerable.Range(2, teamCount - 1).Reverse().Select(d => new DropDownOption
                        {
                            Title      = "{0} Teams".F(d),
                            IsSelected = () => false,
                            OnClick    = () => orderManager.IssueOrder(Order.Command("assignteams {0}".F(d.ToString())))
                        }).ToList();

                        if (orderManager.LobbyInfo.Slots.Any(s => s.Value.AllowBots))
                        {
                            teamOptions.Add(new DropDownOption
                            {
                                Title      = "Humans vs Bots",
                                IsSelected = () => false,
                                OnClick    = () => orderManager.IssueOrder(Order.Command("assignteams 1"))
                            });
                        }

                        teamOptions.Add(new DropDownOption
                        {
                            Title      = "Free for all",
                            IsSelected = () => false,
                            OnClick    = () => orderManager.IssueOrder(Order.Command("assignteams 0"))
                        });

                        options.Add("Configure Teams", teamOptions);
                    }

                    Func <DropDownOption, ScrollItemWidget, ScrollItemWidget> setupItem = (option, template) =>
                    {
                        var item = ScrollItemWidget.Setup(template, option.IsSelected, option.OnClick);
                        item.Get <LabelWidget>("LABEL").GetText = () => option.Title;
                        return(item);
                    };
                    slotsButton.ShowDropDown("LABEL_DROPDOWN_TEMPLATE", 175, options, setupItem);
                };
            }

            var optionsBin = Ui.LoadWidget("LOBBY_OPTIONS_BIN", lobby.Get("TOP_PANELS_ROOT"), new WidgetArgs());

            optionsBin.IsVisible = () => panel == PanelType.Options;

            var musicBin = Ui.LoadWidget("LOBBY_MUSIC_BIN", lobby.Get("TOP_PANELS_ROOT"), new WidgetArgs
            {
                { "onExit", DoNothing },
                { "world", worldRenderer.World }
            });

            musicBin.IsVisible = () => panel == PanelType.Music;

            var optionsTab = lobby.Get <ButtonWidget>("OPTIONS_TAB");

            optionsTab.IsHighlighted = () => panel == PanelType.Options;
            optionsTab.IsDisabled    = () => !map.RulesLoaded || map.InvalidCustomRules || panel == PanelType.Kick || panel == PanelType.ForceStart;
            optionsTab.OnClick       = () => panel = PanelType.Options;

            var playersTab = lobby.Get <ButtonWidget>("PLAYERS_TAB");

            playersTab.IsHighlighted = () => panel == PanelType.Players;
            playersTab.IsDisabled    = () => panel == PanelType.Kick || panel == PanelType.ForceStart;
            playersTab.OnClick       = () => panel = PanelType.Players;

            var musicTab = lobby.Get <ButtonWidget>("MUSIC_TAB");

            musicTab.IsHighlighted = () => panel == PanelType.Music;
            musicTab.IsDisabled    = () => panel == PanelType.Kick || panel == PanelType.ForceStart;
            musicTab.OnClick       = () => panel = PanelType.Music;

            // Force start panel
            Action startGame = () =>
            {
                gameStarting = true;
                orderManager.IssueOrder(Order.Command("startgame"));
            };

            var startGameButton = lobby.GetOrNull <ButtonWidget>("START_GAME_BUTTON");

            if (startGameButton != null)
            {
                startGameButton.IsDisabled = () => configurationDisabled() || map.Status != MapStatus.Available ||
                                             orderManager.LobbyInfo.Slots.Any(sl => sl.Value.Required && orderManager.LobbyInfo.ClientInSlot(sl.Key) == null) ||
                                             (!orderManager.LobbyInfo.GlobalSettings.EnableSingleplayer && orderManager.LobbyInfo.NonBotPlayers.Count() < 2);

                startGameButton.OnClick = () =>
                {
                    // Bots and admins don't count
                    if (orderManager.LobbyInfo.Clients.Any(c => c.Slot != null && !c.IsAdmin && c.Bot == null && !c.IsReady))
                    {
                        panel = PanelType.ForceStart;
                    }
                    else
                    {
                        startGame();
                    }
                };
            }

            var forceStartBin = Ui.LoadWidget("FORCE_START_DIALOG", lobby.Get("TOP_PANELS_ROOT"), new WidgetArgs());

            forceStartBin.IsVisible = () => panel == PanelType.ForceStart;
            forceStartBin.Get("KICK_WARNING").IsVisible               = () => orderManager.LobbyInfo.Clients.Any(c => c.IsInvalid);
            forceStartBin.Get <ButtonWidget>("OK_BUTTON").OnClick     = startGame;
            forceStartBin.Get <ButtonWidget>("CANCEL_BUTTON").OnClick = () => panel = PanelType.Players;

            // Options panel
            var optionCheckboxes = new Dictionary <string, string>()
            {
                { "EXPLORED_MAP_CHECKBOX", "explored" },
                { "CRATES_CHECKBOX", "crates" },
                { "SHORTGAME_CHECKBOX", "shortgame" },
                { "FOG_CHECKBOX", "fog" },
                { "ALLYBUILDRADIUS_CHECKBOX", "allybuild" },
                { "ALLOWCHEATS_CHECKBOX", "cheats" },
                { "CREEPS_CHECKBOX", "creeps" },
            };

            foreach (var kv in optionCheckboxes)
            {
                var checkbox = optionsBin.GetOrNull <CheckboxWidget>(kv.Key);
                if (checkbox != null)
                {
                    var option = new CachedTransform <Session.Global, Session.LobbyOptionState>(
                        gs => gs.LobbyOptions[kv.Value]);

                    var visible = new CachedTransform <Session.Global, bool>(
                        gs => gs.LobbyOptions.ContainsKey(kv.Value));

                    checkbox.IsVisible  = () => visible.Update(orderManager.LobbyInfo.GlobalSettings);
                    checkbox.IsChecked  = () => option.Update(orderManager.LobbyInfo.GlobalSettings).Enabled;
                    checkbox.IsDisabled = () => configurationDisabled() ||
                                          option.Update(orderManager.LobbyInfo.GlobalSettings).Locked;
                    checkbox.OnClick = () => orderManager.IssueOrder(Order.Command(
                                                                         "option {0} {1}".F(kv.Value, !option.Update(orderManager.LobbyInfo.GlobalSettings).Enabled)));
                }
            }

            var optionDropdowns = new Dictionary <string, string>()
            {
                { "TECHLEVEL", "techlevel" },
                { "STARTINGUNITS", "startingunits" },
                { "STARTINGCASH", "startingcash" },
                { "DIFFICULTY", "difficulty" },
                { "GAMESPEED", "gamespeed" }
            };

            var allOptions = new CachedTransform <MapPreview, LobbyOption[]>(
                mapPreview => mapPreview.Rules.Actors["player"].TraitInfos <ILobbyOptions>()
                .Concat(mapPreview.Rules.Actors["world"].TraitInfos <ILobbyOptions>())
                .SelectMany(t => t.LobbyOptions(mapPreview.Rules))
                .ToArray());

            foreach (var kv in optionDropdowns)
            {
                var dropdown = optionsBin.GetOrNull <DropDownButtonWidget>(kv.Key + "_DROPDOWNBUTTON");
                if (dropdown != null)
                {
                    var optionValue = new CachedTransform <Session.Global, Session.LobbyOptionState>(
                        gs => gs.LobbyOptions[kv.Value]);

                    var option = new CachedTransform <MapPreview, LobbyOption>(
                        mapPreview => allOptions.Update(mapPreview).FirstOrDefault(o => o.Id == kv.Value));

                    var getOptionLabel = new CachedTransform <string, string>(id =>
                    {
                        string value;
                        if (id == null || !option.Update(map).Values.TryGetValue(id, out value))
                        {
                            return("Not Available");
                        }

                        return(value);
                    });

                    dropdown.GetText    = () => getOptionLabel.Update(optionValue.Update(orderManager.LobbyInfo.GlobalSettings).Value);
                    dropdown.IsVisible  = () => option.Update(map) != null;
                    dropdown.IsDisabled = () => configurationDisabled() ||
                                          optionValue.Update(orderManager.LobbyInfo.GlobalSettings).Locked;

                    dropdown.OnMouseDown = _ =>
                    {
                        Func <KeyValuePair <string, string>, ScrollItemWidget, ScrollItemWidget> setupItem = (c, template) =>
                        {
                            Func <bool> isSelected = () => optionValue.Update(orderManager.LobbyInfo.GlobalSettings).Value == c.Key;
                            Action      onClick    = () => orderManager.IssueOrder(Order.Command("option {0} {1}".F(kv.Value, c.Key)));

                            var item = ScrollItemWidget.Setup(template, isSelected, onClick);
                            item.Get <LabelWidget>("LABEL").GetText = () => c.Value;
                            return(item);
                        };

                        var options = option.Update(map).Values;
                        dropdown.ShowDropDown("LABEL_DROPDOWN_TEMPLATE", options.Count() * 30, options, setupItem);
                    };

                    var label = optionsBin.GetOrNull(kv.Key + "_DESC");
                    if (label != null)
                    {
                        label.IsVisible = () => option.Update(map) != null;
                    }
                }
            }

            var disconnectButton = lobby.Get <ButtonWidget>("DISCONNECT_BUTTON");

            disconnectButton.OnClick = () => { Ui.CloseWindow(); onExit(); };

            if (skirmishMode)
            {
                disconnectButton.Text = "Back";
            }

            var globalChat      = Game.LoadWidget(null, "LOBBY_GLOBALCHAT_PANEL", lobby.Get("GLOBALCHAT_ROOT"), new WidgetArgs());
            var globalChatInput = globalChat.Get <TextFieldWidget>("CHAT_TEXTFIELD");

            globalChat.IsVisible = () => chatPanel == ChatPanelType.Global;

            var globalChatTab = lobby.Get <ButtonWidget>("GLOBALCHAT_TAB");

            globalChatTab.IsHighlighted = () => chatPanel == ChatPanelType.Global;
            globalChatTab.OnClick       = () =>
            {
                chatPanel = ChatPanelType.Global;
                globalChatInput.TakeKeyboardFocus();
            };

            var globalChatLabel = globalChatTab.Text;

            globalChatTab.GetText = () =>
            {
                if (globalChatUnreadMessages == 0 || chatPanel == ChatPanelType.Global)
                {
                    return(globalChatLabel);
                }

                return(globalChatLabel + " ({0})".F(globalChatUnreadMessages));
            };

            globalChatLastReadMessages = Game.GlobalChat.History.Count(m => m.Type == ChatMessageType.Message);

            var lobbyChat = lobby.Get("LOBBYCHAT");

            lobbyChat.IsVisible = () => chatPanel == ChatPanelType.Lobby;

            chatLabel = lobby.Get <LabelWidget>("LABEL_CHATTYPE");
            var chatTextField = lobby.Get <TextFieldWidget>("CHAT_TEXTFIELD");

            chatTextField.MaxLength = UnitOrders.ChatMessageMaxLength;

            chatTextField.TakeKeyboardFocus();
            chatTextField.OnEnterKey = () =>
            {
                if (chatTextField.Text.Length == 0)
                {
                    return(true);
                }

                // Always scroll to bottom when we've typed something
                lobbyChatPanel.ScrollToBottom();

                orderManager.IssueOrder(Order.Chat(teamChat, chatTextField.Text));
                chatTextField.Text = "";
                return(true);
            };

            chatTextField.OnTabKey = () =>
            {
                var previousText = chatTextField.Text;
                chatTextField.Text           = tabCompletion.Complete(chatTextField.Text);
                chatTextField.CursorPosition = chatTextField.Text.Length;

                if (chatTextField.Text == previousText)
                {
                    return(SwitchTeamChat());
                }
                else
                {
                    return(true);
                }
            };

            chatTextField.OnEscKey = () => { chatTextField.Text = ""; return(true); };

            var lobbyChatTab = lobby.Get <ButtonWidget>("LOBBYCHAT_TAB");

            lobbyChatTab.IsHighlighted = () => chatPanel == ChatPanelType.Lobby;
            lobbyChatTab.OnClick       = () =>
            {
                chatPanel = ChatPanelType.Lobby;
                chatTextField.TakeKeyboardFocus();
            };

            var lobbyChatLabel = lobbyChatTab.Text;

            lobbyChatTab.GetText = () =>
            {
                if (lobbyChatUnreadMessages == 0 || chatPanel == ChatPanelType.Lobby)
                {
                    return(lobbyChatLabel);
                }

                return(lobbyChatLabel + " ({0})".F(lobbyChatUnreadMessages));
            };

            lobbyChatPanel = lobby.Get <ScrollPanelWidget>("CHAT_DISPLAY");
            chatTemplate   = lobbyChatPanel.Get("CHAT_TEMPLATE");
            lobbyChatPanel.RemoveChildren();

            var settingsButton = lobby.GetOrNull <ButtonWidget>("SETTINGS_BUTTON");

            if (settingsButton != null)
            {
                settingsButton.OnClick = () => Ui.OpenWindow("SETTINGS_PANEL", new WidgetArgs
                {
                    { "onExit", DoNothing },
                    { "worldRenderer", worldRenderer }
                });
            }

            // Add a bot on the first lobbyinfo update
            if (skirmishMode)
            {
                addBotOnMapLoad = true;
            }
        }
Esempio n. 13
0
        // GET: /Builds/other
        public ActionResult Other()
        {
            WebServices ws = new WebServices ();
            WebServiceLogin login = new WebServiceLogin ();

            FrontPageResponse data = ws.GetFrontPageData2 (login, 10, null, null);

            List<StatusStrip> strips = new List<StatusStrip> ();

            StatusStrip strip_md = new StatusStrip ();
            strip_md.Name = "MonoDevelop - 2.2 - Dist";
            strip_md.Rows.Add (MonkeyWrenchHelper.GetRow (49, data, "dist"));
            strip_md.Rows.Add (MonkeyWrenchHelper.GetRow (50, data, "database-dist"));
            strip_md.Rows.Add (MonkeyWrenchHelper.GetRow (51, data, "boo-dist"));
            strip_md.Rows.Add (MonkeyWrenchHelper.GetRow (52, data, "java-dist"));
            strip_md.Rows.Add (MonkeyWrenchHelper.GetRow (53, data, "vala-dist"));
            strip_md.Rows.Add (MonkeyWrenchHelper.GetRow (54, data, "debugger-gdb-dist"));
            strip_md.Rows.Add (MonkeyWrenchHelper.GetRow (55, data, "debugger-mdb-dist"));
            strip_md.Rows.Add (MonkeyWrenchHelper.GetRow (56, data, "python-dist"));

            StatusStrip strip_tools = new StatusStrip ();
            strip_tools.Name = "Tools - Trunk";
            strip_tools.Rows.Add (MonkeyWrenchHelper.GetRow (10, data, "libgdiplus - dist"));
            strip_tools.Rows.Add (MonkeyWrenchHelper.GetRow (43, data, "libgdiplus - check"));
            strip_tools.Rows.Add (MonkeyWrenchHelper.GetRow (44, data, "mono-tools - dist"));
            strip_tools.Rows.Add (MonkeyWrenchHelper.GetRow (47, data, "xsp - dist"));
            strip_tools.Rows.Add (MonkeyWrenchHelper.GetRow (48, data, "debugger - dist"));

            StatusStrip strip_tools_26 = new StatusStrip ();
            strip_tools_26.Name = "Tools - 2.6";
            strip_tools_26.Rows.Add (MonkeyWrenchHelper.GetRow (76, data, "libgdiplus - dist"));
            strip_tools_26.Rows.Add (MonkeyWrenchHelper.GetRow (78, data, "mono-tools - dist"));
            strip_tools_26.Rows.Add (MonkeyWrenchHelper.GetRow (79, data, "xsp - dist"));
            strip_tools_26.Rows.Add (MonkeyWrenchHelper.GetRow (77, data, "debugger - dist"));
            strip_tools_26.Rows.Add (MonkeyWrenchHelper.GetRow (80, data, "mono-basic - dist"));
            strip_tools_26.Rows.Add (MonkeyWrenchHelper.GetRow (81, data, "mod_mono - dist"));
            strip_tools_26.Rows.Add (MonkeyWrenchHelper.GetRow (82, data, "gluezilla - dist"));

            StatusStrip strip_tools_24 = new StatusStrip ();
            strip_tools_24.Name = "Tools - 2.4.3";
            strip_tools_24.Rows.Add (MonkeyWrenchHelper.GetRow (108, data, "libgdiplus - dist"));
            strip_tools_24.Rows.Add (MonkeyWrenchHelper.GetRow (106, data, "mono-tools - dist"));
            strip_tools_24.Rows.Add (MonkeyWrenchHelper.GetRow (107, data, "xsp - dist"));
            strip_tools_24.Rows.Add (MonkeyWrenchHelper.GetRow (103, data, "debugger - dist"));
            strip_tools_24.Rows.Add (MonkeyWrenchHelper.GetRow (109, data, "mono-basic - dist"));
            strip_tools_24.Rows.Add (MonkeyWrenchHelper.GetRow (105, data, "mod_mono - dist"));
            strip_tools_24.Rows.Add (MonkeyWrenchHelper.GetRow (104, data, "gluezilla - dist"));

            StatusStrip strip_mw = new StatusStrip ();
            strip_mw.Name = "MonkeyWrench";
            strip_mw.Rows.Add (MonkeyWrenchHelper.GetRow (57, data));

            strips.Add (strip_md);
            strips.Add (strip_tools);
            strips.Add (strip_tools_26);
            strips.Add (strip_tools_24);
            strips.Add (strip_mw);

            ViewData["PageTitle"] = "MonkeyWrench - Other Projects Build Overview";

            return View ("Index", strips);
        }
Esempio n. 14
0
 public void SaveScreen(int ReferenceId, string Url)
 {
     WebServices<CreateScreenRequest, CreateScreenResponse> ws = new WebServices<CreateScreenRequest, CreateScreenResponse>();
     var request = new CreateScreenRequest() { ReferenceId = ReferenceId, Url = Url };
     ws.MakeRequest(BaseURL + "/" + Urls.CreateScreen, request);
 }
Esempio n. 15
0
 public NoticiaRepositorio()
 {
     _webServices = new WebServices();
 }
 public GeolearningCSharpExample()
 {
     testUtility = new TestUtilityServices();
     service = testUtility.GetWsConnection();
 }
Esempio n. 17
0
        // GET: /Builds/monodevelop
        public ActionResult MonoDevelop()
        {
            WebServices ws = new WebServices ();
            WebServiceLogin login = new WebServiceLogin ();

            FrontPageResponse data = ws.GetFrontPageData2 (login, 10, null, null);

            List<StatusStrip> strips = new List<StatusStrip> ();

            StatusStrip strip_md = new StatusStrip ("MonoDevelop - Trunk");
            AddRowsToStrip (strip_md, "monodevelop", new int[] { 131 }, data);
            strips.Add (strip_md);

            ViewData["PageTitle"] = "MonkeyWrench - MonoDevelop";

            return View ("Index", strips);
        }
        /// <summary>
        /// Updates the issue tracker from the change set.
        /// </summary>
        /// <param name="repository"> </param>
        /// <param name="changeset"> </param>
        /// <param name="service"> </param>
        public static void UpdateBugNetForChangeset(string repository, Changeset changeset, WebServices.BugNetServices service)
        {
            var issuesAffectedList = new List<int>();
            var regEx = new Regex(AppSettings.IssueIdRegEx, RegexOptions.IgnoreCase);

            var commitMessage = changeset.CommitMessage.Trim();
            var matchResults = regEx.Match(commitMessage);

            if (!matchResults.Success) // none in the commit message
            {
                Log.Info("MercurialChangeGroupHook: Found no Issue Ids in change set");
                return;
            }

            // capture the issues ids in the commit message
            // validate if the issue id is 
            // change the commit message for each issue id (may be more to the commit)
            while (matchResults.Success)
            {
                var value = matchResults.Groups[1].Value.Trim();
                var issueIdParts = value.Split(new[] { '-' });

                if (issueIdParts.Length.Equals(2))
                {
                    var idString = issueIdParts[1];

                    int issueId;
                    if (int.TryParse(idString, out issueId))
                    {
                        if(service.ValidIssue(issueId)) // check the issue to make sure it exists
                        {
                            commitMessage = Regex.Replace(commitMessage, AppSettings.IssueIdRegEx, "<a href=\"IssueDetail.aspx?id=$2#top\"><b>$1</b></a>");
                            issuesAffectedList.Add(issueId);   
                        }
                    }
                }

                matchResults = matchResults.NextMatch();
            }

            if (issuesAffectedList.Count <= 0) return;

            var revisionNumber = changeset.RevisionNumber;
            var revision = changeset.Hash.Trim();
            var author = changeset.AuthorName.Trim();
            var dateTime = changeset.Timestamp.ToString();
            var branch = changeset.Branch.Trim();

            foreach (var id in issuesAffectedList)
            {
                try
                {
                    Log.Info("MercurialChangeGroupHook: Creating new issue revision");

                    var success = service.CreateNewIssueRevision(
                        revisionNumber,
                        id,
                        repository,
                        author,
                        dateTime,
                        commitMessage,
                        revision,
                        branch);

                    if (success)
                        Log.Info("MercurialChangeGroupHook: Successfully added new issue revision");
                    else
                        Log.Warn("MercurialChangeGroupHook: Adding new issue revision failed");
                }
                catch (Exception ex)
                {
                    Log.ErrorFormat("MercurialChangeGroupHook: An error occurred adding a new issue revision to BugNET: {0} \n\n {1}", ex.Message, ex.StackTrace);
                }
            }
        }
Esempio n. 19
0
        // GET: /Builds/Official
        public ActionResult Index()
        {
            int[] trunk_rows = new int[] { 14, 41, 31, 110, 128, 129 };
            int[] mono26_rows = new int[] { 75, 100, 98, 122, 163, 164 };
            int[] mono24_rows = new int[] { 94, 101, 96, 123, 119, 120 };

            WebServices ws = new WebServices ();
            WebServiceLogin login = new WebServiceLogin ();

            DateTime start = DateTime.Now;
            FrontPageResponse data = ws.GetFrontPageData2 (login, 10, null, null);
            TimeSpan data_elapsed = DateTime.Now - start;

            List<StatusStrip> strips = new List<StatusStrip> ();

            StatusStrip strip = new StatusStrip ("Mono - Trunk");
            AddRowsToStrip (strip, "mono", trunk_rows, data);

            StatusStrip strip26 = new StatusStrip ("Mono - 2.6 Branch");
            AddRowsToStrip (strip26, "mono26", mono26_rows, data);

            StatusStrip strip24 = new StatusStrip ("Mono - 2.4 Branch");
            AddRowsToStrip (strip24, "mono24", mono24_rows, data);

            strips.Add (strip);
            strips.Add (strip26);
            strips.Add (strip24);

            // This adds the MSVC build to the page.
            // Disabled because the MSVC build doesn't support Git
            //start = DateTime.Now;
            //try {
            //        MonkeyWrench.Public.Public ws2 = new MvcWrench.MonkeyWrench.Public.Public ();
            //        var msvc = ws2.GetRecentData ("msvc");

            //        strip.Rows.Add (MonkeyWrenchHelper.GetRow (msvc));
            //        //strip.Rows.Insert (0, MonkeyWrenchHelper.GetHeaderRow (msvc));
            //} catch {
            //        // Carry on even if this fails
            //}
            //TimeSpan remote_elapsed = DateTime.Now - start;
            //ViewData["MsvcElapsed"] = remote_elapsed;

            ViewData["PageTitle"] = "MonkeyWrench - Mono Build Overview";
            ViewData["MonkeyWrenchElapsed"] = data_elapsed;

            return View ("Index", strips);
        }
Esempio n. 20
0
        public ActionResult RevisionDetails(string project, string platform, string revision)
        {
            int lane_id;
            int host_id;
            int revision_id;

            if (!FindHostAndLane (project, platform, out host_id, out lane_id))
                return View ("Error");

            WebServices ws = new WebServices ();
            WebServiceLogin login = new WebServiceLogin ();

            var rev = ws.FindRevisionForLane (login, null, revision, lane_id, null);
            revision_id = rev.Revision.id;

            GetViewLaneDataResponse data = ws.GetViewLaneData (login, lane_id, null, host_id, null, revision_id, null);

            Commit commit = new Commit ();

            commit.CompletionStatus = data.RevisionWork.state;
            commit.Revision = data.Revision.revision;
            commit.Author = data.Revision.author;
            commit.CommitTime = data.Revision.date;
            commit.Lane = data.Lane.lane;
            commit.Host = data.Host.host;
            commit.Builder = data.WorkHost == null ? "" : data.WorkHost.host;
            commit.BuildDuration = TimeSpan.Zero;
            commit.CommitLog = "";
            commit.Email = SvnGravatars.Get (commit.Author);
            commit.ProjectLinkName = project;

            // Download the commit log to add
            string url = string.Format ("http://build.mono-project.com/GetRevisionLog.aspx?id={0}", data.Revision.id);

            WebClient wc = new WebClient ();
            string content = wc.DownloadString (url);

            Regex reg = new Regex (@"\<pre\ id\=\""ctl00_content_log\""\>(?<data>(?:.|\n)*?)\<\/pre\>", RegexOptions.Multiline);
            Match m = reg.Match (content);
            commit.CommitLog = m.Groups["data"].Value.Trim ();

            // Build the list of steps
            BuildStepList bsl = new BuildStepList ();

            string history_url = @"http://build.mono-project.com/ViewWorkTable.aspx?lane_id={0}&host_id={1}&command_id={2}";
            string log_url = @"http://build.mono-project.com/GetFile.aspx?id={0}";

            DateTime start_time = DateTime.MinValue;

            for (int j = 0; j < data.WorkViews.Length; j++) {
                var item = data.WorkViews[j];
                var log = data.WorkFileViews[j];

                if (j == 0)
                    start_time = item.starttime;

                BuildStepListItem i = new BuildStepListItem ();

                i.BuildStepID = item.id;
                i.ElapsedTime = item.endtime.Subtract (item.starttime);
                i.HistoryUrl = string.Format (history_url, lane_id, host_id, item.command_id);
                i.Name = item.command;
                i.Results = item.summary;
                i.CompletionStatus = item.state;

                if (log != null && log.Length > 0)
                    i.LogUrl = string.Format (log_url, log[0].id);

                bsl.Items.Add (i);
            }

            if (data.RevisionWork.completed)
                commit.BuildDuration = data.RevisionWork.endtime.Subtract (start_time);

            //ws.getre
            ViewData["commit"] = commit;
            ViewData["steps"] = bsl;
            ViewData["PageTitle"] = string.Format ("MonkeyWrench - Revision {0} - Host {1}", commit.Revision, commit.Host);

            return View ("RevisionDetails");
        }
        public async Task BasicTest2()
        {
            await using var serving = await WebHost.Serve();

            var authServer     = WebServices.GetRequiredService <IServerSideAuthService>();
            var authClient     = ClientServices.GetRequiredService <IAuthService>();
            var authLocal      = Services.GetRequiredService <IServerSideAuthService>();
            var sessionFactory = ClientServices.GetRequiredService <ISessionFactory>();
            var sessionA       = sessionFactory.CreateSession();
            var sessionB       = sessionFactory.CreateSession();
            var bob            = new User("", "Bob")
                                 .WithClaim("id", "bob")
                                 .WithIdentity("g:1");

            var session = sessionA;
            await authServer.SignIn(new SignInCommand(session, bob).MarkServerSide());

            var user = await authServer.GetUser(session);

            user.Name.Should().Be(bob.Name);
            long.TryParse(user.Id, out var _).Should().BeTrue();
            user.Claims.Count.Should().Be(1);
            user.Identities.Single(); // Client-side users shouldn't have them

            // Server-side methods to get the same user
            var sameUser = await authServer.TryGetUser(user.Id);

            sameUser !.Id.Should().Be(user.Id);
            sameUser.Name.Should().Be(user.Name);
            sameUser.Identities.Keys.Select(i => i.Id.Value).Should().BeEquivalentTo(new [] { "g:1" });
            bob = user;

            // Checking if the client is able to see the same user & sessions
            user = await authClient.GetUser(sessionA);

            user.Id.Should().Be(bob.Id);
            user.IsAuthenticated.Should().BeTrue();
            user = await authClient.GetUser(session);

            user.Id.Should().Be(bob.Id);
            user.IsAuthenticated.Should().BeTrue();

            // Checking if local service is able to see the same user & sessions
            if (!Options.UseInMemoryAuthService)
            {
                await Delay(0.5);

                user = await authLocal.GetUser(session);

                user.Id.Should().Be(bob.Id);
                user.IsAuthenticated.Should().BeTrue();
            }

            // Checking guest session
            session = sessionB;
            user    = await authClient.GetUser(session);

            user.IsAuthenticated.Should().BeFalse();

            // Checking sign-out
            await authServer.SignOut(new(sessionA));

            user = await authServer.GetUser(sessionA);

            user.IsAuthenticated.Should().BeFalse();
            await Delay(0.5);

            user = await authClient.GetUser(sessionA);

            user.IsAuthenticated.Should().BeFalse();
            if (!Options.UseInMemoryAuthService)
            {
                user = await authLocal.GetUser(sessionA);

                user.IsAuthenticated.Should().BeFalse();
            }
        }
Esempio n. 22
0
        public StringBuilder Execute(Dictionary <string, StringBuilder> values, IWorkspace theWorkspace)
        {
            var msg        = new ExecuteMessage();
            var serializer = new Dev2JsonSerializer();

            try
            {
                Dev2Logger.Info("Test Web Connection Service", GlobalConstants.WarewolfInfo);

                values.TryGetValue("WebService", out StringBuilder resourceDefinition);

                VerifyArgument.IsNotNull(nameof(WebService), resourceDefinition);

                var src = serializer.Deserialize <IWebService>(resourceDefinition);

                var parameters = src.Inputs?.Select(a => new MethodParameter {
                    EmptyToNull = a.EmptyIsNull, IsRequired = a.RequiredField, Name = a.Name, Value = a.Value
                }).ToList() ?? new List <MethodParameter>();

                var requestHeaders = new List <string>();
                var requestHeader  = string.Empty;

                requestHeaders = src.Headers.Select(nameValue => nameValue.Name + ":" + nameValue.Value).ToList();
                requestHeader  = string.Join(";", requestHeaders).TrimEnd(':', ';');


                var res = new WebService
                {
                    Method              = new ServiceMethod(src.Name, src.Name, parameters, new OutputDescription(), new List <MethodOutput>(), "test"),
                    RequestUrl          = string.Concat(src.RequestUrl, src.QueryString),
                    ResourceName        = src.Name,
                    ResourceID          = src.Id,
                    Headers             = src.Headers,
                    RequestBody         = src.PostData,
                    IsManualChecked     = src.IsManualChecked,
                    IsFormDataChecked   = src.IsFormDataChecked,
                    IsUrlEncodedChecked = src.IsUrlEncodedChecked,
                    FormDataParameters  = src.FormDataParameters?.Where(o => !o.IsEmptyRow).ToList(),
                    RequestHeaders      = requestHeader,
                    RequestMethod       = src.Method,
                    RequestResponse     = src.Response,
                    Source              = new WebSource
                    {
                        Address            = src.Source.HostName,
                        DefaultQuery       = src.Source.DefaultQuery,
                        AuthenticationType = src.Source.AuthenticationType,
                        UserName           = src.Source.UserName,
                        Password           = src.Source.Password
                    }
                };

                WebServices.TestWebService(res);
                msg.HasError = false;
                msg.Message  = serializer.SerializeToBuilder(res);
            }
            catch (Exception err)
            {
                msg.HasError = true;
                msg.Message  = new StringBuilder(err.Message);
                Dev2Logger.Error(err, GlobalConstants.WarewolfError);
            }

            return(serializer.SerializeToBuilder(msg));
        }
Esempio n. 23
0
 public Checker(WebServices i_WebService)
 {
     Checks        = new List <T>();
     UploadResults = new Results();
     m_WebServices = i_WebService;
 }
Esempio n. 24
0
        public ServerListLogic(Widget widget, ModData modData, Action <GameServer> onJoin)
        {
            this.modData = modData;
            this.onJoin  = onJoin;

            services = modData.Manifest.Get <WebServices>();

            incompatibleVersionColor       = ChromeMetrics.Get <Color>("IncompatibleVersionColor");
            incompatibleGameColor          = ChromeMetrics.Get <Color>("IncompatibleGameColor");
            incompatibleProtectedGameColor = ChromeMetrics.Get <Color>("IncompatibleProtectedGameColor");
            protectedGameColor             = ChromeMetrics.Get <Color>("ProtectedGameColor");
            waitingGameColor             = ChromeMetrics.Get <Color>("WaitingGameColor");
            incompatibleWaitingGameColor = ChromeMetrics.Get <Color>("IncompatibleWaitingGameColor");
            gameStartedColor             = ChromeMetrics.Get <Color>("GameStartedColor");
            incompatibleGameStartedColor = ChromeMetrics.Get <Color>("IncompatibleGameStartedColor");

            serverList     = widget.Get <ScrollPanelWidget>("SERVER_LIST");
            headerTemplate = serverList.Get <ScrollItemWidget>("HEADER_TEMPLATE");
            serverTemplate = serverList.Get <ScrollItemWidget>("SERVER_TEMPLATE");

            noticeContainer = widget.GetOrNull("NOTICE_CONTAINER");
            if (noticeContainer != null)
            {
                noticeContainer.IsVisible = () => showNotices;
                noticeContainer.Get("OUTDATED_VERSION_LABEL").IsVisible   = () => services.ModVersionStatus == ModVersionStatus.Outdated;
                noticeContainer.Get("UNKNOWN_VERSION_LABEL").IsVisible    = () => services.ModVersionStatus == ModVersionStatus.Unknown;
                noticeContainer.Get("PLAYTEST_AVAILABLE_LABEL").IsVisible = () => services.ModVersionStatus == ModVersionStatus.PlaytestAvailable;
            }

            var noticeWatcher = widget.Get <LogicTickerWidget>("NOTICE_WATCHER");

            if (noticeWatcher != null && noticeContainer != null)
            {
                var containerHeight = noticeContainer.Bounds.Height;
                noticeWatcher.OnTick = () =>
                {
                    var show = services.ModVersionStatus != ModVersionStatus.NotChecked && services.ModVersionStatus != ModVersionStatus.Latest;
                    if (show != showNotices)
                    {
                        var dir = show ? 1 : -1;
                        serverList.Bounds.Y      += dir * containerHeight;
                        serverList.Bounds.Height -= dir * containerHeight;
                        showNotices = show;
                    }
                };
            }

            joinButton = widget.GetOrNull <ButtonWidget>("JOIN_BUTTON");
            if (joinButton != null)
            {
                joinButton.IsVisible  = () => currentServer != null;
                joinButton.IsDisabled = () => !currentServer.IsJoinable;
                joinButton.OnClick    = () => onJoin(currentServer);
                joinButtonY           = joinButton.Bounds.Y;
            }

            // Display the progress label over the server list
            // The text is only visible when the list is empty
            var progressText = widget.Get <LabelWidget>("PROGRESS_LABEL");

            progressText.IsVisible = () => searchStatus != SearchStatus.Hidden;
            progressText.GetText   = ProgressLabelText;

            var gs = Game.Settings.Game;
            Action <MPGameFilters> toggleFilterFlag = f =>
            {
                gs.MPGameFilters ^= f;
                Game.Settings.Save();
                RefreshServerList();
            };

            var filtersButton = widget.GetOrNull <DropDownButtonWidget>("FILTERS_DROPDOWNBUTTON");

            if (filtersButton != null)
            {
                // HACK: MULTIPLAYER_FILTER_PANEL doesn't follow our normal procedure for dropdown creation
                // but we still need to be able to set the dropdown width based on the parent
                // The yaml should use PARENT_RIGHT instead of DROPDOWN_WIDTH
                var filtersPanel = Ui.LoadWidget("MULTIPLAYER_FILTER_PANEL", filtersButton, new WidgetArgs());
                filtersButton.Children.Remove(filtersPanel);

                var showWaitingCheckbox = filtersPanel.GetOrNull <CheckboxWidget>("WAITING_FOR_PLAYERS");
                if (showWaitingCheckbox != null)
                {
                    showWaitingCheckbox.IsChecked = () => gs.MPGameFilters.HasFlag(MPGameFilters.Waiting);
                    showWaitingCheckbox.OnClick   = () => toggleFilterFlag(MPGameFilters.Waiting);
                }

                var showEmptyCheckbox = filtersPanel.GetOrNull <CheckboxWidget>("EMPTY");
                if (showEmptyCheckbox != null)
                {
                    showEmptyCheckbox.IsChecked = () => gs.MPGameFilters.HasFlag(MPGameFilters.Empty);
                    showEmptyCheckbox.OnClick   = () => toggleFilterFlag(MPGameFilters.Empty);
                }

                var showAlreadyStartedCheckbox = filtersPanel.GetOrNull <CheckboxWidget>("ALREADY_STARTED");
                if (showAlreadyStartedCheckbox != null)
                {
                    showAlreadyStartedCheckbox.IsChecked = () => gs.MPGameFilters.HasFlag(MPGameFilters.Started);
                    showAlreadyStartedCheckbox.OnClick   = () => toggleFilterFlag(MPGameFilters.Started);
                }

                var showProtectedCheckbox = filtersPanel.GetOrNull <CheckboxWidget>("PASSWORD_PROTECTED");
                if (showProtectedCheckbox != null)
                {
                    showProtectedCheckbox.IsChecked = () => gs.MPGameFilters.HasFlag(MPGameFilters.Protected);
                    showProtectedCheckbox.OnClick   = () => toggleFilterFlag(MPGameFilters.Protected);
                }

                var showIncompatibleCheckbox = filtersPanel.GetOrNull <CheckboxWidget>("INCOMPATIBLE_VERSION");
                if (showIncompatibleCheckbox != null)
                {
                    showIncompatibleCheckbox.IsChecked = () => gs.MPGameFilters.HasFlag(MPGameFilters.Incompatible);
                    showIncompatibleCheckbox.OnClick   = () => toggleFilterFlag(MPGameFilters.Incompatible);
                }

                filtersButton.IsDisabled  = () => searchStatus == SearchStatus.Fetching;
                filtersButton.OnMouseDown = _ =>
                {
                    filtersButton.RemovePanel();
                    filtersButton.AttachPanel(filtersPanel);
                };
            }

            var reloadButton = widget.GetOrNull <ButtonWidget>("RELOAD_BUTTON");

            if (reloadButton != null)
            {
                reloadButton.IsDisabled = () => searchStatus == SearchStatus.Fetching;
                reloadButton.OnClick    = RefreshServerList;

                var reloadIcon = reloadButton.GetOrNull <ImageWidget>("IMAGE_RELOAD");
                if (reloadIcon != null)
                {
                    var disabledFrame = 0;
                    var disabledImage = "disabled-" + disabledFrame.ToString();
                    reloadIcon.GetImageName = () => searchStatus == SearchStatus.Fetching ? disabledImage : reloadIcon.ImageName;

                    var reloadTicker = reloadIcon.Get <LogicTickerWidget>("ANIMATION");
                    if (reloadTicker != null)
                    {
                        reloadTicker.OnTick = () =>
                        {
                            disabledFrame = searchStatus == SearchStatus.Fetching ? (disabledFrame + 1) % 12 : 0;
                            disabledImage = "disabled-" + disabledFrame.ToString();
                        };
                    }
                }
            }

            var playersLabel = widget.GetOrNull <LabelWidget>("PLAYER_COUNT");

            if (playersLabel != null)
            {
                var playersText = new CachedTransform <int, string>(c => c == 1 ? "1 Player Online" : c.ToString() + " Players Online");
                playersLabel.IsVisible = () => playerCount != 0;
                playersLabel.GetText   = () => playersText.Update(playerCount);
            }

            mapPreview = widget.GetOrNull <MapPreviewWidget>("SELECTED_MAP_PREVIEW");
            if (mapPreview != null)
            {
                mapPreview.Preview = () => currentMap;
            }

            var mapTitle = widget.GetOrNull <LabelWidget>("SELECTED_MAP");

            if (mapTitle != null)
            {
                var font  = Game.Renderer.Fonts[mapTitle.Font];
                var title = new CachedTransform <MapPreview, string>(m =>
                                                                     WidgetUtils.TruncateText(m.Title, mapTitle.Bounds.Width, font));

                mapTitle.GetText = () =>
                {
                    if (currentMap == null)
                    {
                        return("No Server Selected");
                    }

                    if (currentMap.Status == MapStatus.Searching)
                    {
                        return("Searching...");
                    }

                    if (currentMap.Class == MapClassification.Unknown)
                    {
                        return("Unknown Map");
                    }

                    return(title.Update(currentMap));
                };
            }

            var ip = widget.GetOrNull <LabelWidget>("SELECTED_IP");

            if (ip != null)
            {
                ip.IsVisible = () => currentServer != null;
                ip.GetText   = () => currentServer.Address;
            }

            var status = widget.GetOrNull <LabelWidget>("SELECTED_STATUS");

            if (status != null)
            {
                status.IsVisible = () => currentServer != null;
                status.GetText   = () => GetStateLabel(currentServer);
                status.GetColor  = () => GetStateColor(currentServer, status);
            }

            var modVersion = widget.GetOrNull <LabelWidget>("SELECTED_MOD_VERSION");

            if (modVersion != null)
            {
                modVersion.IsVisible = () => currentServer != null;
                modVersion.GetColor  = () => currentServer.IsCompatible ? modVersion.TextColor : incompatibleVersionColor;

                var font    = Game.Renderer.Fonts[modVersion.Font];
                var version = new CachedTransform <GameServer, string>(s => WidgetUtils.TruncateText(s.ModLabel, modVersion.Bounds.Width, font));
                modVersion.GetText = () => version.Update(currentServer);
            }

            var players = widget.GetOrNull <LabelWidget>("SELECTED_PLAYERS");

            if (players != null)
            {
                players.IsVisible = () => currentServer != null && (clientContainer == null || !currentServer.Clients.Any());
                players.GetText   = () => PlayersLabel(currentServer);
            }

            clientContainer = widget.GetOrNull("CLIENT_LIST_CONTAINER");
            if (clientContainer != null)
            {
                clientList           = Ui.LoadWidget("MULTIPLAYER_CLIENT_LIST", clientContainer, new WidgetArgs()) as ScrollPanelWidget;
                clientList.IsVisible = () => currentServer != null && currentServer.Clients.Any();
                clientHeader         = clientList.Get <ScrollItemWidget>("HEADER");
                clientTemplate       = clientList.Get <ScrollItemWidget>("TEMPLATE");
                clientList.RemoveChildren();
            }

            lanGameLocations = new List <BeaconLocation>();
            try
            {
                lanGameProbe = new Probe("OpenRALANGame");
                lanGameProbe.BeaconsUpdated += locations => lanGameLocations = locations;
                lanGameProbe.Start();
            }
            catch (Exception ex)
            {
                Log.Write("debug", "BeaconLib.Probe: " + ex.Message);
            }

            RefreshServerList();
        }
 private void PopulateRunners()
 {
     WebServices s = new WebServices();
       Cursor = Cursors.WaitCursor;
       runners.DataSource = FormattedRunner.ToFormattedRunners(s.GetRunnersAndSplits(((FormattedEvent)winSplitsEvents.SelectedItem).Event.DatabaseId, (short)categories.SelectedIndex));
       Cursor = Cursors.Default;
 }
Esempio n. 26
0
        public ReplayBrowserLogic(Widget widget, ModData modData, Action onExit, Action onStart)
        {
            map   = MapCache.UnknownMap;
            panel = widget;

            services              = modData.Manifest.Get <WebServices>();
            this.modData          = modData;
            this.onStart          = onStart;
            Game.BeforeGameStart += OnGameStart;

            playerList     = panel.Get <ScrollPanelWidget>("PLAYER_LIST");
            playerHeader   = playerList.Get <ScrollItemWidget>("HEADER");
            playerTemplate = playerList.Get <ScrollItemWidget>("TEMPLATE");
            playerList.RemoveChildren();

            panel.Get <ButtonWidget>("CANCEL_BUTTON").OnClick = () => { cancelLoadingReplays = true; Ui.CloseWindow(); onExit(); };

            replayList = panel.Get <ScrollPanelWidget>("REPLAY_LIST");
            var template = panel.Get <ScrollItemWidget>("REPLAY_TEMPLATE");

            var mod = modData.Manifest;
            var dir = Path.Combine(Platform.SupportDir, "Replays", mod.Id, mod.Metadata.Version);

            if (Directory.Exists(dir))
            {
                ThreadPool.QueueUserWorkItem(_ => LoadReplays(dir, template));
            }

            var watch = panel.Get <ButtonWidget>("WATCH_BUTTON");

            watch.IsDisabled = () => selectedReplay == null || map.Status != MapStatus.Available;
            watch.OnClick    = () => { WatchReplay(); };

            var mapPreviewRoot = panel.Get("MAP_PREVIEW_ROOT");

            mapPreviewRoot.IsVisible           = () => selectedReplay != null;
            panel.Get("REPLAY_INFO").IsVisible = () => selectedReplay != null;

            var spawnOccupants = new CachedTransform <ReplayMetadata, Dictionary <int, SpawnOccupant> >(r =>
            {
                // Avoid using .ToDictionary to improve robustness against replays defining duplicate spawn assignments
                var occupants = new Dictionary <int, SpawnOccupant>();
                foreach (var p in r.GameInfo.Players)
                {
                    if (p.SpawnPoint != 0)
                    {
                        occupants[p.SpawnPoint] = new SpawnOccupant(p);
                    }
                }

                return(occupants);
            });

            var noSpawns            = new HashSet <int>();
            var disabledSpawnPoints = new CachedTransform <ReplayMetadata, HashSet <int> >(r => r.GameInfo.DisabledSpawnPoints ?? noSpawns);

            Ui.LoadWidget("MAP_PREVIEW", mapPreviewRoot, new WidgetArgs
            {
                { "orderManager", null },
                { "getMap", (Func <MapPreview>)(() => map) },
                { "onMouseDown", (Action <MapPreviewWidget, MapPreview, MouseInput>)((preview, mapPreview, mi) => { }) },
                { "getSpawnOccupants", (Func <Dictionary <int, SpawnOccupant> >)(() => spawnOccupants.Update(selectedReplay)) },
                { "getDisabledSpawnPoints", (Func <HashSet <int> >)(() => disabledSpawnPoints.Update(selectedReplay)) },
                { "showUnoccupiedSpawnpoints", false },
            });

            var replayDuration = new CachedTransform <ReplayMetadata, string>(r =>
                                                                              "Duration: {0}".F(WidgetUtils.FormatTimeSeconds((int)selectedReplay.GameInfo.Duration.TotalSeconds)));

            panel.Get <LabelWidget>("DURATION").GetText = () => replayDuration.Update(selectedReplay);

            SetupFilters();
            SetupManagement();
        }
Esempio n. 27
0
        // GET: /Builds/monoextended
        public ActionResult MonoExtended()
        {
            int[] trunk_dist_rows = new int[] { 14, 110, 111, 128, 129 };
            int[] trunk_rows = new int[] { 34, 35, 36, 37, 31, 41, 84 };
            int[] trunk_rpm_rows = new int[] { 39 };
            int[] trunk_40_rows = new int[] { 58 };
            int[] trunk_minimal_rows = new int[] { 38 };
            int[] mono_26_rows = new int[] { 75, 99, 98, 100, 116, 163, 164, 122, 125, 126 };
            int[] mono_26_rpm_rows = new int[] { 112 };
            int[] mono_243_rows = new int[] { 102, 94, 101, 96, 123, 119, 120, 97, 115, 124, 127 };

            WebServices ws = new WebServices ();
            WebServiceLogin login = new WebServiceLogin ();

            FrontPageResponse data = ws.GetFrontPageData2 (login, 10, null, null);

            List<StatusStrip> strips = new List<StatusStrip> ();

            StatusStrip strip_trunk_dist = new StatusStrip ("Mono - Trunk - Dist");
            AddRowsToStrip (strip_trunk_dist, null, trunk_dist_rows, data);

            StatusStrip strip_trunk = new StatusStrip ("Mono - Trunk");
            AddRowsToStrip (strip_trunk, null, trunk_rows, data);

            StatusStrip strip_rpm = new StatusStrip ("Mono - Trunk - rpm");
            AddRowsToStrip (strip_rpm, null, trunk_rpm_rows, data);

            StatusStrip strip_40 = new StatusStrip ("Mono - Trunk - 4.0");
            AddRowsToStrip (strip_40, null, trunk_40_rows, data);

            StatusStrip strip_trunk_min = new StatusStrip ("Mono - Trunk - Minimal");
            AddRowsToStrip (strip_trunk_min, null, trunk_minimal_rows, data);

            StatusStrip strip_26 = new StatusStrip ("Mono - 2.6");
            AddRowsToStrip (strip_26, null, mono_26_rows, data);

            StatusStrip strip_rpm_26 = new StatusStrip ("Mono - 2.6 - rpm");
            AddRowsToStrip (strip_rpm_26, null, mono_26_rpm_rows, data);

            StatusStrip strip24 = new StatusStrip ("Mono - 2.4.3");
            AddRowsToStrip (strip24, null, mono_243_rows, data);

            strips.Add (strip_trunk_dist);
            strips.Add (strip_trunk);
            strips.Add (strip_rpm);
            strips.Add (strip_40);
            strips.Add (strip_26);
            strips.Add (strip_rpm_26);
            strips.Add (strip24);

            ViewData["PageTitle"] = "MonkeyWrench - Mono Extended Build Overview";

            return View ("Index", strips);
        }
Esempio n. 28
0
 public void PostGuest(Guest newGuest)
 {
     WebServices.PostGuestAsync(newGuest);
     Guests.Add(newGuest);
 }
Esempio n. 29
0
 protected virtual void ExecuteWebRequest(WebService service, out ErrorResultTO errors)
 {
     WebServices.ExecuteRequest(service, true, out errors);
 }
Esempio n. 30
0
        async void ButtonClickedEvent(object sender, System.EventArgs e)
        {
            try
            {
                //var _url = "https://www.pexels.com/search/beauty/";
                var _url        = "https://www.pexels.com/search/";
                var _methodName = "beauty";
                var url         = (!string.IsNullOrEmpty(entryURL.Text)) ? entryURL.Text : _url;
                using (IWebServices webServices = new WebServices())
                {
                    var response = await webServices.GetHTMLFromURL(_url, _methodName);

                    serviceResponse = response.ToString();
                }
                //labelJSONStringData.Text = serviceResponse;
                var tree = serviceResponse.Split('>');
                //List<StringList> stringLists = new List<StringList>();
                //var stree = "{\"data\":[{\"Name\":\"\" },{\"Name\":\"\" }]}";
                var stree = "{\"data\":[";//{\"Name\":\"\" },{\"Name\":\"\" }]}
                foreach (var item in tree)
                {
                    if (item.ToLower().Contains("img") || item.ToLower().Contains("image"))
                    {
                        if (item.Contains("src"))
                        {
                            var _item = (item.Contains("\"")) ? item.Replace("\"", "\\\"") : item;
                            _item  = (_item.Contains("\n")) ? _item.Replace("\n", "") : _item;
                            stree += "{\"Name\":\"" + _item + ">\" },";
                            //stringLists.Add()
                            //obtData.Add(item, HTMLAttributes(item)["src"]);
                        }
                    }
                }
                stree  = stree.Remove(stree.Length - 1);
                stree += "]}";

                var           jsonString    = Newtonsoft.Json.JsonConvert.DeserializeObject <HTMLSet>(stree);
                List <string> imagesURLList = new List <string>();
                foreach (var item in jsonString.data)
                {
                    var attrs = HTMLAttributes(item.Name);
                    foreach (var attr in attrs)
                    {
                        if (attr.Key == "src")
                        {
                            imagesURLList.Add(attr.Value);
                            try
                            {
                                Image image = new Image();
                                image.Source = ImageSource.FromUri(new Uri(attr.Value));

                                //galleryImageItem.Image_Source = ImageSource.FromStream(() =>
                                //{
                                //    return new System.IO.MemoryStream(Convert.FromBase64String(imageItem.File));
                                //});
                                //galleryImageItem.ImageStream = new System.IO.MemoryStream(Convert.FromBase64String(imageItem.File));
                                //using(var stream = new System.IO.MemoryStream(Convert.FromBase64String(imageItem.File)))
                                //{
                                //    galleryImageItem.ImageStream = stream;
                                //}

                                stackImageHolder.Children.Add(image);
                            }
                            catch (Exception ex)
                            {
                                var msg = ex.Message + "\n" + ex.StackTrace;
                                System.Diagnostics.Debug.WriteLine(msg);
                            }
                        }
                    }
                }
                System.Diagnostics.Debug.WriteLine(stree);
                //var ress = HTMLAttributes(serviceResponse)["src"];
            }
            catch (Exception ex)
            {
                var msg = ex.Message + "\n" + ex.StackTrace;
                System.Diagnostics.Debug.WriteLine(msg);
            }
        }
Esempio n. 31
0
 public AirportModel(WebServices.Airport a)
 {
     this.Code = a.airport_code;
     this.Location = a.airport_location;
     this.Country = a.airport_country;
 }
Esempio n. 32
0
        private static int Main2(string [] arguments)
        {
            Lock process_lock;
            ReportBuildBotStatusResponse status_response;
            BuildBotStatus status;

            try {
                if (!Configuration.LoadConfiguration(arguments))
                {
                    Logger.Log("Could not load configuration.");
                    return(1);
                }

                if (!Configuration.VerifyBuildBotConfiguration())
                {
                    Logger.Log("Configuration verification failed.");
                    return(1);
                }

                process_lock = Lock.Create("MonkeyWrench.Builder");
                if (process_lock == null)
                {
                    Logger.Log("Builder could not acquire lock. Exiting");
                    return(1);
                }
                Logger.Log("Builder lock aquired successfully.");
            } catch (Exception ex) {
                Logger.Log("Could not aquire lock: {0}", ex.Message);
                return(1);
            }

            try {
                WebService = WebServices.Create();
                WebService.CreateLogin(Configuration.Host, Configuration.WebServicePassword);

                status      = new BuildBotStatus();
                status.Host = Configuration.Host;
                status.FillInAssemblyAttributes();
                status_response = WebService.ReportBuildBotStatus(WebService.WebServiceLogin, status);
                if (status_response.Exception != null)
                {
                    Logger.Log("Failed to report status: {0}", status_response.Exception.Message);
                    return(1);
                }

                if (!string.IsNullOrEmpty(status_response.ConfiguredVersion) && status_response.ConfiguredVersion != status.AssemblyVersion)
                {
                    if (!Update(status, status_response))
                    {
                        Console.Error.WriteLine("Automatic update to: {0} / {1} failed (see log for details). Please update manually.", status_response.ConfiguredVersion, status_response.ConfiguredRevision);
                        return(2);                        /* Magic return code that means "automatic update failed" */
                    }
                    else
                    {
                        Console.WriteLine("The builder has been updated. Please run 'make build' again.");
                        return(1);
                    }
                }

                response = WebService.GetBuildInfoMultiple(WebService.WebServiceLogin, Configuration.Host, true);

                if (!response.Host.enabled)
                {
                    Logger.Log("This host is disabled. Exiting.");
                    return(0);
                }

                Logger.Log("Builder will now build {0} lists of work items.", response.Work.Count);

                for (int i = 0; i < response.Work.Count; i++)
                {
                    //foreach (var item in response.Work)
                    Logger.Log("Building list #{0}/{1}", i + 1, response.Work.Count);
                    Build(response.Work [i]);                     //item);
                }

                Logger.Log("Builder finished successfully.");

                return(0);
            } catch (Exception ex) {
                Logger.Log("An exception occurred: {0}", ex.ToString());
                return(1);
            } finally {
                process_lock.Unlock();
            }
        }
Esempio n. 33
0
 public SoapCreator(WebServices webserv)
 {
     this.WebService = webserv;
 }
Esempio n. 34
0
    public async Task CommunicationTest()
    {
        await using var serving = await WebHost.Serve();

        var publisher = WebServices.GetRequiredService <IPublisher>();

        using var wss = WebServices.CreateScope();
        var sp = wss.ServiceProvider.GetRequiredService <ISimplestProvider>();

        var cp = CreateChannelPair("c1");

        publisher.ChannelHub.Attach(cp.Channel1).Should().BeTrue();
        var cReader = cp.Channel2.Reader;

        sp.SetValue("");

        var p1 = await publisher.Publish(_ => sp.GetValue());

        p1.Should().NotBeNull();

        Debug.WriteLine("a1");
        await publisher.Subscribe(cp.Channel1, p1, true);

        Debug.WriteLine("a2");
        var m = await cReader.AssertRead();

        m.Should().BeOfType <PublicationStateReply <string, string> >()
        .Which.Output !.Value.Value.Should().Be("");
        Debug.WriteLine("a3");
        await cReader.AssertCannotRead();

        Debug.WriteLine("b1");
        sp.SetValue("1");
        Debug.WriteLine("b2");
        m = await cReader.AssertRead();

        Debug.WriteLine("b3");
        m.Should().BeOfType <PublicationStateReply <string> >()
        .Which.IsConsistent.Should().BeFalse();
        Debug.WriteLine("b4");
        var pm = (PublicationReply)m;

        pm.PublisherId.Should().Be(publisher.Id);
        pm.PublicationId.Should().Be(p1.Id);
        Debug.WriteLine("b5");
        await cReader.AssertCannotRead();

        Debug.WriteLine("c1");
        sp.SetValue("12");
        // No auto-update after invalidation
        Debug.WriteLine("c2");
        await cReader.AssertCannotRead();

        Debug.WriteLine("d1");
        await publisher.Subscribe(cp.Channel1, p1, true);

        Debug.WriteLine("d2");
        m = await cReader.AssertRead();

        Debug.WriteLine("d3");
        m.Should().BeOfType <PublicationStateReply <string, string> >()
        .Which.IsConsistent.Should().BeTrue();
        m.Should().BeOfType <PublicationStateReply <string, string> >()
        .Which.Output !.Value.Value.Should().Be("12");
        Debug.WriteLine("d4");
        await cReader.AssertCannotRead();

        Debug.WriteLine("e1");
        await p1.DisposeAsync();

        Debug.WriteLine("e2");
        await cReader.AssertCannotRead();

        Debug.WriteLine("f1");
        await publisher.Subscribe(cp.Channel1, p1, true);

        Debug.WriteLine("f2");
        m = await cReader.AssertRead();

        Debug.WriteLine("f3");
        m.Should().BeOfType <PublicationAbsentsReply>();
    }
Esempio n. 35
0
 public void Create(WebServices webserv)
 {
     this.WebService = webserv;
     this.Create();
 }
Esempio n. 36
0
    protected void Page_Load(object sender, EventArgs e)
    {
        string ip          = Request.UserHostAddress;
        bool   ip_accepted = false;
        string payload;

        log.InfoFormat("Received GitHub post with {2} files from: {0} allowed ips: {1}", ip, Configuration.AllowedCommitReporterIPs, Request.Files.Count);

        if (log.IsDebugEnabled)
        {
            foreach (HttpPostedFile f in Request.Files)
            {
                log.DebugFormat("ReportGitHubCommit.aspx: got file: {0}", f.FileName);
            }
            foreach (string f in Request.Form.AllKeys)
            {
                log.DebugFormat("ReportGitHubCommit.aspx: {0}={1}", f, Request.Form [f]);
            }
        }

        foreach (string allowed_ip in Configuration.AllowedCommitReporterIPs.Split('.'))
        {
            if (string.IsNullOrEmpty(ip))
            {
                continue;
            }
            if (Regex.IsMatch(ip, FileUtilities.GlobToRegExp(allowed_ip)))
            {
                ip_accepted = true;
                break;
            }
        }

        if (!ip_accepted)
        {
            log.WarnFormat("{0} tried to send a file, ignored. Allowed IPs: {1}", ip, Configuration.AllowedCommitReporterIPs);
            Response.StatusCode = 403;
            return;
        }

        payload = Request ["payload"];

        if (!string.IsNullOrEmpty(payload))
        {
            string outdir  = Configuration.GetSchedulerCommitsDirectory();
            string outfile = Path.Combine(outdir, string.Format("commit-{0}.xml", DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss")));

            if (!Directory.Exists(outdir))
            {
                Directory.CreateDirectory(outdir);
            }

            log.InfoFormat("Got 'payload' from {2} with size {0} bytes, writing to '{1}'", payload.Length, outfile, ip);

            JavaScriptSerializer json = new JavaScriptSerializer();
            GitHub.Payload       pl   = json.Deserialize <GitHub.Payload> (payload);

            if (pl.commits == null)
            {
                log.InfoFormat("Payload did not contain any commits.");
                Response.StatusCode = 204;
                return;
            }

            XmlWriterSettings settings = new XmlWriterSettings();
            settings.CloseOutput = true;
            settings.Indent      = true;
            settings.IndentChars = "\t";
            XmlWriter writer = XmlWriter.Create(outfile, settings);

            /*
             # <monkeywrench version="1">
             #   <changeset sourcecountrol="svn|git" root="<repository root>" revision="<revision>">
             #     <directories>
             #        <directory>/dir1</directory>
             #        <directory>/dir2</directory>
             #     </directories>
             #   </changeset>
             # </monkeywrench>
             * */
            writer.WriteStartElement("monkeywrench");
            writer.WriteAttributeString("version", "1");
            foreach (GitHub.Commit commit in pl.commits)
            {
                writer.WriteStartElement("changeset");
                writer.WriteAttributeString("sourcecontrol", "git");
                writer.WriteAttributeString("root", pl.repository.url);
                writer.WriteAttributeString("revision", commit.id);
                writer.WriteStartElement("directories");
                HashSet <string> dirs = new HashSet <string> ();
                foreach (string f in commit.added)
                {
                    dirs.Add(Path.GetDirectoryName(f));
                }
                foreach (string f in commit.modified)
                {
                    dirs.Add(Path.GetDirectoryName(f));
                }
                foreach (string f in commit.removed)
                {
                    dirs.Add(Path.GetDirectoryName(f));
                }
                foreach (string dir in dirs)
                {
                    writer.WriteElementString("directory", dir);
                }
                writer.WriteEndElement();
                writer.WriteEndElement();
            }
            writer.WriteEndElement();
            writer.Close();
        }
        else
        {
            log.Warn("Didn't get a file called 'payload'");
        }

        Response.StatusCode = 204;
        WebServices.ExecuteSchedulerAsync();
    }
Esempio n. 37
0
 public Car_Park()
 {
     base.Credentials = WebServices.GetCredentials();
 }
Esempio n. 38
0
 public static string CreateWebServiceDownloadUrl(HttpRequest Request, int work_id, string filename, bool redirect)
 {
     return(WebServices.CreateWebServiceDownloadNamedUrl(work_id, filename, CreateWebServiceLogin(Request), redirect));
 }
Esempio n. 39
0
 public NewsRepository()
 {
     _webServices = new WebServices();
 }
Esempio n. 40
0
        public async Task <int> Webapi()
        {
            try
            {
                string grant_type = Grant_type;
                string username   = _email;
                string password   = _password;
                await PopupNavigation.Instance.PushAsync(new CustomLoader());

                WebServices service = new WebServices();

                var response = await service.LoginApi(grant_type, username, password);

                if (Convert.ToInt16(response.StatusCode) == 200)
                {
                    string loginBody = string.Empty;
                    loginBody = await response.Content.ReadAsStringAsync();

                    DataContractJsonSerializer ser1 = new DataContractJsonSerializer(typeof(LoginResponseModel));
                    MemoryStream stream1            = new MemoryStream(Encoding.UTF8.GetBytes(loginBody));
                    var          log = (LoginResponseModel)ser1.ReadObject(stream1);
                    App.accesstoken = log.access_token;
                    App.expiresTime = log.expires;
                    App.IssuedTime  = log.issued;
                    App.username    = log.userName;
                    App.tokentype   = log.token_type;
                    await PopupNavigation.Instance.PopAllAsync();

                    await PopupNavigation.Instance.PushAsync(new LoadingData());

                    var responses = await service.GetUser();

                    if (Convert.ToInt16(response.StatusCode) == 200)
                    {
                        App.NameCoome = responses.NomeCognome;
                        App.Email     = responses.Email;
                        App.Name      = responses.Nome;
                        App.COName    = responses.Cognome;
                    }

                    App.contactResponse = await service.ContactDetail();

                    App.companyResponse = await service.Company();

                    App.AppointmentResponse = await service.GetAppoint();



                    if (Device.RuntimePlatform == Device.Android)
                    {
                        Application.Current.MainPage = new MainPage();
                    }
                    else if (Device.RuntimePlatform == Device.iOS)
                    {
                        await Application.Current.MainPage.Navigation.PushModalAsync(new MainPage());
                    }

                    //IsOpens = true;
                    // Application.Current.MainPage = new MainPage();

                    await PopupNavigation.Instance.PopAllAsync();

                    return(1);
                }
                else
                {
                    await App.Current.MainPage.DisplayAlert("Error", "Invalid Username or Password", "OK");

                    return(0);
                }
            }
            catch (Exception e)
            {
                throw e;
            }
        }
Esempio n. 41
0
 public LoginViewModel()
 {
     OnLogin    = new Command(async() => await Login());
     OnRegistar = new Command(Registar);
     webService = new WebServices();
 }
Esempio n. 42
0
 public EspecialistasRepository()
 {
     _webServices = new WebServices();
 }
Esempio n. 43
0
        internal LobbyLogic(Widget widget, ModData modData, WorldRenderer worldRenderer, OrderManager orderManager, Action onExit, Action onStart, bool skirmishMode)
        {
            map               = MapCache.UnknownMap;
            lobby             = widget;
            this.modData      = modData;
            this.orderManager = orderManager;
            this.onStart      = onStart;
            this.onExit       = onExit;
            this.skirmishMode = skirmishMode;


            services = modData.Manifest.Get <WebServices>();

            WarGame.LobbyInfoChanged       += UpdateCurrentMap;
            WarGame.LobbyInfoChanged       += UpdatePlayerList;
            WarGame.BeforeGameStart        += OnGameStart;
            WarGame.ConnectionStateChanged += ConnectionStateChanged;


            UpdateCurrentMap();

            var gameStarting = false;


            var mapButton = lobby.GetOrNull <ButtonWidget>("CHANGEMAP_BUTTON");

            if (mapButton != null)
            {
                mapButton.OnClick = () =>
                {
                    var onSelect = new Action <string>(uid =>
                    {
                        //Don't select the same map again
                        if (uid == map.Uid)
                        {
                            return;
                        }

                        orderManager.IssueOrder(Order.Command("map " + uid));
                        WarGame.Settings.Server.Map = uid;
                    });

                    UI.OpenWindow("MAPCHOOSER_PANEL", new WidgetArgs()
                    {
                        { "initialMap", map.Uid },
                        { "initialTab", MapClassification.System },
                        { "onExit", DoNothing },
                        { "onSelect", WarGame.IsHost ? onSelect : null },
                        { "filter", MapVisibility.Lobby },
                    });
                };
            }
            Action startGame = () =>
            {
                gameStarting = true;
                orderManager.IssueOrder(Order.Command("startgame"));
            };

            var startGameButton = lobby.GetOrNull <ButtonWidget>("START_GAME_BUTTON");

            if (startGameButton != null)
            {
                startGameButton.OnClick = () =>
                {
                    if (orderManager.LobbyInfo.Clients.Any(c => c.Slot != null && !c.IsAdmin && c.Bot == null && !c.IsReady))
                    {
                    }
                    else
                    {
                        startGame();
                    }
                };
            }

            var disconnectButton = lobby.Get <ButtonWidget>("DISCONNECT_BUTTON");

            disconnectButton.OnClick = () => { UI.CloseWindow(); onExit(); };

            if (skirmishMode)
            {
                disconnectButton.Text = "Back";
            }

            // Add a bot on the first lobbyinfo update
            if (skirmishMode)
            {
                addBotOnMapLoad = true;
            }
        }
        public async Task BasicTest1()
        {
            await using var serving = await WebHost.Serve();

            var authServer     = WebServices.GetRequiredService <IServerSideAuthService>();
            var authClient     = ClientServices.GetRequiredService <IAuthService>();
            var authLocal      = Services.GetRequiredService <IServerSideAuthService>();
            var sessionFactory = ClientServices.GetRequiredService <ISessionFactory>();
            var sessionA       = sessionFactory.CreateSession();
            var sessionB       = sessionFactory.CreateSession();
            var bob            = new User("", "Bob").WithIdentity("g:1");

            var session = sessionA;
            await WebServices.Commander().Call(
                new SignInCommand(session, bob).MarkServerSide());

            var user = await authServer.GetUser(session);

            user.Name.Should().Be(bob.Name);
            long.TryParse(user.Id, out var _).Should().BeTrue();
            user.Claims.Count.Should().Be(0);
            bob = user;

            // Trying to edit user name
            var newName = "Bobby";
            await authClient.EditUser(new(session, newName));

            user = await authServer.GetUser(session);

            user.Name.Should().Be(newName);
            bob = bob with {
                Name = newName
            };

            // Checking if the client is able to see the same user & sessions
            user = await authClient.GetUser(sessionA);

            user.Id.Should().Be(bob.Id);
            user.IsAuthenticated.Should().BeTrue();
            user = await authClient.GetUser(session);

            user.Id.Should().Be(bob.Id);
            user.IsAuthenticated.Should().BeTrue();

            // Checking if local service is able to see the same user & sessions
            if (!Options.UseInMemoryAuthService)
            {
                await Delay(0.5);

                user = await authLocal.GetUser(session);

                user.Id.Should().Be(bob.Id);
                user.IsAuthenticated.Should().BeTrue();
            }

            // Checking guest session
            session = sessionB;
            user    = await authClient.GetUser(session);

            user.IsAuthenticated.Should().BeFalse();

            // Checking sign-out
            await WebServices.Commander().Call(new SignOutCommand(sessionA));

            user = await authServer.GetUser(sessionA);

            user.IsAuthenticated.Should().BeFalse();
            await Delay(0.5);

            user = await authClient.GetUser(sessionA);

            user.IsAuthenticated.Should().BeFalse();
            if (!Options.UseInMemoryAuthService)
            {
                user = await authLocal.GetUser(sessionA);

                user.IsAuthenticated.Should().BeFalse();
            }
        }
Esempio n. 45
0
		private static int Main2 (string [] arguments)
		{
			Lock process_lock;
			ReportBuildBotStatusResponse status_response;
			BuildBotStatus status;

			try {
				if (!Configuration.LoadConfiguration (arguments))
					return 1;

				if (!Configuration.VerifyBuildBotConfiguration ())
					return 1;

				process_lock = Lock.Create ("MonkeyWrench.Builder");
				if (process_lock == null) {
					Logger.Log ("Builder could not acquire lock. Exiting");
					return 1;
				}
				Logger.Log ("Builder lock aquired successfully.");
			} catch (Exception ex) {
				Logger.Log ("Could not aquire lock: {0}", ex.Message);
				return 1;
			}

			try {
				WebService = WebServices.Create ();
				WebService.CreateLogin (Configuration.Host, Configuration.WebServicePassword);

				status = new BuildBotStatus ();
				status.Host = Configuration.Host;
				status.FillInAssemblyAttributes ();
				status_response = WebService.ReportBuildBotStatus (WebService.WebServiceLogin, status);
				if (status_response.Exception != null) {
					Logger.Log ("Failed to report status: {0}", status_response.Exception.Message);
					return 1;
				}

				if (!string.IsNullOrEmpty (status_response.ConfiguredVersion) && status_response.ConfiguredVersion != status.AssemblyVersion) {
					if (!Update (status, status_response)) {
						Console.Error.WriteLine ("Automatic update to: {0} / {1} failed (see log for details). Please update manually.", status_response.ConfiguredVersion, status_response.ConfiguredRevision);
						return 2; /* Magic return code that means "automatic update failed" */
					} else {
						Console.WriteLine ("The builder has been updated. Please run 'make build' again.");
						return 1;
					}
				}

				response = WebService.GetBuildInfoMultiple (WebService.WebServiceLogin, Configuration.Host, true);

				if (!response.Host.enabled) {
					Logger.Log ("This host is disabled. Exiting.");
					return 0;
				}

				Logger.Log ("Builder will now build {0} lists of work items.", response.Work.Count);

				for (int i = 0; i < response.Work.Count; i++) {
					//foreach (var item in response.Work)
					Logger.Log ("Building list #{0}/{1}", i+ 1, response.Work.Count);
					Build (response.Work [i]);//item);
				}

				Logger.Log ("Builder finished successfully.");

				return 0;
			} catch (Exception ex) {
				Logger.Log ("An exception occurred: {0}", ex.ToString ());
				return 1;
			} finally {
				process_lock.Unlock ();
			}
		}
Esempio n. 46
0
        public MultiplayerLogic(Widget widget, ModData modData, Action onStart, Action onExit, string directConnectHost, int directConnectPort)
        {
            this.modData = modData;
            this.onStart = onStart;
            this.onExit  = onExit;

            services = modData.Manifest.Get <WebServices>();

            incompatibleVersionColor       = ChromeMetrics.Get <Color>("IncompatibleVersionColor");
            incompatibleGameColor          = ChromeMetrics.Get <Color>("IncompatibleGameColor");
            incompatibleProtectedGameColor = ChromeMetrics.Get <Color>("IncompatibleProtectedGameColor");
            protectedGameColor             = ChromeMetrics.Get <Color>("ProtectedGameColor");
            waitingGameColor             = ChromeMetrics.Get <Color>("WaitingGameColor");
            incompatibleWaitingGameColor = ChromeMetrics.Get <Color>("IncompatibleWaitingGameColor");
            gameStartedColor             = ChromeMetrics.Get <Color>("GameStartedColor");
            incompatibleGameStartedColor = ChromeMetrics.Get <Color>("IncompatibleGameStartedColor");

            LoadBrowserPanel(widget);
            LoadDirectConnectPanel(widget);
            LoadCreateServerPanel(widget);

            // Filter and refresh buttons act on the browser panel,
            // but remain visible (disabled) on the other panels
            var refreshButton = widget.Get <ButtonWidget>("REFRESH_BUTTON");

            refreshButton.IsDisabled = () => searchStatus == SearchStatus.Fetching || panel != PanelType.Browser;

            var filtersButton = widget.Get <DropDownButtonWidget>("FILTERS_DROPDOWNBUTTON");

            filtersButton.IsDisabled = () => searchStatus == SearchStatus.Fetching || panel != PanelType.Browser;

            var browserTab = widget.Get <ButtonWidget>("BROWSER_TAB");

            browserTab.IsHighlighted = () => panel == PanelType.Browser;
            browserTab.OnClick       = () => panel = PanelType.Browser;

            var directConnectTab = widget.Get <ButtonWidget>("DIRECTCONNECT_TAB");

            directConnectTab.IsHighlighted = () => panel == PanelType.DirectConnect;
            directConnectTab.OnClick       = () => panel = PanelType.DirectConnect;

            var createServerTab = widget.Get <ButtonWidget>("CREATE_TAB");

            createServerTab.IsHighlighted = () => panel == PanelType.CreateServer;
            createServerTab.OnClick       = () => panel = PanelType.CreateServer;

            widget.Get <ButtonWidget>("BACK_BUTTON").OnClick = () => { Ui.CloseWindow(); onExit(); };

            lanGameLocations = new List <BeaconLocation>();
            try
            {
                lanGameProbe = new Probe("OpenRALANGame");
                lanGameProbe.BeaconsUpdated += locations => lanGameLocations = locations;
                lanGameProbe.Start();
            }
            catch (Exception ex)
            {
                Log.Write("debug", "BeaconLib.Probe: " + ex.Message);
            }

            RefreshServerList();

            if (directConnectHost != null)
            {
                // The connection window must be opened at the end of the tick for the widget hierarchy to
                // work out, but we also want to prevent the server browser from flashing visible for one tick.
                widget.Visible = false;
                Game.RunAfterTick(() =>
                {
                    ConnectionLogic.Connect(directConnectHost, directConnectPort, "", OpenLobby, DoNothing);
                    widget.Visible = true;
                });
            }
        }
Esempio n. 47
0
 // GET: Calendar
 public ActionResult Index()
 {
     ViewBag.No = WebServices.StudentNo(User.Identity.Name);
     return(View());
 }
Esempio n. 48
0
 public void SaveScreenAsync(int ReferenceId, string Url, RequestCompletedDelegate<CreateScreenResponse> callback)
 {
     WebServices<CreateScreenRequest, CreateScreenResponse> ws = new WebServices<CreateScreenRequest, CreateScreenResponse>();
     var request = new CreateScreenRequest() { ReferenceId = ReferenceId, Url = Url };
     ws.MakeRequestAsync(BaseURL + "/" + Urls.CreateScreen, request,callback);
 }
Esempio n. 49
0
 public ascx_HostLocalWebsite()
 {
     InitializeComponent();
     ascx_DropObject1.Text = "Drop Folder To Run";
     webservices           = new WebServices();
 }
Esempio n. 50
0
 public UsersRepository()
 {
     _webServices = new WebServices();
 }
Esempio n. 51
0
	int Run (String[] args) {
		if (!Configuration.LoadConfiguration (new string[0])) {
			Console.WriteLine ("Couldn't load configuration.");
			return 1;
		}
		ws = WebServices.Create ();
		ws.CreateLogin (Configuration.Host, Configuration.WebServicePassword);
		login = ws.WebServiceLogin;
		ws.Login (login);

		string command = args.Length > 0 ? args [0] : "";
		if (command == "lane-config") {
			// Requires admin rights (because it uses GetLaneForEdit)
			if (args.Length < 2) {
				Console.WriteLine ("Usage: lane-config <lane name>");
				return 1;
			}
			string lane_name = args [1];
			var lane = FindLaneByName (lane_name);
			if (lane == null)
				return 1;
			Console.WriteLine ("Lane: " + lane.lane);
			if (lane.parent_lane_id != null) {
				var parent_lane = ws.FindLane (login, lane.parent_lane_id, null).lane;
				if (parent_lane != null)
					Console.WriteLine ("Parent: " + parent_lane.lane);
			}
			Console.WriteLine ("Source control: " + lane.source_control);
			Console.WriteLine ("Repository: " + lane.repository);
			Console.WriteLine ("Mini/Max revision: " + lane.min_revision + "/" + (lane.max_revision != "" ? lane.max_revision : "<none>"));

			var res = ws.GetLaneForEdit (login, lane.id, null);
			foreach (var c in res.Commands) {
				Console.WriteLine ("\t " + c.sequence + " " + c.command + " (" + c.filename + " " + c.arguments + ")");
			}
			Console.WriteLine ("Files:");
			foreach (var f in res.Files) {
				Console.WriteLine ("\t" + f.name);
			}
			Console.WriteLine ("Hosts:");
			foreach (var h in res.HostLaneViews) {
				Console.WriteLine ("\t" + h.host);
			}
		} else if (command == "show-step") {
			// Requires admin rights
			if (args.Length < 3) {
				Console.WriteLine ("Usage: show-step <lane> <step name>");
				return 1;
			}
			string lane_name = args [1];
			string cmd_name = args [2];
			var lane = FindLaneByName (lane_name);
			if (lane == null)
				return 1;
			var cmd = FindCmdByName (lane, cmd_name);
			if (cmd == null)
				return 1;
			PrintCmd (cmd);
		} else if (command == "add-step") {
			if (args.Length < 3) {
				Console.WriteLine ("Usage: add-step <lane> <step name>");
				return 1;
			}
			string lane_name = args [1];
			string cmd_name = args [2];
			var lane = FindLaneByName (lane_name);
			if (lane == null)
				return 1;
			if (!CheckCmdExists (lane, cmd_name))
				return 1;
			bool always = true;
			bool nonfatal = true;
			int timeout = 5;
			// FIXME: AddCommand () ignores this
			int seq = 0;
			ws.AddCommand (login, lane.id, cmd_name, always, nonfatal, timeout, seq);
		} else if (command == "edit-step") {
			if (args.Length < 3) {
				Console.WriteLine ("Usage: edit-step <lane> <step name> [<edit options>]");
				return 1;
			}
			string lane_name = args [1];
			string cmd_name = args [2];
			var lane = FindLaneByName (lane_name);
			if (lane == null)
				return 1;
			var cmd = FindCmdByName (lane, cmd_name);
			if (cmd == null)
				return 1;

			int? seq = null;
			int? timeout = null;
			bool nonfatal = cmd.nonfatal;
			bool alwaysexecute = cmd.alwaysexecute;
			string filename = null;
			string arguments = null;
			string upload_files = null;
			OptionSet p = new OptionSet ()
				.Add ("seq=", v => seq = Int32.Parse (v))
				.Add ("timeout=", v => timeout = Int32.Parse (v))
				.Add ("nonfatal=", v => nonfatal = Boolean.Parse (v))
				.Add ("alwaysexecute=", v => alwaysexecute = Boolean.Parse (v))
				.Add ("filename=", v => filename = v)
				.Add ("arguments=", v => arguments = v)
				.Add ("upload-files=", v => upload_files = v);
			var new_args = p.Parse (args.Skip (3).ToArray ());
			if (new_args.Count > 0) {
				Console.WriteLine ("Unknown arguments: " + String.Join (" ", new_args.ToArray ()));
				return 1;
			}

			PrintCmd (cmd);

			if (seq != null)
				ws.EditCommandSequence (login, cmd.id, (int)seq);
			if (filename != null)
				ws.EditCommandFilename (login, cmd.id, filename);
			if (arguments != null)
				ws.EditCommandArguments (login, cmd.id, arguments);
			if (upload_files != null)
				ws.EditCommandUploadFiles (login, cmd.id, upload_files);
			if (timeout != null)
				ws.EditCommandTimeout (login, cmd.id, (int)timeout);
			if (alwaysexecute != cmd.alwaysexecute)
				ws.SwitchCommandAlwaysExecute (login, cmd.id);
			if (nonfatal != cmd.nonfatal)
				ws.SwitchCommandNonFatal (login, cmd.id);

			cmd = FindCmdByName (lane, cmd_name);
			if (cmd == null)
				return 1;
			Console.WriteLine ("=>");
			PrintCmd (cmd);
		} else if (command == "add-lane-file") {
			if (args.Length < 3) {
				Console.WriteLine ("Usage: add-lane-file <lane> <lane file name>");
				return 1;
			}
			string lane_name = args [1];
			string lane_file_name = args [2];
			var lane = FindLaneByName (lane_name);
			if (lane == null)
				return 1;
			var res = ws.GetLaneForEdit (login, lane.id, null);
			var file = (from f in res.Files where f.name == lane_file_name select f).FirstOrDefault ();
			if (file != null) {
				Console.WriteLine ("A file named '" + lane_file_name + "' already exists in lane '" + lane.lane + "'.");
				return 1;
			}
			ws.CreateLanefile (login, lane.id, lane_file_name);
		} else if (command == "edit-lane-file") {
			if (args.Length < 4) {
				Console.WriteLine ("Usage: edit-lane-file <lane> <lane file name> <filename>");
				return 1;
			}
			string lane_name = args [1];
			string lane_file_name = args [2];
			string filename = args [3];
			var lane = FindLaneByName (lane_name);
			if (lane == null)
				return 1;

			var res = ws.GetLaneForEdit (login, lane.id, null);
			var file = (from f in res.Files where f.name == lane_file_name select f).FirstOrDefault ();
			if (file == null) {
				Console.WriteLine ("No file named '" + lane_file_name + "' in lane '" + lane.lane + "'.");
				return 1;
			}

			file.contents = File.ReadAllText (filename);
			ws.EditLaneFile (login, file);
		} else if (command == "lanes") {
			var res = ws.GetLanes (login);
			foreach (var l in res.Lanes)
				Console.WriteLine (l.lane);
		} else if (command == "lane-tree") {
			var res = ws.GetLanes (login);
			var tree = new Dictionary<DBLane, List<DBLane>> ();
			foreach (var l in res.Lanes) {
				tree [l] = new List<DBLane> ();
			}
			foreach (var l in res.Lanes) {
				if (l.parent_lane_id != null) {
					var parent_lane = (from l2 in res.Lanes where l2.id == l.parent_lane_id select l2).First ();
					tree [parent_lane].Add (l);
				}
			}
			foreach (var l in tree.Keys) {
				if (l.parent_lane_id == null)
					PrintLaneTree (tree, l, 0);
			}
		} else if (command == "rev") {
			if (args.Length < 4) {
				Console.WriteLine ("Usage: rev <lane> <host> <revision>");
				return 1;
			}
			string lane_name = args [1];
			string host_name = args [2];
			string rev_name = args [3];

			var lane = ws.FindLane (login, null, lane_name).lane;
			if (lane == null) {
				Console.WriteLine ("Lane '" + lane_name + "' not found.");
				return 1;
			}
			var host = ws.FindHost (login, null, host_name).Host;
			var res = ws.FindRevisionForLane (login, null, rev_name, lane.id, null);
			var rev = res.Revision;
			if (res.Revision == null) {
				Console.WriteLine ("Revision '" + rev_name + "' not found.");
				return 1;
			}
			var res2 = ws.GetViewLaneData (login, lane.id, null, host.id, null, rev.id, null);
			Console.WriteLine ("" + rev.revision + " " + rev.author + " " + (DBState)res2.RevisionWork.state);
			int vindex = 0;
			foreach (var view in res2.WorkViews) {
				Console.WriteLine ("\t " + view.command + " " + (DBState)view.state);
				foreach (var fview in res2.WorkFileViews [vindex]) {
					if (fview.work_id == view.id)
						Console.WriteLine ("\t\t" + fview.filename);
				}
				vindex ++;
			}
		} else if (command == "lane") {
			if (args.Length < 3) {
				Console.WriteLine ("Usage: lane <lane> <host>");
				return 1;
			}				

			string lane_name = args [1];
			string host_name = args [2];

			int limit = 10;
			OptionSet p = new OptionSet ()
				.Add ("limit=", v => limit = Int32.Parse (v));
			p.Parse (args.Skip (3).ToArray ());

			var lane = ws.FindLane (login, null, lane_name).lane;
			if (lane == null) {
				Console.WriteLine ("Lane '" + lane_name + "' not found.");
				return 1;
			}
			//var cmds = ws.GetCommands (login, lane.id);
			//var cmd = (from c in cmds.Commands where c.command == "package" select c).First ();
			var hosts = ws.GetHosts (login);
			var host = (from h in hosts.Hosts where h.host == host_name select h).FirstOrDefault ();
			if (host == null) {
				Console.WriteLine ("Host '" + host_name + "' not found.");
				return 1;
			}
			var revs = ws.GetRevisions (login, null, lane.lane, limit, 0);
			foreach (var rev in revs.Revisions) {
				var watch = new Stopwatch ();
				watch.Start ();
				var res3 = ws.GetViewLaneData (login, lane.id, null, host.id, null, rev.id, null);
				watch.Stop ();
				if (res3.RevisionWork == null) {
					Console.WriteLine ("Host/lane pair not found.");
					return 1;
				}
				DBState state = (DBState)res3.RevisionWork.state;
				string extra = "";
				if (state == DBState.Executing || state == DBState.Issues) {
					int nsteps = 0;
					int ndone = 0;
					string step = "";
					foreach (var view in res3.WorkViews) {
						nsteps ++;
						DBState viewstate = (DBState)view.state;
						if (viewstate != DBState.NotDone && viewstate != DBState.Executing)
							ndone ++;
						if (viewstate == DBState.Executing)
							step = view.command;
					}
					extra = " (" + nsteps + "/" + ndone + (step != "" ? " " + step : "") + ")";
				}
				if (state == DBState.Issues || state == DBState.Failed) {
					string failed = "";
					foreach (var view in res3.WorkViews) {
						if ((DBState)view.state == DBState.Failed) {
							if (failed != "")
								failed += " ";
							failed += view.command;
						}
					}
					if (failed != "")
						extra += " (" + failed + ")";
				}
				Console.WriteLine ("" + rev.revision + " " + rev.author + " " + state + extra);
			}
		} else if (command == "help") {
			PrintUsage ();
		} else {
			PrintUsage ();
			return 1;
		}
		ws.Logout (login);
		return 0;
	}