Example #1
0
        private object InvokeWebRequestWithParameters(SimpleWebRequest webRequest, IDictionary <string, object> values = null)
        {
            // Take the values, which are defined in the mapping
            foreach (var dataMapping in this.DataMappings)
            {
                object value = null;

                if (dataMapping.Value != null)
                {
                    // replace token e.g {Filename} ->  C:\Temp\Test.txt
                    value = TokenProcessor.ReplaceTokens(dataMapping.Value.ToStringOrEmpty(), values);
                }
                else
                {
                    value = values.GetValue(dataMapping.Name);
                }

                webRequest.Parameters.Add(dataMapping.Name, value.ToStringOrEmpty());
            }

            // call the service
            var result = webRequest.Invoke();

            // format the result
            object data = null;

            if (this.formatter != null && result != null)
            {
                data = this.formatter.Format(result, null);
            }

            return(data);
        }
        protected override void SetHost <T>(SimpleWebRequest <T> request)
        {
            if (request != null)
            {
                var dics = new Dictionary <string, string>();

                dics.Add("x-ca-accesskeyid", _accessKeyId);
                dics.Add("x-ca-version", _version);
                dics.Add("x-ca-timestamp", string.Format("{0}", (long)(DateTime.Now.Subtract(new DateTime(1970, 1, 1, 0, 0, 0)).TotalSeconds)));
                dics.Add("x-ca-signaturenonce", Guid.NewGuid().ToString("N"));
                dics.Add("requestmethod", "POST");

                foreach (var dic in dics)
                {
                    request.SetHeader(dic.Key, dic.Value);
                }

                var properties = request.GetType().GetProperties();
                foreach (var p in properties)
                {
                    var ca = p.GetCustomAttribute(typeof(ParaSignAttribute));
                    if (ca != null)
                    {
                        var _ca   = ca as ParaSignAttribute;
                        var value = p.GetValue(request);
                        if (p.PropertyType == typeof(System.String))
                        {
                            if (value != null && !string.IsNullOrWhiteSpace(value.ToString()))
                            {
                                dics.Add(_ca.Name, string.Format("{0}", value));
                            }
                        }
                        else if (p.PropertyType == typeof(int?))
                        {
                            var v = value as int?;
                            if (v != null)
                            {
                                dics.Add(_ca.Name, string.Format("{0}", value));
                            }
                        }
                        else if (p.PropertyType == typeof(double?))
                        {
                            var v = value as double?;
                            if (v != null)
                            {
                                dics.Add(_ca.Name, string.Format("{0}", value));
                            }
                        }
                    }
                }

                request.SetHeader("x-ca-signature", Signnature(dics));
            }

            base.SetHost <T>(request);
        }
Example #3
0
        public DetailsInfo GetDetails(antiufo.Threading.BackgroundFunction <DetailsInfo> a)
        {
            if (!HasDetailsTable)
            {
                throw new InvalidOperationException("Details are not available for this program.");
            }
            var html = SimpleWebRequest.GetHtmlRobust("http://www.mymovies.it/dizionario/" + _id, true, "ISO-8859-1");

            return(new DetailsInfo(html, _id));
        }
Example #4
0
        /// <summary>
        /// Call the web service function with an Xml payload to add a crash to the database.
        /// </summary>
        /// <param name="Payload">Xml representation of a new crash to upload.</param>
        /// <returns>The database id of the newly added row.</returns>
        private int UploadCrash(string Payload)
        {
            int NewID = -1;

            try
            {
                // Simple suppression by blanking out the URL for local testing
                if (Config.Default.CrashReportWebSite.Length > 0)
                {
                    bool   bDebug = false;
                    string RequestString;
                    if (!bDebug)
                    {
                        RequestString = "http://" + Config.Default.CrashReportWebSite + ":80/Crashes/AddCrash/-1";
                    }
                    else
                    {
                        RequestString = "http://localhost:80/Crashes/AddCrash/-1";
                    }

                    string ErrorMessage = string.Empty;

                    for (int Retry = 0; Retry < 3; ++Retry)
                    {
                        string ResponseString = SimpleWebRequest.GetWebServiceResponse(RequestString, Payload);
                        if (ResponseString.Length > 0)
                        {
                            // Convert response into a string
                            CrashReporterResult Result = XmlHandler.FromXmlString <CrashReporterResult>(ResponseString);
                            if (Result.ID > 0)
                            {
                                NewID = Result.ID;
                                break;
                            }
                            ErrorMessage = Result.Message;
                        }
                        Thread.Sleep(200);
                    }

                    if (NewID == -1)
                    {
                        CrashReporterProcessServicer.WriteFailure(string.Format("PROC-{0} ", ProcessorIndex) + "UploadCrash: " + ErrorMessage);
                    }
                }
            }
            catch (Exception Ex)
            {
                CrashReporterProcessServicer.WriteException(string.Format("PROC-{0} ", ProcessorIndex) + "UploadCrash: " + Ex.ToString());
            }

            return(NewID);
        }
        public override async Task <T> ExecuteAsync <T>(SimpleWebRequest <T> request)
        {
            if (request == null)
            {
                throw new ArgumentNullException(nameof(request));
            }

            var objType = request.GetType();

            if (objType == typeof(Entity.AuthenticationRequest))
            {
                return(await base.ExecuteAsync <T>(request));
            }

            await ConnectAsync();

            //Append Authorization token in the Http Headers
            //if (request.Headers.ContainsKey("Authorization"))
            //    request.Headers["Authorization"] = _token;
            //else
            //    request.Headers.Add("Authorization", _token);
            var tokenPro = objType.GetProperty("AuthorizationToken");

            if (tokenPro != null && tokenPro.CanWrite)
            {
                tokenPro.SetValue(request, _token);
            }

            //Get Response
            var response = await base.ExecuteAsync(request);

            if (response != null)
            {
                var _apiResponse = response.GetType().GetProperty("Response");
                if (_apiResponse != null)
                {
                    var responseBody = _apiResponse.GetValue(response);
                    var pro          = responseBody.GetType().GetProperty("ErrorId");
                    var errorId      = pro.GetValue(responseBody);
                    if (responseBody != null && pro != null && errorId != null && errorId.ToString() == "NOAUTH")
                    {
                        //re-auth
                        await ReAuthAsync();

                        return(await this.ExecuteAsync(request));
                    }
                }
            }

            return(response);
        }
Example #6
0
        static private void Main(string[] Arguments)
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            // Create a new instance of the window (which may not be shown)
            RegisterPII Instance = new RegisterPII();

            // Check to see if we should hide the window
            bool bShowWindow = true;

            if (Arguments.Length > 0)
            {
                if (Arguments[0].ToLower() == "/silent")
                {
                    bShowWindow = false;
                }
            }

            // Display the window if it isn't hidden
            if (bShowWindow)
            {
                // Show the dialog
                Instance.Show();
                Application.DoEvents();
            }

            // Send the info to the server
            string WebRequest = "http://" + Properties.Settings.Default.CrashReportWebSite + ":80/Crashes/RegisterPII/" + Environment.UserName + "/" + Environment.MachineName + "/" + Instance.MachineIDString;

            SimpleWebRequest.GetWebServiceResponse(WebRequest, null);

            // Display the window for 5 seconds
            DateTime StartTime = DateTime.UtcNow;

            while (DateTime.UtcNow < StartTime.AddSeconds(5))
            {
                Application.DoEvents();
                Thread.Sleep(50);
            }

            Instance.Close();
        }
        /// <summary>
        /// Call the web service function with an Xml payload to add a crash to the database.
        /// </summary>
        /// <param name="Payload">Xml representation of a new crash to upload.</param>
        /// <returns>The database id of the newly added row.</returns>
        private int UploadCrash(string Payload)
        {
            int NewID = -1;

            try
            {
                // Simple suppression by blanking out the URL for local testing
                if (Properties.Settings.Default.CrashReportWebSite.Length > 0)
                {
                    bool   bDebug = false;
                    string RequestString;
                    if (!bDebug)
                    {
                        RequestString = "http://" + Properties.Settings.Default.CrashReportWebSite + ":80/Crashes/AddCrash/-1";
                    }
                    else
                    {
                        RequestString = "http://localhost:80/Crashes/AddCrash/-1";
                    }

                    string ResponseString = SimpleWebRequest.GetWebServiceResponse(RequestString, Payload);
                    if (ResponseString.Length > 0)
                    {
                        // Convert response into a string
                        CrashReporterResult Result = XmlHandler.FromXmlString <CrashReporterResult>(ResponseString);
                        if (Result.ID > 0)
                        {
                            NewID = Result.ID;
                        }
                        else
                        {
                            CrashReporterProcessServicer.WriteFailure("UploadCrash: " + Result.Message);
                        }
                    }
                }
            }
            catch (Exception Ex)
            {
                CrashReporterProcessServicer.WriteException("UploadCrash: " + Ex.ToString());
            }

            return(NewID);
        }
        public override async Task <T> ExecuteDownloadAsync <T>(SimpleWebRequest <T> request, string fileSaveFullPath)
        {
            await ConnectAsync();

            var tokenPro = request.GetType().GetProperty("AuthorizationToken");

            if (tokenPro != null && tokenPro.CanWrite)
            {
                tokenPro.SetValue(request, _token);
            }

            var t = await base.ExecuteDownloadAsync <T>(request, fileSaveFullPath);

            if (t.StatusCode == System.Net.HttpStatusCode.Unauthorized)
            {
                ReAuth();

                return(await this.ExecuteDownloadAsync(request, fileSaveFullPath));
            }

            return(t);
        }
        public bool ProcessQuery(SimpleWebRequest request, HttpResponse response)
        {
            object result = null;

            if (request.Path.Equals("/myapp/api/v1/data.json", StringComparison.InvariantCultureIgnoreCase))
            {
                result = Data;
            }

            if (result != null)
            {
                string mimeType = "application/json";
                Newtonsoft.Json.JsonSerializer ser = new Newtonsoft.Json.JsonSerializer();
                StringWriter writer = new StringWriter();
                ser.Serialize(writer, result);
                string       data   = writer.GetStringBuilder().ToString();
                byte[]       buffer = Encoding.ASCII.GetBytes(data);
                MemoryStream ms     = new MemoryStream(buffer);
                response.SendFile(HttpStatus.OK, ms, mimeType);
                return(true);
            }
            return(false);
        }
Example #10
0
        /// <summary>
        /// Call the web service function with an Xml payload to add a crash to the database.
        /// </summary>
        /// <param name="Payload">Xml representation of a new crash to upload.</param>
        /// <returns>The database id of the newly added row.</returns>
        private int UploadCrash(string Payload)
        {
            int NewID = -1;

            try
            {
                // Simple suppression by blanking out the URL for local testing
                if (Config.Default.CrashReportWebSite.Length > 0)
                {
                    bool   bDebug = false;
                    string RequestString;
                    if (!bDebug)
                    {
                        RequestString = "http://" + Config.Default.CrashReportWebSite + ":80/Crashes/AddCrash/-1";
                    }
                    else
                    {
                        RequestString = "http://localhost:80/Crashes/AddCrash/-1";
                    }


                    Action <UploadRetryState> TryUpload = InRetryState =>
                    {
                        string ResponseString = SimpleWebRequest.GetWebServiceResponse(RequestString, Payload, Config.Default.AddCrashRequestTimeoutSeconds * 1000);
                        if (ResponseString.Length > 0)
                        {
                            // Convert response into a string
                            CrashReporterResult Result = XmlHandler.FromXmlString <CrashReporterResult>(ResponseString);
                            if (!Result.bSuccess || Result.ID <= 0)
                            {
                                if (Result.bTimeout)
                                {
                                    // Website responded - website->DB connection timeout
                                    InRetryState.Timeouts++;
                                }
                                else
                                {
                                    // Website responded - fail condition
                                    InRetryState.BadResponses++;
                                    CrashReporterProcessServicer.WriteEvent(string.Format("PROC-{0} UploadCrash response invalid. FailedResponses={1} Response={2}",
                                                                                          ProcessorIndex, InRetryState.BadResponses, Result.Message));
                                    if (InRetryState.BadResponses > Config.Default.AddCrashRejectedRetries)
                                    {
                                        InRetryState.bShouldRetry = false;
                                        CrashReporterProcessServicer.WriteEvent(string.Format("PROC-{0} UploadCrash abandoned. FailedResponses={1}",
                                                                                              ProcessorIndex, InRetryState.BadResponses));
                                    }
                                }
                            }
                            else
                            {
                                // Website responded - success
                                NewID = Result.ID;
                                InRetryState.bUploaded = true;
                                return;
                            }
                        }
                        else
                        {
                            // No response
                            InRetryState.Timeouts++;
                        }
                        InRetryState.bUploaded = false;
                    };
                    Action <UploadRetryState> OnRetry = InRetryState =>
                    {
                        if (!InRetryState.bUploaded)
                        {
                            Thread.Sleep(Config.Default.AddCrashRetryDelaySeconds * 1000);
                            CrashReporterProcessServicer.WriteEvent(string.Format("PROC-{0} UploadCrash retrying upload. Timeouts={1} FailedResponses={2}", ProcessorIndex, InRetryState.Timeouts, InRetryState.BadResponses));
                        }
                    };

                    UploadRetryState RetryState = new UploadRetryState();

                    for (; !RetryState.bUploaded && RetryState.bShouldRetry && !CancelSource.IsCancellationRequested; OnRetry(RetryState))
                    {
                        TryUpload(RetryState);
                        CrashReporterProcessServicer.StatusReporter.AlertOnConsecutiveFails("AddCrash",
                                                                                            "Cannot contact CR website. CRP is paused!",
                                                                                            "Contact with CR website restored.",
                                                                                            TimeSpan.FromSeconds(Config.Default.FailedWebAddAlertTimeSeconds), RetryState.bUploaded);
                    }
                }
#if DEBUG
                else
                {
                    // No website set - simulate successful upload
                    var Rnd = new Random();
                    NewID = Rnd.Next(1, 99999999);
                }
#endif
            }
            catch (Exception Ex)
            {
                CrashReporterProcessServicer.WriteException(string.Format("PROC-{0} ", ProcessorIndex) + "UploadCrash: " + Ex, Ex);
            }

            return(NewID);
        }
Example #11
0
        /// <summary>
        /// Call the web service function with an Xml payload to add a crash to the database.
        /// </summary>
        /// <param name="Payload">Xml representation of a new crash to upload.</param>
        /// <returns>The database id of the newly added row.</returns>
        private int UploadCrash(string Payload)
        {
            int NewID = -1;

            try
            {
                // Simple suppression by blanking out the URL for local testing
                if (Config.Default.CrashReportWebSite.Length > 0)
                {
                    bool   bDebug = false;
                    string RequestString;
                    if (!bDebug)
                    {
                        RequestString = "http://" + Config.Default.CrashReportWebSite + ":80/Crashes/AddCrash/-1";
                    }
                    else
                    {
                        RequestString = "http://localhost:80/Crashes/AddCrash/-1";
                    }

                    string ErrorMessage = string.Empty;

                    const int MaxRetries = 1;
                    for (int AddCrashTry = 0; AddCrashTry < MaxRetries + 1; ++AddCrashTry)
                    {
                        string ResponseString = SimpleWebRequest.GetWebServiceResponse(RequestString, Payload, Config.Default.AddCrashRequestTimeoutMillisec);
                        if (ResponseString.Length > 0)
                        {
                            // Convert response into a string
                            CrashReporterResult Result = XmlHandler.FromXmlString <CrashReporterResult>(ResponseString);
                            if (Result.ID > 0)
                            {
                                NewID = Result.ID;
                                break;
                            }
                            CrashReporterProcessServicer.WriteEvent(string.Format("PROC-{0} UploadCrash response timeout (attempt {1} of {2}): {3}", ProcessorIndex, AddCrashTry + 1, MaxRetries + 1, ErrorMessage));
                            ErrorMessage = Result.Message;
                        }
                        Thread.Sleep(Config.Default.AddCrashRetryDelayMillisec);
                    }

                    if (NewID == -1)
                    {
                        CrashReporterProcessServicer.WriteFailure(string.Format("PROC-{0} ", ProcessorIndex) + "UploadCrash failed: " + ErrorMessage);
                    }
                }
#if DEBUG
                else
                {
                    // No website set - simulate successful upload
                    var Rnd = new Random();
                    NewID = Rnd.Next(1, 99999999);
                }
#endif
            }
            catch (Exception Ex)
            {
                CrashReporterProcessServicer.WriteException(string.Format("PROC-{0} ", ProcessorIndex) + "UploadCrash: " + Ex, Ex);
            }

            return(NewID);
        }
Example #12
0
        /// <summary>
        /// Call the web service function with an Xml payload to add a crash to the database.
        /// </summary>
        /// <param name="Payload">Xml representation of a new crash to upload.</param>
        /// <returns>The database id of the newly added row.</returns>
        private int UploadCrash(string Payload)
        {
            int NewID = -1;

            try
            {
                // Simple suppression by blanking out the URL for local testing
                if (Config.Default.CrashReportWebSite.Length > 0)
                {
                    bool   bDebug = false;
                    string RequestString;
                    if (!bDebug)
                    {
                        RequestString = "http://" + Config.Default.CrashReportWebSite + ":80/Crashes/AddCrash/-1";
                    }
                    else
                    {
                        RequestString = "http://localhost:80/Crashes/AddCrash/-1";
                    }

                    int         Attempt   = 1;
                    Func <bool> TryUpload = () =>
                    {
                        string ResponseString = SimpleWebRequest.GetWebServiceResponse(RequestString, Payload, Config.Default.AddCrashRequestTimeoutSeconds * 1000);
                        if (ResponseString.Length > 0)
                        {
                            // Convert response into a string
                            CrashReporterResult Result = XmlHandler.FromXmlString <CrashReporterResult>(ResponseString);
                            if (Result.ID > 0)
                            {
                                NewID = Result.ID;
                                return(true);
                            }

                            CrashReporterProcessServicer.WriteEvent(string.Format("PROC-{0} UploadCrash response invalid (upload attempt {1}): {2}", ProcessorIndex, Attempt, Result.Message));
                        }
                        return(false);
                    };
                    Action <bool> OnRetry = bUploaded =>
                    {
                        if (!bUploaded)
                        {
                            Thread.Sleep(Config.Default.AddCrashRetryDelaySeconds * 1000);
                            CrashReporterProcessServicer.WriteEvent(string.Format("PROC-{0} UploadCrash retrying upload attempt {1}", ProcessorIndex, Attempt));
                            Attempt++;
                        }
                    };

                    for (bool bUploaded = false; !bUploaded; OnRetry(bUploaded))
                    {
                        bUploaded = TryUpload();
                        CrashReporterProcessServicer.StatusReporter.AlertOnConsecutiveFails("AddCrash",
                                                                                            "Cannot contact CR website. CRP is paused!",
                                                                                            "Contact with CR website restored.",
                                                                                            TimeSpan.FromSeconds(Config.Default.FailedWebAddAlertTimeSeconds), bUploaded);
                    }
                }
#if DEBUG
                else
                {
                    // No website set - simulate successful upload
                    var Rnd = new Random();
                    NewID = Rnd.Next(1, 99999999);
                }
#endif
            }
            catch (Exception Ex)
            {
                CrashReporterProcessServicer.WriteException(string.Format("PROC-{0} ", ProcessorIndex) + "UploadCrash: " + Ex, Ex);
            }

            return(NewID);
        }