Beispiel #1
0
        private void FetchRequestLine()
        {
            string firstLine;

            do
            {
                firstLine = Reader.ReadLine();
                if (string.IsNullOrEmpty(firstLine))
                {
                    throw new Exception("Error during fetching of the request line.");
                }
            } while (firstLine == "\n" || firstLine == "\r\n" || firstLine == "\r");

            if (string.IsNullOrEmpty(firstLine))
            {
                return;
            }

            var firstLineMatch = FirstLineParser.Match(firstLine);
            var method         = firstLineMatch.Groups["Method"].ToString();

            if (!EnumTryParse(method, out _method))
            {
                _method = RequestMethods.None;
            }
            Path    = firstLineMatch.Groups["Path"].ToString();
            Path    = Uri.UnescapeDataString(Path);
            Version = firstLineMatch.Groups["Version"].ToString();
        }
Beispiel #2
0
 public RestHandler(MethodInfo method, RequestMethods requestMethods, Func <string, object>[] parsers,
                    Regex[] matchers)
 {
     this._method         = method;
     this._parsers        = parsers;
     this._matchers       = matchers;
     this._requestMethods = requestMethods;
 }
Beispiel #3
0
        Code == 999;           // Wewnętrzny błąd systemu

        #endregion


        #region Execute(Command, Data, ...)

        /// <summary>
        /// Exceute the given SMSAPI command.
        /// </summary>
        /// <param name="Command">The SMSAPI command.</param>
        /// <param name="Data">The data of the SMSAPI command.</param>
        /// <param name="File">An optional file to send.</param>
        /// <param name="HTTPMethod">The HTTP method to use.</param>
        public Task <Stream> Execute(String Command,
                                     NameValueCollection Data,
                                     Stream File,
                                     RequestMethods HTTPMethod = RequestMethods.POST)

        => Execute(Command,
                   Data,
                   new Dictionary <String, Stream> {
            { "file", File }
        },
                   HTTPMethod);
Beispiel #4
0
        public bool HandlesRequest(HttpContext context)
        {
            string         url    = Utility.CleanURL(Utility.BuildURL(context));
            RequestMethods method = (RequestMethods)Enum.Parse(typeof(RequestMethods), context.Request.Method.ToUpper());

            foreach (IRequestHandler handler in _Handlers)
            {
                if (handler.HandlesRequest(url, method))
                {
                    return(true);
                }
            }
            return(false);
        }
Beispiel #5
0
        public async Task <TResult> OAuth2Request <TResult>(RequestMethods method, string url, OAuthAccount account, Dictionary <string, string> parameters = null)
        {
            var stringMethod = Enum.GetName(typeof(RequestMethods), method);

            Request2 = new OAuth2Request(stringMethod, new Uri(url), parameters, account);

            var response = await Request2.GetResponseAsync();

            if (response != null)
            {
                string resultJson = response.GetResponseText();
                var    result     = JsonConvert.DeserializeObject <TResult>(resultJson);
                return(result);
            }

            return(Activator.CreateInstance <TResult>());
        }
Beispiel #6
0
        public async Task ProcessRequest(HttpContext context, ISecureSession session)
        {
            string         url      = Utility.CleanURL(Utility.BuildURL(context));
            RequestMethods method   = (RequestMethods)Enum.Parse(typeof(RequestMethods), context.Request.Method.ToUpper());
            string         formData = new StreamReader(context.Request.Body).ReadToEnd();
            bool           found    = false;

            foreach (IRequestHandler handler in _Handlers)
            {
                if (handler.HandlesRequest(url, method))
                {
                    found = true;
                    try
                    {
                        await handler.HandleRequest(url, method, formData, context, session, new IsValidCall(_ValidCall));
                    }
                    catch (CallNotFoundException cnfe)
                    {
                        context.Response.ContentType = "text/text";
                        context.Response.StatusCode  = 400;
                        await context.Response.WriteAsync(cnfe.Message);
                    }
                    catch (InsecureAccessException iae)
                    {
                        context.Response.ContentType = "text/text";
                        context.Response.StatusCode  = 403;
                        await context.Response.WriteAsync(iae.Message);
                    }
                    catch (Exception e)
                    {
                        context.Response.ContentType = "text/text";
                        context.Response.StatusCode  = 500;
                        await context.Response.WriteAsync("Error");
                    }
                }
            }
            if (!found)
            {
                context.Response.ContentType = "text/text";
                context.Response.StatusCode  = 404;
                await context.Response.WriteAsync("Not Found");
            }
        }
Beispiel #7
0
        public static String RequestMethodToString(this RequestMethods method)
        {
            switch (method)
            {
            case RequestMethods.GET:
                return("GET");

            case RequestMethods.PUT:
                return("PUT");

            case RequestMethods.POST:
                return("POST");

            case RequestMethods.DELETE:
                return("DELETE");

            default:
                throw new HTTPClientException("Invalid request method");
            }
        }
        private async Task <string> SendHttpRequestAsync(RequestMethods methods, string url, Dictionary <string, string> parameters)
        {
            if (methods == RequestMethods.Get)
            {
                return(await _httpClient.GetStringAsync($"{url}?{GetUrlParameter(parameters)}"));
            }
            else if (methods == RequestMethods.Post)
            {
                // StringContent,FormUrlEncodedContent,MultipartFormDataContent
                //var content = new FormUrlEncodedContent(parameters);
                var response = await _httpClient.PostAsync($"{url}?{GetUrlParameter(parameters)}", null);

                if (response.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    return(await response.Content.ReadAsStringAsync());
                }
                _logger.LogError($"请求[{response.RequestMessage.Method.Method}] {response.RequestMessage.RequestUri} 返回{response.StatusCode} : {await response.Content.ReadAsStringAsync()}");
            }
            return(string.Empty);
        }
Beispiel #9
0
        private void Compute()
        {
            dataGridView1.Rows.Clear();

            IRequestMethods requestMethods = new RequestMethods();
            var             output1        = requestMethods.GetMatsTwo(decimal.Parse(txtTireQty.Text));
            var             output2        = requestMethods.GetMatsThree(decimal.Parse(txtTireQty.Text));
            var             t       = output2.Where(r => r.hasraw == 1).Select(r => r.qty);
            var             output3 = requestMethods.GetMatsRawMats(decimal.Parse(t.FirstOrDefault().ToString()));

            List <Output> finaloutput = new List <Output>();

            finaloutput.AddRange(output1);
            finaloutput.AddRange(output2);
            finaloutput.AddRange(output3);

            foreach (var item in finaloutput)
            {
                AddToDGV(item.description, Math.Round(item.qty, 3).ToString(), item.uom);
            }
        }
Beispiel #10
0
        public string GetResponse(string uri, string data = "", RequestMethods method = RequestMethods.GET)
        {
            System.Diagnostics.Trace.WriteLine(uri);

            // create request
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
            request.PreAuthenticate = true;
            request.Method = method.ToString().ToUpper();
            request.ContentType = "application/x-www-form-urlencoded";

            // log in
            string authInfo = API_KEY + ":" + ""; // blank password
            authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));
            request.Headers["Authorization"] = "Basic " + authInfo;

            // send data
            if (data != "")
            {
                byte[] paramBytes = Encoding.ASCII.GetBytes(data);
                request.ContentLength = paramBytes.Length;
                Stream reqStream = request.GetRequestStream();
                reqStream.Write(paramBytes, 0, paramBytes.Length);
                reqStream.Close();
            }

            // get response
            try
            {
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                return new StreamReader(response.GetResponseStream()).ReadToEnd();
            }
            catch (WebException ex)
            {
                HttpWebResponse response = ((HttpWebResponse)ex.Response);
                throw new Exception(uri + " caused a " + (int)response.StatusCode + " error.\n" + response.StatusDescription);
            }
        }
Beispiel #11
0
        private HttpPacket(Frame parentFrame, int packetStartIndex, int packetEndIndex)
            : base(parentFrame, packetStartIndex, packetEndIndex, "HTTP")
        {
            /*
             *
             *         generic-message = start-line
             *             *(message-header CRLF)
             *             CRLF
             *             [ message-body ]
             *
             *         start-line      = Request-Line | Status-Line
             *
             * */
            this.headerFields                     = new List <string>();
            this.requestedHost                    = null;
            this.requestedFileName                = null;
            this.userAgentBanner                  = null;
            this.statusCode                       = null;
            this.statusMessage                    = null;
            this.serverBanner                     = null;
            this.contentType                      = null;
            this.contentLength                    = -1;//instead of null
            this.contentEncoding                  = null;
            this.cookie                           = null;
            this.transferEncoding                 = null;
            this.wwwAuthenticateRealm             = null;
            this.authorizationCredentialsUsername = null;
            this.authorizationCredentailsPassword = null;
            this.packetHeaderIsComplete           = false;
            this.contentDispositionFilename       = null;
            this.contentRange                     = null;

            int dataIndex = packetStartIndex;

            //a start-line
            string startLine = Utils.ByteConverter.ReadLine(parentFrame.Data, ref dataIndex);

            if (startLine == null)
            {
                throw new Exception("HTTP packet does not contain a valid start line. Probably a false HTTP positive");
            }
            if (startLine.Length > 2048)
            {
                throw new Exception("HTTP start line is longer than 255 bytes. Probably a false HTTP positive");
            }

            if (dataIndex > packetEndIndex)
            {
                throw new Exception("HTTP start line ends after packet end...");
            }

            if (startLine.StartsWith("GET"))
            {
                this.messageTypeIsRequest = true;
                this.requestMethod        = RequestMethods.GET;
            }
            else if (startLine.StartsWith("HEAD"))
            {
                this.messageTypeIsRequest = true;
                this.requestMethod        = RequestMethods.HEAD;
            }
            else if (startLine.StartsWith("POST"))
            {
                this.messageTypeIsRequest = true;
                this.requestMethod        = RequestMethods.POST;
            }
            else if (startLine.StartsWith("PUT"))
            {
                this.messageTypeIsRequest = true;
                this.requestMethod        = RequestMethods.PUT;
            }
            else if (startLine.StartsWith("DELETE"))
            {
                this.messageTypeIsRequest = true;
                this.requestMethod        = RequestMethods.DELETE;
            }
            else if (startLine.StartsWith("TRACE"))
            {
                this.messageTypeIsRequest = true;
                this.requestMethod        = RequestMethods.TRACE;
            }
            else if (startLine.StartsWith("OPTIONS"))
            {
                this.messageTypeIsRequest = true;
                this.requestMethod        = RequestMethods.OPTIONS;
            }
            else if (startLine.StartsWith("CONNECT"))
            {
                this.messageTypeIsRequest = true;
                this.requestMethod        = RequestMethods.CONNECT;
            }
            else if (startLine.StartsWith("HTTP"))
            {
                this.messageTypeIsRequest = false;
                this.requestMethod        = RequestMethods.none;
            }
            else
            {
                throw new Exception("Incorrect HTTP Message Type or Request Method");
            }

            //zero or more header fields (also known as "headers")
            while (true)
            {
                string headerLine = Utils.ByteConverter.ReadLine(parentFrame.Data, ref dataIndex);
                if (headerLine == null)
                {
                    break;//this.packetHeaderIsComplete will NOT be true!
                }
                else if (headerLine.Length > 0)
                {
                    this.headerFields.Add(headerLine);
                    ExtractHeaderField(headerLine);
                }
                else  //headerLine.Length==0
                {
                    this.packetHeaderIsComplete = true;//the header is complete and that's enough
                    break;//the for loop should stop now...
                }
            }

            //see if there is a message-body
            if (this.packetHeaderIsComplete && this.messageTypeIsRequest && (requestMethod == RequestMethods.HEAD || requestMethod == RequestMethods.GET))
            {
                //this part is important in case there are chained (queued) requests as in HTTP 1.1
                this.messageBody    = null;
                this.PacketEndIndex = dataIndex - 1;
            }
            else if (this.packetHeaderIsComplete && dataIndex <= packetEndIndex)//we have a body!
            {
                if (this.contentLength > 0 && this.contentLength < packetEndIndex - dataIndex + 1)
                {
                    this.messageBody    = new byte[this.contentLength];
                    this.PacketEndIndex = dataIndex + this.contentLength - 1;
                }
                else
                {
                    this.messageBody = new byte[packetEndIndex - dataIndex + 1];
                }
                Array.Copy(parentFrame.Data, dataIndex, this.messageBody, 0, this.messageBody.Length);

                /*
                 * for(int i=0; i<this.messageBody.Length; i++)
                 *  this.messageBody[i]=parentFrame.Data[dataIndex+i];
                 * */
            }
            else
            {
                this.messageBody = null;
            }


            //now extract some interresting information from the packet
            if (this.messageTypeIsRequest) //REQUEST
            {
                if (this.requestMethod == RequestMethods.GET || this.requestMethod == RequestMethods.POST || this.requestMethod == RequestMethods.HEAD || this.requestMethod == RequestMethods.OPTIONS)
                {
                    int    requestUriOffset = this.requestMethod.ToString().Length + 1;
                    string fileURI          = startLine.Substring(requestUriOffset, startLine.Length - requestUriOffset);
                    if (fileURI.Contains(" HTTP"))
                    {
                        fileURI = fileURI.Substring(0, fileURI.IndexOf(" HTTP"));
                    }
                    if (fileURI.Length > 0)//If it is the index-file the URI will be just "/"
                    {
                        this.requestedFileName = fileURI;
                    }
                    else
                    {
                        this.requestedFileName = null;
                    }
                } /*
                   * else if(this.requestMethod==RequestMethods.POST) {
                   * string fileURI=startLine.Substring(5, startLine.Length-5);
                   * if(fileURI.Contains(" HTTP")) {
                   *     fileURI=fileURI.Substring(0, fileURI.IndexOf(" HTTP"));
                   * }
                   * if(fileURI.Length>0) {//If it is the index-file the URI will be just "/"
                   *     this.requestedFileName=fileURI;
                   * }
                   * }*/
            }
            else  //REPLY
            {
                if (startLine.StartsWith("HTTP/1."))
                {
                    this.statusCode = startLine.Substring(9, 3);
                    if (startLine.Length > 12)
                    {
                        this.statusMessage = startLine.Substring(12).Trim();
                    }
                }
            }
        }
 private ServiceMethod(RequestMethods RequestMethods)
 {
     _Method = RequestMethods;
 }
Beispiel #13
0
        /// <summary>
        /// Exceute the given SMSAPI command.
        /// </summary>
        /// <param name="Command">The SMSAPI command.</param>
        /// <param name="Data">The data of the SMSAPI command.</param>
        /// <param name="Files">Optional files to send.</param>
        /// <param name="HTTPMethod">The HTTP method to use.</param>
        public async Task <Stream> Execute(String Command,
                                           NameValueCollection Data,
                                           Dictionary <String, Stream> Files = null,
                                           RequestMethods HTTPMethod         = RequestMethods.POST)
        {
            #region Init

            var EventTrackingId = EventTracking_Id.New;
            var RequestTimeout  = TimeSpan.FromSeconds(60);
            var JSONData        = new JObject();
            var values          = new String[0];

            foreach (var key in Data.AllKeys)
            {
                values = Data.GetValues(key);

                if (values.Length == 1)
                {
                    JSONData[key] = values[0];
                }

                if (values.Length > 1)
                {
                    JSONData[key] = new JArray(values);
                }
            }

            MemoryStream         response       = new MemoryStream();
            SMSAPIResponseStatus responseStatus = null;

            #endregion

            #region Send OnSendSMSAPIRequest event

            var StartTime = DateTime.UtcNow;

            try
            {
                if (OnSendSMSAPIRequest != null)
                {
                    await Task.WhenAll(OnSendSMSAPIRequest.GetInvocationList().
                                       Cast <OnSendSMSAPIRequestDelegate>().
                                       Select(e => e(StartTime,
                                                     this,
                                                     EventTrackingId,
                                                     Command,
                                                     JSONData,
                                                     RequestTimeout))).
                    ConfigureAwait(false);
                }
            }
            catch (Exception e)
            {
                e.Log(nameof(SMSAPIClient) + "." + nameof(OnSendSMSAPIRequest));
            }

            #endregion


            try
            {
                var boundary = "SMSAPI-" + DateTime.Now.ToString("yyyy-MM-dd_HH:mm:ss") + new Random().Next(int.MinValue, int.MaxValue).ToString() + "-boundary";

                var webRequest = WebRequest.Create(RemoteURL.ToString() + Command);
                webRequest.Method = HTTPMethod.RequestMethodToString();

                if (BasicAuthentication != null)
                {
                    webRequest.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(BasicAuthentication.Username + ":" + BasicAuthentication.Password)));
                }

                #region POST | PUT

                if (RequestMethods.POST.Equals(HTTPMethod) || RequestMethods.PUT.Equals(HTTPMethod))
                {
                    Stream stream;

                    if (Files != null && Files.Count > 0)
                    {
                        webRequest.ContentType = "multipart/form-data; boundary=" + boundary;
                        stream = PrepareMultipartContent(boundary, Data, Files);
                    }

                    else
                    {
                        webRequest.ContentType = "application/x-www-form-urlencoded";
                        stream = PrepareContent(Data);
                    }

                    webRequest.ContentLength = stream.Length;

                    try
                    {
                        stream.Position = 0;
                        CopyStream(stream, webRequest.GetRequestStream());
                        stream.Close();
                    }
                    catch (WebException e)
                    {
                        throw new HTTPClientException(e.Message, e);
                    }
                }

                #endregion

                try
                {
                    CopyStream((await webRequest.GetResponseAsync()).GetResponseStream(), response);
                }
                catch (WebException e)
                {
                    throw new HTTPClientException("Failed to get response from " + webRequest.RequestUri.ToString(), e);
                }

                response.Position = 0;

                responseStatus = ResponseToObject <SMSAPIResponseStatus>(response);
            }
            catch (Exception e)
            {
                responseStatus = SMSAPIResponseStatus.Failed(e);
            }


            #region Send OnSendSMSAPIResponse event

            var Endtime = DateTime.UtcNow;

            try
            {
                if (OnSendSMSAPIResponse != null)
                {
                    await Task.WhenAll(OnSendSMSAPIResponse.GetInvocationList().
                                       Cast <OnSendSMSAPIResponseDelegate>().
                                       Select(e => e(Endtime,
                                                     this,
                                                     EventTrackingId,
                                                     Command,
                                                     JSONData,
                                                     RequestTimeout,
                                                     responseStatus,
                                                     Endtime - StartTime))).
                    ConfigureAwait(false);
                }
            }
            catch (Exception e)
            {
                e.Log(nameof(SMSAPIClient) + "." + nameof(OnSendSMSAPIResponse));
            }

            #endregion

            return(response);
        }
        public dynamic Get(string companyName)
        {
            if (CheckClientSecret())
            {
                string customerID;

                try
                {
                    using (Entities db = new Entities())
                    {
                        customerID = AliasMethods.GetAlias(companyName, db, "GoogleAdsCustomerID");
                    }
                }
                catch
                {
                    return(new ArgumentException($"No ID found for the company {companyName}"));
                }

                GoogleAdsClient client = new GoogleAdsClient();

                // Get the GoogleAdsService.
                GoogleAdsServiceClient googleAdsService = client.GetService(Services.V4.GoogleAdsService);

                string query = "SELECT "
                               + "account_budget.approved_spending_limit_micros, "
                               + "account_budget.proposed_spending_limit_micros, "
                               + "account_budget.approved_start_date_time, "
                               + "account_budget.proposed_start_date_time, "
                               + "account_budget.approved_end_date_time, "
                               + "account_budget.proposed_end_date_time, "
                               + "account_budget.amount_served_micros "
                               + "FROM account_budget";

                try
                {
                    RepeatedField <GoogleAdsRow> results = RequestMethods.SearchRequest(customerID, query, googleAdsService);

                    if (results.Any())
                    {
                        List <GoogleAdsBudgetDTO> resultsDTO = new List <GoogleAdsBudgetDTO>();

                        for (int i = 0; i < results.Count; i++)
                        {
                            resultsDTO.Add(new GoogleAdsBudgetDTO(results[i]));
                        }

                        return(resultsDTO);
                    }
                    else
                    {
                        return(JsonConvert.SerializeObject("No results were found"));
                    }
                }
                catch (GoogleAdsException e)
                {
                    Debug.WriteLine("Failure:");
                    Debug.WriteLine($"Message: {e.Message}");
                    Debug.WriteLine($"Failure: {e.Failure}");
                    Debug.WriteLine($"Request ID: {e.RequestId}");
                    throw;
                }
            }
            else
            {
                return(new HttpResponseMessage(System.Net.HttpStatusCode.Forbidden));
            }
        }
Beispiel #15
0
        public async Task ProcessRequest(HttpContext context, ISecureSession session)
        {
            string         url      = Utility.CleanURL(Utility.BuildURL(context));
            RequestMethods method   = (RequestMethods)Enum.Parse(typeof(RequestMethods), context.Request.Method.ToUpper());
            Hashtable      formData = new Hashtable();

            if (context.Request.ContentType != null &&
                (
                    context.Request.ContentType == "application/x-www-form-urlencoded" ||
                    context.Request.ContentType.StartsWith("multipart/form-data")
                ))
            {
                foreach (string key in context.Request.Form.Keys)
                {
                    if (key.EndsWith(":json"))
                    {
                        if (context.Request.Form[key].Count > 1)
                        {
                            ArrayList al = new ArrayList();
                            foreach (string str in context.Request.Form[key])
                            {
                                al.Add(JSON.JsonDecode(str));
                            }
                            formData.Add(key.Substring(0, key.Length - 5), al);
                        }
                        else
                        {
                            formData.Add(key.Substring(0, key.Length - 5), JSON.JsonDecode(context.Request.Form[key][0]));
                        }
                    }
                    else
                    {
                        if (context.Request.Form[key].Count > 1)
                        {
                            ArrayList al = new ArrayList();
                            foreach (string str in context.Request.Form[key])
                            {
                                al.Add(str);
                            }
                            formData.Add(key, al);
                        }
                        else
                        {
                            formData.Add(key, context.Request.Form[key][0]);
                        }
                    }
                }
            }
            else
            {
                string tmp = await new StreamReader(context.Request.Body).ReadToEndAsync();
                if (tmp != "")
                {
                    formData = (Hashtable)JSON.JsonDecode(tmp);
                }
            }
            bool found = false;

            foreach (IRequestHandler handler in _Handlers)
            {
                if (handler.HandlesRequest(url, method))
                {
                    found = true;
                    try
                    {
                        await handler.HandleRequest(url, method, formData, context, session, new IsValidCall(_ValidCall));
                    }
                    catch (CallNotFoundException cnfe)
                    {
                        context.Response.ContentType = "text/text";
                        context.Response.StatusCode  = 400;
                        await context.Response.WriteAsync(cnfe.Message);
                    }
                    catch (InsecureAccessException iae)
                    {
                        context.Response.ContentType = "text/text";
                        context.Response.StatusCode  = 403;
                        await context.Response.WriteAsync(iae.Message);
                    }
                    catch (Exception e)
                    {
                        context.Response.ContentType = "text/text";
                        context.Response.StatusCode  = 500;
                        await context.Response.WriteAsync("Error");
                    }
                }
            }
            if (!found)
            {
                context.Response.ContentType = "text/text";
                context.Response.StatusCode  = 404;
                await context.Response.WriteAsync("Not Found");
            }
        }
Beispiel #16
0
 public string GetResponse(string uri, ICollection<KeyValuePair<string, string>> parameters, RequestMethods method = RequestMethods.POST)
 {
     return GetResponse(uri, EncodeParameters(parameters), method);
 }
        public dynamic Get(string companyName)
        {
            if (CheckClientSecret())
            {
                string customerID;

                try
                {
                    using (Entities db = new Entities())
                    {
                        customerID = AliasMethods.GetAlias(companyName, db, "GoogleAdsCustomerID");
                    }
                }
                catch
                {
                    return(new ArgumentException($"No ID found for the company {companyName}"));
                }

                GoogleAdsClient client = new GoogleAdsClient();

                // Get the GoogleAdsService.
                GoogleAdsServiceClient googleAdsService = client.GetService(
                    Services.V4.GoogleAdsService);



                string query = "SELECT "
                               + "campaign.id, "
                               + "campaign.name, "
                               + "campaign.start_date, "
                               + "campaign.end_date, "
                               + "metrics.impressions, "
                               + "metrics.clicks, "
                               + "metrics.conversions_value, "
                               + "metrics.conversions, "
                               + "metrics.cost_micros "
                               + "FROM campaign "
                               + "WHERE campaign.serving_status='SERVING' "
                               + "AND segments.date DURING THIS_MONTH "
                               + "ORDER BY metrics.impressions DESC";

                string lastMonthQuery = "SELECT "
                                        + "metrics.conversions_value, "
                                        + "metrics.conversions,"
                                        + "metrics.cost_micros "
                                        + "FROM campaign "
                                        + "WHERE segments.date DURING LAST_MONTH ";

                try
                {
                    RepeatedField <GoogleAdsRow> results = RequestMethods.SearchRequest(customerID, query, googleAdsService);

                    if (results.Any())
                    {
                        List <GoogleAdsCampaignDTO> campaignsDTO = new List <GoogleAdsCampaignDTO>();

                        double?totalSpend       = 0;
                        double?totalValue       = 0;
                        double?totalConversions = 0;
                        double?rOAS             = 0;

                        for (int i = 0; i < results.Count; i++)
                        {
                            campaignsDTO.Add(new GoogleAdsCampaignDTO(results[i]));

                            totalSpend       += results[i].Metrics.CostMicros;
                            totalValue       += results[i].Metrics.ConversionsValue;
                            totalConversions += results[i].Metrics.Conversions;
                        }

                        double?totalSpendPounds = totalSpend / 1000000;

                        if (totalValue != 0 && totalSpendPounds != 0)
                        {
                            rOAS = totalValue / totalSpendPounds;
                        }

                        RepeatedField <GoogleAdsRow> lastMonthResults = RequestMethods.SearchRequest(customerID, lastMonthQuery, googleAdsService);

                        if (lastMonthResults.Any())
                        {
                            double?lMTotalSpend       = 0;
                            double?lMTotalValue       = 0;
                            double?lMTotalConversions = 0;
                            double?lMROAS             = 0;

                            for (int i = 0; i < lastMonthResults.Count; i++)
                            {
                                lMTotalSpend       += lastMonthResults[i].Metrics.CostMicros;
                                lMTotalValue       += lastMonthResults[i].Metrics.ConversionsValue;
                                lMTotalConversions += lastMonthResults[i].Metrics.Conversions;
                            }

                            double?lMTotalSpendPounds = lMTotalSpend / 1000000;

                            if (lMTotalValue != 0 && lMTotalSpendPounds != 0)
                            {
                                lMROAS = lMTotalValue / lMTotalSpendPounds;
                            }

                            return(new GoogleAdsCampaignSummaryDTO(campaignsDTO, totalSpendPounds, totalConversions, totalValue, rOAS, lMROAS));
                        }
                        else
                        {
                            return(new GoogleAdsCampaignSummaryDTO(campaignsDTO, totalSpend / 1000000, totalConversions, totalValue, rOAS, 0));
                        }
                    }
                    else
                    {
                        return(JsonConvert.SerializeObject("No results were found"));
                    }
                }
                catch (GoogleAdsException e)
                {
                    Debug.WriteLine("Failure:");
                    Debug.WriteLine($"Message: {e.Message}");
                    Debug.WriteLine($"Failure: {e.Failure}");
                    Debug.WriteLine($"Request ID: {e.RequestId}");
                    throw;
                }
            }
            else
            {
                return(new HttpResponseMessage(System.Net.HttpStatusCode.Forbidden));
            }
        }
        /// <summary>
        /// Perform generic API calling
        /// </summary>
        /// <param name="methodURL">IssueTracker method URL</param>
        /// <param name="data">Generic data</param>
        /// <param name="attachments">List of file paths (optional)</param>
        /// <param name="update">flag to indicate if this is a  PUT operation</param>
        /// <returns>the JSON string returned from server</returns>
        private string api(string methodURL, RequestMethods request_method,
            List<KeyValuePair<string, string>> data = null, List<string> attachments = null)
        {
            string url = baseURL + methodURL;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Headers.Add("Authorization: Basic " + auth);
            request.Method = request_method.ToString();

            if (data != null || attachments != null)
            {
                byte[] formData = null;

                if (attachments == null)
                {
                    request.ContentType = "application/x-www-form-urlencoded";

                    var postParams = new List<string>();

                    foreach (KeyValuePair<string, string> item in data)
                    {
                        postParams.Add(String.Format("{0}={1}", item.Key, Uri.EscapeUriString(item.Value)));
                    }

                    string postQuery = String.Join("&", postParams.ToArray());
                    formData = Encoding.UTF8.GetBytes(postQuery);
                    request.ContentLength = formData.Length;

                    using (var requestStream = request.GetRequestStream())
                    {
                        requestStream.Write(formData, 0, formData.Length);
                        requestStream.Flush();
                    }
                }
                else
                {
                    var boundary = "------------------------" + DateTime.Now.Ticks;
                    var newLine = Environment.NewLine;

                    request.ContentType = "multipart/form-data; boundary=" + boundary;

                    using (var requestStream = request.GetRequestStream())
                    {
                        #region Stream data to request

                        var fieldTemplate = newLine + "--" + boundary + newLine + "Content-Type: text/plain" +
                            newLine + "Content-Disposition: form-data;name=\"{0}\"" + newLine + newLine + "{1}";

                        var fieldData = "";

                        foreach (KeyValuePair<string, string> item in data)
                        {
                            fieldData += String.Format(fieldTemplate, item.Key, item.Value);
                        }

                        var fieldBytes = Encoding.UTF8.GetBytes(fieldData);
                        requestStream.Write(fieldBytes, 0, fieldBytes.Length);

                        #endregion

                        #region Stream files to request

                        var fileInfoTemplate = newLine + "--" + boundary + newLine + "Content-Disposition: filename=\"{0}\"" +
                            newLine + "Content-Type: {1}" + newLine + newLine;

                        foreach (var path in attachments)
                        {
                            using (var reader = new BinaryReader(File.OpenRead(path)))
                            {
                                #region Stream file info

                                var fileName = Path.GetFileName(path);
                                var fileInfoData = String.Format(fileInfoTemplate, fileName, getMimeType(fileName));
                                var fileInfoBytes = Encoding.UTF8.GetBytes(fileInfoData);

                                requestStream.Write(fileInfoBytes, 0, fileInfoBytes.Length);

                                #endregion

                                #region Stream file

                                using (var fileStream = new FileStream(path, FileMode.Open, FileAccess.Read))
                                {
                                    byte[] buffer = new byte[4096];
                                    var fileBytesRead = 0;

                                    while ((fileBytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
                                    {
                                        requestStream.Write(buffer, 0, fileBytesRead);
                                    }
                                }

                                #endregion
                            }
                        }

                        var trailer = Encoding.ASCII.GetBytes(newLine + "--" + boundary + "--");
                        requestStream.Write(trailer, 0, trailer.Length);

                        #endregion
                    }
                }
            }

            try
            {
                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
                    using (Stream responseStream = response.GetResponseStream())
                    {
                        using (StreamReader reader = new StreamReader(responseStream))
                        {
                            return reader.ReadToEnd();
                        }
                    }
                }
            }
            catch (WebException wex)
            {
                var response = (HttpWebResponse)wex.Response;

                string message = "An API error occurred.";

                if (response == null)
                {
                    throw new APIException(message, null);
                }

                var code = response.StatusCode;

                using (Stream responseStream = response.GetResponseStream())
                {
                    using (StreamReader reader = new StreamReader(responseStream))
                    {
                        message = reader.ReadToEnd();
                    }
                }

                throw new APIException(message, response);
            }
            catch (Exception e)
            {
                return e.Message;
            }
        }
Beispiel #19
0
 public Task <Stream> Execute(string Command, NameValueCollection Data, Dictionary <string, Stream> Files = null, RequestMethods HTTPMethod = RequestMethods.POST)
 {
     throw new NotImplementedException();
 }
Beispiel #20
0
 private string OnRequestFile(string message, string requestId, out string error)
 => RequestMethods.RequestFile((args) => RequestData?.Invoke(this, args), message, requestId, out error);
 private long OnRequestNumber(string message, long defaultValue, out string error)
 => RequestMethods.RequestNumber((args) => RequestData?.Invoke(this, args), message, defaultValue, out error);
Beispiel #22
0
        internal static HttpWebRequest BuildRequest(Endpoints endpoint, string[,] parameters, RequestMethods method = RequestMethods.POST)
        {
            string targetURL  = string.Format(APIUrl, EndpointHelper.Parse(endpoint));
            string targetVerb = "";

            if (parameters != null)
            {
                for (int i = 0; i < parameters.GetLength(0); i++)
                {
                    targetVerb += (i == 0 ? "?" : "&") + parameters[i, 0] + "=" + Uri.EscapeDataString(parameters[i, 1]);
                }
            }

            HttpWebRequest req = null;

            switch (method)
            {
            case RequestMethods.GET:
                req        = WebRequest.CreateHttp(targetURL + targetVerb);
                req.Method = "GET";
                break;

            case RequestMethods.POST:
                req             = WebRequest.CreateHttp(targetURL);
                req.Method      = "POST";
                req.ContentType = "application/x-www-form-urlencoded";

                byte[] data = Encoding.UTF8.GetBytes(targetVerb);
                using (Stream reqStream = Task <Stream> .Factory.FromAsync(req.BeginGetRequestStream, req.EndGetRequestStream, null).Result)
                    reqStream.Write(data, 0, data.Length);
                break;
            }

            return(req);
        }
Beispiel #23
0
 public static IRequestMethod GetByName(string name)
 {
     name = name.ToUpper();
     return(RequestMethods.FirstOrDefault(r => r.Name.Equals(name, StringComparison.OrdinalIgnoreCase)));
 }
Beispiel #24
0
 private byte[] OnRequestKey(string message, int keyLength, out string error)
 => RequestMethods.RequestKey((args) => RequestData?.Invoke(this, args), message, keyLength, out error);
Beispiel #25
0
        /// <summary>
        /// Initializes a new instance of the HTTPMethod class
        /// </summary>
        /// <param name="Line">the line to parse</param>
        public HTTPMethod(string Line)
        {
            if (Line == null)
            {
                //Not good
                throw new ArgumentNullException("Line");
            }

            //Parse line
            Line = Line.Trim();
            string[] words = Line.Split(new char[] { ' ' }, StringSplitOptions.None);

            if (words.Length > 0)
            {
                switch (words[0].ToUpperInvariant())
                {
                    case "GET":
                        RequestMethod = RequestMethods.Get;
                        Type = HTTPMessageType.Request;
                        break;
                    case "PUT":
                        RequestMethod = RequestMethods.Put;
                        Type = HTTPMessageType.Request;
                        break;
                    case "DELETE":
                        RequestMethod = RequestMethods.Delete;
                        Type = HTTPMessageType.Request;
                        break;
                    case "HEAD":
                        RequestMethod = RequestMethods.Head;
                        Type = HTTPMessageType.Request;
                        break;
                    default:
                        RequestMethod = RequestMethods.Unknown;

                        int res;
                        if (int.TryParse(words[0], out res) ||
                            (words.Length > 1 && (words[0] == "HTTP/1.0" || words[0] == "HTTP/1.1") && int.TryParse(words[1], out res))
                            )
                        {
                            ResponseCode = res;
                            Type = HTTPMessageType.Response;
                        }

                        break;
                }

                if (words.Length > 2 && words[words.Length - 1] == "HTTP/1.1")
                {
                    Resource = string.Join(" ", words, 1, words.Length - 2).Trim();

                }
                else if (words.Length > 2 || (words[words.Length - 1] != "HTTP/1.1" && words.Length > 1))
                {
                    Resource = string.Join(" ", words, 1, words.Length - 1).Trim();
                }
                else
                {
                    Resource = string.Empty;
                }

            }
            else
            {
                throw new ArgumentException("Empty Line", "Line");
            }
        }