Example #1
0
        private static bool PostAction(Proxy p, Server server, Action action)
        {
            var instance = p.Instance;
            // if we can't issue any commands, bomb out
            if (instance.AdminUser.IsNullOrEmpty() || instance.AdminPassword.IsNullOrEmpty()) return false;

            var loginInfo = $"{instance.AdminUser}:{instance.AdminPassword}";
            var haproxyUri = new Uri(instance.Url);
            var requestBody = $"s={server.Name}&action={action.ToString().ToLower()}&b={p.Name}";
            var requestHeader = $"POST {haproxyUri.AbsolutePath} HTTP/1.1\r\nHost: {haproxyUri.Host}\r\nContent-Length: {Encoding.GetEncoding("ISO-8859-1").GetBytes(requestBody).Length}\r\nAuthorization: Basic {Convert.ToBase64String(Encoding.Default.GetBytes(loginInfo))}\r\n\r\n";

            try
            {
                var socket = new System.Net.Sockets.Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                socket.Connect(haproxyUri.Host, haproxyUri.Port);
                socket.Send(Encoding.UTF8.GetBytes(requestHeader + requestBody));

                var responseBytes = new byte[socket.ReceiveBufferSize];
                socket.Receive(responseBytes);

                var response = Encoding.UTF8.GetString(responseBytes);
                instance.PurgeCache();
                return response.StartsWith("HTTP/1.0 303") || response.StartsWith("HTTP/1.1 303");
            }
            catch (Exception e)
            {
                Current.LogException(e);
                return false;
            }
        }
Example #2
0
 public Pacote(Action act, string target, string nick)
 {
     this.users = new List<Amigo>();
     this.action = act.ToString();
     this.target = target;
     this.nickname = nick;
 }
Example #3
0
        public static string ToDebugString(this System.Action action)
        {
#if UNITY_WSA && ENABLE_DOTNET && !UNITY_EDITOR
            return(action.ToString());
#else
            return(action.Method.ToDebugString());
#endif
        }
 public EditClassDialog(List<Class> classList, Action action)
 {
     InitializeComponent();
     this.Text = action + " class";
     bEditClass.Text = action.ToString();
     foreach (Class c in classList)
     {
         cmbClassList.Items.Add(c);
     }
     cmbClassList.SelectedIndex = -1;
 }
 public void Execute(Action command)
 {
     executionCount.AtomicIncrementAndGet();
     if (!ignoreExecution.ReadFullFence())
     {
         var th = new Thread(() => command());
         th.Name = command.ToString();
         th.IsBackground = true;
         threads.Add(th);
         th.Start();
     }
 }
 public EditStudentDialog(List<Class> classList, AbstractHelper helper, Action action)
 {
     InitializeComponent();
     this._helper = helper;
     this.Text = action + " student";
     bEditStud.Text = action.ToString();
     foreach (Class c in classList)
     {
         cmbClassList.Items.Add(c);
         cmbEditStudClass.Items.Add(c);
     }
     cmbClassList.SelectedIndex = -1;
 }
 private void AddActionToList(Action act, int index)
 {
     int imgIdx = (int)act.ActionType;
     if (imgIdx > 0) imgIdx -= 4;
     string txt = act.ToString();
     ListViewItem lvi = new ListViewItem(new string[] {
             TaskEnumGlobalizer.GetString(act.ActionType),
             txt }, imgIdx) { Tag = act, ToolTipText = txt };
     if (index < 0)
         actionListView.Items.Add(lvi);
     else
         actionListView.Items.Insert(index, lvi);
 }
Example #8
0
		protected void RunAction (Action<TextEditorData> action)
		{
			HideMouseCursor ();
			try {
				Document.BeginAtomicUndo ();
				action (this.textEditorData);
				if (Document != null) // action may have closed the document.
					Document.EndAtomicUndo ();
			} catch (Exception e) {
				Console.WriteLine ("Error while executing action " + action.ToString () + " :" + e);
			}
		}
Example #9
0
		protected void RunAction (Action<TextEditorData> action)
		{
			HideMouseCursor ();
			try {
				action (this.textEditorData);
			} catch (Exception e) {
				Console.WriteLine ("Error while executing action " + action.ToString () + " :" + e);
			}
		}
Example #10
0
        void CheckCopyPalette(MainForm form, DataEntry[] de, Action<IWICPalette> method)
        {
            IWICImagingFactory factory = (IWICImagingFactory)new WICImagingFactory();
            IWICPalette palette = factory.CreatePalette();

            try
            {
                method(palette);
                try
                {
                    if (palette.GetColorCount() == 0)
                    {
                        form.Add(this, method.ToString(Resources._0_ZeroColorPalette), de);
                    }
                }
                catch (Exception e)
                {
                    form.Add(this, method.ToString(Resources._0_IncorrectStatePalette), de, new DataEntry(e));
                }
            }
            catch (Exception e)
            {
                form.CheckHRESULT(this, WinCodecError.WINCODEC_ERR_PALETTEUNAVAILABLE, e, de);
            }
            finally
            {
                palette.ReleaseComObject();
                factory.ReleaseComObject();
            }
        }
		//Unsubscribes a Function member from everything
		public static void UnsubscribeFunction(Action<object> func){

			if (func == null)
				return;

			foreach (var eventName in subscribedMembers.Keys){
				foreach (var member in subscribedMembers[eventName].ToArray()){
					if (member.subscribedFunction != null && member.subscribedFunction.ToString() == func.ToString())
						subscribedMembers[eventName].Remove(member);
				}
			}

			if (logEvents)
				Debug.Log("XXX " + func.ToString() + " Unsubscribed from everything");
		}
Example #12
0
 /// <summary>
 /// Detaches the specifed listener for all sensors
 /// </summary>
 /// <param name="listener">
 /// A <see cref="Action<Sensor>"/>
 /// </param>
 public void RemoveListener(Action<Sensor> listener)
 {
     if (Logger.DUMP) Logger.dump("SensorRegistry", "RemoveListener " + listener.ToString());
     lock(sync_listener)
     {
     foreach (var sl in activeSensors.Values.ToArray()) {
         var removed = sl.listeners.RemoveAll((g) => {return g == listener;});
         if (removed > 0)
             sl.sensor.NotifyRemoveListener(listener);
         if(sl.listeners.Count == 0)
             activeSensors.Remove(sl.sensor);
     }
     activeSensors_array = null;
     }
 }
Example #13
0
 public Pacote(Action act, string nick)
 {
     users = new List<Amigo>();
     action = act.ToString();
     nickname = nick;
 }
Example #14
0
        public XmlDocument MakeRequest(Action action, ParameterCollection parameters)
        {
            TimeSpan diff = DateTime.Now - _lastQueryTime;
            if (action == Action.Edit && diff.Milliseconds < _sleepBetweenEdits)
            {
                Thread.Sleep(_sleepBetweenEdits - diff.Milliseconds);
            }

            XmlDocument doc = new XmlDocument();
            HttpWebResponse response = null;
            string query = PrepareQuery(action, parameters);
            for (int tries = 0; tries < 3; ++tries)
            {
                HttpWebRequest request = PrepareRequest();
                using (StreamWriter sw =
                    new StreamWriter(request.GetRequestStream()))
                {
                    sw.Write(query);
                }
                response = (HttpWebResponse)request.GetResponse();
                string[] retryAfter = response.Headers.GetValues("Retry-After");
                if (retryAfter != null)
                {
                    int lagInSeconds = int.Parse(retryAfter[0]);
                    Thread.Sleep(lagInSeconds * 1000);
                }
                else
                {
                    using (StreamReader sr =
                        new StreamReader(GetResponseStream((HttpWebResponse)response)))
                    {
                        doc.LoadXml(sr.ReadToEnd());
                        _lastQueryTime = DateTime.Now;
                        XmlNode errorNode = doc.SelectSingleNode("//error");
                        if (errorNode != null &&
                            errorNode.Attributes["code"].Value == "maxlag")
                        {
                            Thread.Sleep(5 * 1000 * (tries + 1));
                            continue;
                        }
                    }
                    break;
                }
            }

            XmlNode node = doc.SelectSingleNode("//error");
            if (node != null)
            {
                string code = node.Attributes["code"].Value;
                throw MakeActionException(action, code);
            }
            node = doc.SelectSingleNode("//" + action.ToString().ToLower());
            string result = "";
            if (node != null && node.Attributes["result"] != null)
            {
                result = node.Attributes["result"].Value;
                if (result != "Success" && result != "NeedToken")
                {
                    throw MakeActionException(action, result);
                }
            }

            if (action == Action.Login &&
                response.Cookies != null &&
                response.Cookies.Count > 0)
            {
                _cookies = new CookieContainer();
                _cookies.Add(response.Cookies);
            }
            return doc;
        }
Example #15
0
        private void PrintLog(Maked tipo, Action evento, string sender, string content)
        {
            dgvLog.Rows.Add(
                new string[] { evento.ToString(), DateTime.Now.ToString( "hh:mm:ss.fff"),
                               sender, content });

            DataGridViewRow linha = dgvLog.Rows[dgvLog.RowCount - 1];
            DataGridViewCell cel1 = dgvLog.Rows[dgvLog.RowCount - 1].Cells[0];

            setLineColor(tipo, linha);
            setActionColor(evento, cel1);

            dgvLog.CurrentCell = cel1;
        }
 /// <summary>
 /// Queues up commands called on a stream that hasn't fully loaded yet. The commands are executed 
 /// as soon as playback is initiated.
 /// </summary>
 private void QueueCommand(Action command)
 {
     sb.AppendLine("New command issued: " + command.ToString());
     queuedCommands.Add(command);
 }
		protected void RunAction (Action<TextEditorData> action)
		{
			HideMouseCursor ();
			try {
				using (var undo = Document.OpenUndoGroup ()) {
					action (this.textEditorData);
				}
			} catch (Exception e) {
				Console.WriteLine ("Error while executing action " + action.ToString () + " :" + e);
			}
		}
        //SEND MESSAGE TO QUEUE - REQUEST to delete thumbnails & posters
        public void SendDeleteMessages(Action act, string blobUrl = "", string thumbUrl = "")
        {
            // Create message, passing a string message for the body.
            BrokeredMessage message = new BrokeredMessage(AppConfiguration.ApplicationId);

            // Set some additional custom app-specific properties.
            message.Properties["Action"] = act.ToString();
            message.Properties["ImageUrl"] = blobUrl;
            message.Properties["ThumbURL"] = thumbUrl;

            // Send message to the queue.
            QClient.Send(message);
        }
        //The Invoke action for the interface
        //Provides Run to Gui mechanism
        public void Invoke(Action action)
        {
            var handler = new Handler(Looper.MainLooper);
            Log.Info("SharpXmppDemo", ".MultiDebug: " + "Invoke was called for action: " + action.ToString());

            if (handler != null)
            {
                handler.Post(action);
            }
            else
            {
                throw new InvalidOperationException("No handler for the main thread was created");
            }
        }
Example #20
0
 /// <summary>
 /// Adds listener for the specified sensor
 /// </summary>
 /// <remarks>
 /// Use period of milliseconds to
 /// update the reading. Default is 0 - means update as fast as possible
 /// </remarks>
 public void AddListener(Sensor sensor, Action<Sensor> listener, int period)
 {
     if (Logger.DUMP) Logger.dump("SensorRegistry", "AddListener "+ sensor.ID + " " + listener.ToString() + " " + period);
     lock(sync_listener)
     {
     if (sensor == null)
         throw new NullReferenceException("Null sensor");
     SensorListener sl = null;
     try{
         sl = activeSensors[sensor];
     }catch(KeyNotFoundException){
         sl = new SensorListener();
         sl.sensor = sensor;
         sl.period = period;
         activeSensors.Add(sensor, sl);
     }
     if (sl.period > period){
         sl.period = period;
         sl.nextReading = 0;
     }
     if (!sl.listeners.Contains(listener))
     {
         sl.listeners.Add(listener);
     #if DEBUG
         sl.bt += Environment.StackTrace;
     #endif
         sensor.NotifyAddListener(listener);
     }
     activeSensors_array = null;
     }
 }
Example #21
0
 public CoroutineLoopThread(Action method)
     : base(method, "", Priority.Low, 0)
 {
     UnityEngine.Debug.Log("CoroutineLoopThread Created " + method.ToString());
 }
 private static string getActionForIntent(Context context, Action action)
 {
     return context.PackageName + "." + action.ToString();
 }
 public void agentActed(Agent agent, Action action, EnvironmentState resultingState)
 {
     System.Console.WriteLine("Agent acted: " + action.ToString());
 }
Example #24
0
 /// <summary>
 /// Removes the listener for the specified sensor
 /// </summary>
 public void RemoveListener(Sensor sensor, Action<Sensor> listener)
 {
     if (Logger.DUMP) Logger.dump("SensorRegistry", "RemoveListener "+ sensor.ID + " " + listener.ToString());
     lock(sync_listener)
     {
     if (!activeSensors.ContainsKey(sensor))
         return; // TODO: handle errors?
     SensorListener sl = activeSensors[sensor];
     var removed = sl.listeners.RemoveAll((g) => {return g == listener;});
     if (removed > 0)
         sensor.NotifyRemoveListener(listener);
     if(sl.listeners.Count == 0)
         activeSensors.Remove(sensor);
     activeSensors_array = null;
     }
 }
Example #25
0
 private static WikiException MakeActionException(Action action, string error)
 {
     string message = action.ToString() + " failed with error '" + error + "'.";
     switch (action)
     {
         case Action.Edit:
             return new EditException(message);
         case Action.Login:
             return new LoginException(message);
         case Action.Move:
             return new MoveException(message);
         default:
             return new WikiException(message);
     }
 }
 public string RelationshipJson(int userId, Action action) {
     string uri = string.Format(base.Uri + "{0}/relationship?access_token={1}", userId, AuthInfo.Access_Token);
     var parameters = new Dictionary<string, string>();
     parameters.Add("action", action.ToString());
     return HttpClient.POST(uri, parameters);
 }
Example #27
0
 public string PrepareQuery(Action action, ParameterCollection parameters)
 {
     string query = "";
     switch (action)
     {
         default:
             query = "action=" + action.ToString().ToLower();
             break;
     }
     StringBuilder attributes = new StringBuilder();
     foreach (KeyValuePair<string, string> pair in parameters)
     {
         attributes.Append(string.Format("&{0}={1}",
             pair.Key,
             EscapeString(pair.Value)));
     }
     query += attributes.ToString();
     return query;
 }
        public bool NetPermissionWrapper(Action action)
        {
            try
            {
                action();
            }
            catch (Exception e)
            {
                if (Utils.IsAdministrator())
                {
                    MessageBox.Show("Settings the ports, after that JMMServer will quit, run again in normal mode");
                    Utils.SetNetworkRequirements(ServerSettings.JMMServerPort, ServerSettings.JMMServerFilePort,
                        ServerSettings.JMMServerPort, ServerSettings.JMMServerFilePort);
                    try
                    {
                        action();
                    }
                    catch (Exception exception)
                    {
                        MessageBox.Show("Unable start hosting");
                        logger.Error("Unable to run task: " + (action.Method?.Name ?? action.ToString()));
                        logger.Error(exception);
                    }
                    finally
                    {
                        ApplicationShutdown();
                    }
                    return false;
                }
                else
                {
                    MessageBox.Show("Unable to start hosting, please run JMMServer as administrator once.");
                    logger.Error(e);
                    ApplicationShutdown();
                    return false;
                }

            }
            return true;
        }
Example #29
0
 public StandardLoopThread(Action method, string threadName, Priority priority, int cycleTimeMS = 0)
     : base(method, threadName, priority, cycleTimeMS)
 {
     UnityEngine.Debug.Log("StandardLoopThread Created " + method.ToString() + " " + threadName + " " + priority + " " + cycleTimeMS);
 }
Example #30
0
		protected void ExecuteWithErrorHandling(Action action)
		{
			if (CurrentAction != null)
			{
				HideProgress();
				errorLabel.Text = "A maintenance operation is already in progress.";
				errorLabel.Visible = true;
				return;
			}

			CurrentAction = action;
			CurrentActionProgress = "Preparing to run the action: " + CurrentAction.ToString();
			ShowProgress();
			ThreadPool.QueueUserWorkItem((obj) =>
			{
				try
				{
					CurrentActionProgress = "Initializing";
					action();
					CurrentActionProgress = "Completed";
				}
				catch (Exception ex)
				{
					CurrentActionProgress = FormatException(ex);
				}
				finally
				{
					CurrentAction = null;
					HideProgress();
				}
			});
		}
Example #31
0
 public override string ToString()
 {
     return(string.Format("[ActionVoid: {0}]", action.ToString()));
 }
Example #32
0
 public Pacote(Action act)
 {
     users = new List<Amigo>();
     action = act.ToString();
 }