public void GetParametersString_AnonymousData_CorrectString(List<KeyValuePair<string, string>> parameters, HttpUtils sut)
        {
            var expectedValue = string.Concat(parameters.OrderBy(a => a.Key).Select(a => $"{a.Key}={a.Value}"));

            var result = sut.GetParametersString(parameters);

            result.Should().Be(expectedValue);
        }
        public void GenerateTimeStamp_ValidTimeStamp(HttpUtils sut)
        {
            var currentTime = DateTime.UtcNow - new DateTime(1970, 1, 1);

            var timestamp = sut.GenerateTimeStamp();

            var value = long.Parse(timestamp);
            value.Should().BeInRange(Convert.ToInt64(currentTime.TotalSeconds), Convert.ToInt64(currentTime.TotalSeconds) + 1);
        }
        public void GenerateNonce_ValidNonce(HttpUtils sut)
        {
            var previous = string.Empty;

            for (var i = 0; i < 5; i++)
            {
                var current = sut.GenerateNonce();
                current.Should().NotBe(previous);
            }
        }
        public void GetParametersString_AnonymousDataWithDevimeter_CorrectString(
            string firstParameter,
            string secondParameter,
            HttpUtils sut)
        {
            var parameters = new[] {
                new KeyValuePair<string, string>("a", firstParameter),
                new KeyValuePair<string, string>("a", secondParameter),
            };
            var expectedValue = $"{parameters[0].Key}={parameters[0].Value}&{parameters[1].Key}={parameters[1].Value}";

            var result = sut.GetParametersString(parameters, "&");

            result.Should().Be(expectedValue);
        }
Пример #5
0
 public RediffImporter()
 {
     httpUtils = new HttpUtils();
 }
Пример #6
0
 private IEnumerable <BasicKeyValuePair> GetCookiesToProxy(IEnumerable <BasicKeyValuePair> cookiesToProxy)
 {
     return(HttpUtils.ProxyRequiredCookies(RequiredCookies.Discovery, cookiesToProxy));
 }
 public OneSixthreeImporter()
 {
     httpUtils = new HttpUtils();
 }
 public LinkedInImporter()
 {
     httpUtils = new HttpUtils();
 }
Пример #9
0
 public PlaxoImporter()
 {
     httpUtils = new HttpUtils();
 }
Пример #10
0
 public ServiceRegistry(Func <HttpClient> httpClientFactory = null, ILoggerFactory loggerFactory = null, IConsulAclProvider aclProvider = null)
 {
     _logger = loggerFactory?.CreateLogger <ServiceRegistry>();
     _client = httpClientFactory?.Invoke() ?? HttpUtils.CreateClient(aclProvider);
 }
 public void ReciprocatePeerAdd(Peer otherPeer)
 {
     HttpUtils.DoApiPost <Peer, object>(otherPeer.Url, ADD_PEER_API_PATH, thisPeer);
 }
Пример #12
0
 public LXWebSocket(LXUri baseUri, IEncryptorProvider encryptorProvider, IConnection connection, CancellationToken ct) : base(HttpUtils.MakeWebSocketUri(baseUri), ct)
 {
     this._encryptorProvider = encryptorProvider;
     this._connection        = connection;
     this._httpClient        = new LXHttpClient(HttpUtils.MakeHttpUri(baseUri), ct);
 }
Пример #13
0
        /// <summary>
        /// <see cref="Sif.Framework.Service.Registration.IRegistrationService.Register(Sif.Framework.Model.Infrastructure.Environment)">Register</see>
        /// </summary>
        public void Register(ref Environment environment)
        {
            if (!Registered)
            {
                if (sessionService.HasSession(environment.ApplicationInfo.ApplicationKey, environment.SolutionId, environment.UserToken, environment.InstanceId))
                {
                    if (log.IsDebugEnabled)
                    {
                        log.Debug("Session token already exists for this object service (Consumer/Provider).");
                    }

                    string storedSessionToken = sessionService.RetrieveSessionToken(environment.ApplicationInfo.ApplicationKey, environment.SolutionId, environment.UserToken, environment.InstanceId);
                    AuthorisationToken = AuthenticationUtils.GenerateBasicAuthorisationToken(storedSessionToken, settings.SharedSecret);
                    string storedEnvironmentUrl = sessionService.RetrieveEnvironmentUrl(environment.ApplicationInfo.ApplicationKey, environment.SolutionId, environment.UserToken, environment.InstanceId);
                    string environmentXml       = HttpUtils.GetRequest(storedEnvironmentUrl, AuthorisationToken);

                    if (log.IsDebugEnabled)
                    {
                        log.Debug("Environment XML from GET request ...");
                    }
                    if (log.IsDebugEnabled)
                    {
                        log.Debug(environmentXml);
                    }

                    environmentType environmentTypeToDeserialise = SerialiserFactory.GetXmlSerialiser <environmentType>().Deserialise(environmentXml);
                    Environment     environmentResponse          = MapperFactory.CreateInstance <environmentType, Environment>(environmentTypeToDeserialise);

                    sessionToken   = environmentResponse.SessionToken;
                    environmentUrl = environmentResponse.InfrastructureServices[InfrastructureServiceNames.environment].Value;

                    if (log.IsDebugEnabled)
                    {
                        log.Debug("Environment URL is " + environmentUrl + ".");
                    }

                    if (!storedSessionToken.Equals(sessionToken) || !storedEnvironmentUrl.Equals(environmentUrl))
                    {
                        AuthorisationToken = AuthenticationUtils.GenerateBasicAuthorisationToken(sessionToken, settings.SharedSecret);
                        sessionService.RemoveSession(storedSessionToken);
                        sessionService.StoreSession(environmentResponse.ApplicationInfo.ApplicationKey, sessionToken, environmentUrl, environmentResponse.SolutionId, environmentResponse.UserToken, environmentResponse.InstanceId);
                    }

                    environment = environmentResponse;
                }
                else
                {
                    if (log.IsDebugEnabled)
                    {
                        log.Debug("Session token does not exist for this object service (Consumer/Provider).");
                    }

                    string          initialToken = AuthenticationUtils.GenerateBasicAuthorisationToken(environment.ApplicationInfo.ApplicationKey, settings.SharedSecret);
                    environmentType environmentTypeToSerialise = MapperFactory.CreateInstance <Environment, environmentType>(environment);
                    string          body           = SerialiserFactory.GetXmlSerialiser <environmentType>().Serialise(environmentTypeToSerialise);
                    string          environmentXml = HttpUtils.PostRequest(settings.EnvironmentUrl, initialToken, body);

                    if (log.IsDebugEnabled)
                    {
                        log.Debug("Environment XML from POST request ...");
                    }
                    if (log.IsDebugEnabled)
                    {
                        log.Debug(environmentXml);
                    }

                    try
                    {
                        environmentType environmentTypeToDeserialise = SerialiserFactory.GetXmlSerialiser <environmentType>().Deserialise(environmentXml);
                        Environment     environmentResponse          = MapperFactory.CreateInstance <environmentType, Environment>(environmentTypeToDeserialise);

                        sessionToken   = environmentResponse.SessionToken;
                        environmentUrl = environmentResponse.InfrastructureServices[InfrastructureServiceNames.environment].Value;

                        if (log.IsDebugEnabled)
                        {
                            log.Debug("Environment URL is " + environmentUrl + ".");
                        }

                        AuthorisationToken = AuthenticationUtils.GenerateBasicAuthorisationToken(sessionToken, settings.SharedSecret);
                        sessionService.StoreSession(environment.ApplicationInfo.ApplicationKey, sessionToken, environmentUrl, environmentResponse.SolutionId, environmentResponse.UserToken, environmentResponse.InstanceId);
                        environment = environmentResponse;
                    }
                    catch (Exception)
                    {
                        if (environmentUrl != null)
                        {
                            HttpUtils.DeleteRequest(environmentUrl, AuthorisationToken);
                        }
                        else if (!String.IsNullOrWhiteSpace(TryParseEnvironmentUrl(environmentXml)))
                        {
                            HttpUtils.DeleteRequest(TryParseEnvironmentUrl(environmentXml), AuthorisationToken);
                        }

                        throw;
                    }
                }

                Registered = true;
            }
        }
Пример #14
0
        /// <summary>
        /// Creates a context menu.
        /// </summary>
        /// <param name="parms"></param>
        /// <param name="model"></param>
        /// <param name="webBrowser"></param>
        public void ShowContextMenu(PositionAndDocumentType parms, AppModel model, FrameworkElement webBrowser)
        {
            if (webBrowser == null)
            {
                return;
            }

            var      ctm = new ContextMenu();
            MenuItem mi;

            // Image Selected
            if (!string.IsNullOrEmpty(parms.Src))
            {
                mi = new MenuItem()
                {
                    Header = "Copy Image to Clipboard"
                };
                mi.Click += (o, args) =>
                {
                    string image      = null;
                    bool   deleteFile = false;

                    if (parms.Src.StartsWith("https://") || parms.Src.StartsWith("http://"))
                    {
                        image = HttpUtils.DownloadImageToFile(parms.Src);
                        if (string.IsNullOrEmpty(image))
                        {
                            model.Window.ShowStatusError("Unable to copy image from URL to clipboard: " + parms.Src);
                            return;
                        }
                        deleteFile = true;
                    }
                    else
                    {
                        try
                        {
                            image = new Uri(parms.Src).LocalPath;
                        }
                        catch
                        {
                            image = FileUtils.NormalizePath(parms.Src);
                        }

                        image = mmFileUtils.NormalizeFilenameWithBasePath(image,
                                                                          Path.GetDirectoryName(model.ActiveDocument.Filename));
                    }

                    try
                    {
                        BitmapSource bmpSrc;
                        using (var bmp = new Bitmap(image))
                        {
                            bmpSrc = WindowUtilities.BitmapToBitmapSource(bmp);
                            Clipboard.SetImage(bmpSrc);
                        }

                        model.Window.ShowStatusSuccess("Image copied to clipboard.");
                    }
                    catch (Exception ex)
                    {
                        model.Window.ShowStatusError("Couldn't copy image to clipboard: " + ex.Message);
                    }
                    finally
                    {
                        if (deleteFile && File.Exists(image))
                        {
                            File.Delete(image);
                        }
                    }
                };
                ctm.Items.Add(mi);

                mi = new MenuItem()
                {
                    Header = "Edit Image in Image editor"
                };
                mi.Click += (o, args) =>
                {
                    string image = null;
                    if (parms.Src.StartsWith("https://") || parms.Src.StartsWith("http://"))
                    {
                        image = HttpUtils.DownloadImageToFile(parms.Src);
                        if (string.IsNullOrEmpty(image))
                        {
                            model.Window.ShowStatusError("Unable to copy image from URL to clipboard: " + parms.Src);
                            return;
                        }
                    }
                    else
                    {
                        try
                        {
                            image = new Uri(parms.Src).LocalPath;
                        }
                        catch
                        {
                            image = FileUtils.NormalizePath(parms.Src);
                        }
                        image = mmFileUtils.NormalizeFilenameWithBasePath(image, Path.GetDirectoryName(model.ActiveDocument.Filename));
                    }

                    mmFileUtils.OpenImageInImageEditor(image);
                };
                ctm.Items.Add(mi);

                ctm.Items.Add(new Separator());
            }


            // HREF link selected
            if (!string.IsNullOrEmpty(parms.Href))
            {
                // Navigate relative hash links in the document
                if (parms.Href.StartsWith("#") && parms.Href.Length > 1)
                {
                    var docModel = new DocumentOutlineModel();
                    int lineNo   = docModel.FindHeaderHeadline(model.ActiveEditor?.GetMarkdown(), parms.Href?.Substring(1));
                    if (lineNo > -1)
                    {
                        mi = new MenuItem()
                        {
                            Header = "Jump to: " + parms.Href, CommandParameter = parms.Href.Substring(1)
                        };
                        mi.Click += (s, e) =>
                        {
                            var mitem = s as MenuItem;

                            var anchor = mitem.CommandParameter as string;
                            if (string.IsNullOrEmpty(anchor))
                            {
                                return;
                            }

                            docModel = new DocumentOutlineModel();
                            lineNo   = docModel.FindHeaderHeadline(model.ActiveEditor?.GetMarkdown(), anchor);

                            if (lineNo != -1)
                            {
                                model.ActiveEditor.GotoLine(lineNo);
                            }
                        };
                        ctm.Items.Add(mi);

                        ctm.Items.Add(new Separator());
                    }
                }
            }

            // ID to clipboard
            if (!string.IsNullOrEmpty(parms.Id))
            {
                mi = new MenuItem()
                {
                    Header = "Copy Id to Clipboard: #" + parms.Id,
                };
                mi.Click += (s, e) =>
                {
                    ClipboardHelper.SetText("#" + parms.Id);
                    model.Window.ShowStatusSuccess("'#" + parms.Id + "' copied to the clipboard.");
                };
                ctm.Items.Add(mi);

                ctm.Items.Add(new Separator());
            }


            mi = new MenuItem()
            {
                Header           = "View in Web _Browser",
                Command          = model.Commands.ViewInExternalBrowserCommand,
                InputGestureText = model.Commands.ViewInExternalBrowserCommand.KeyboardShortcut
            };
            ctm.Items.Add(mi);

            mi = new MenuItem()
            {
                Header           = "Refresh _Browser",
                Command          = model.Commands.RefreshPreviewCommand,
                InputGestureText = "F5"
            };
            ctm.Items.Add(mi);

            mi = new MenuItem()
            {
                Header  = "View Html _Source",
                Command = model.Commands.ViewHtmlSourceCommand
            };
            ctm.Items.Add(mi);

            ctm.Items.Add(new Separator());


            mi = new MenuItem()
            {
                Header  = "Save As _Html",
                Command = model.Commands.SaveAsHtmlCommand,
            };
            ctm.Items.Add(mi);

            mi = new MenuItem()
            {
                Header  = "Save As _PDF",
                Command = model.Commands.GeneratePdfCommand,
            };
            ctm.Items.Add(mi);

            mi = new MenuItem()
            {
                Header  = "P_rint...",
                Command = model.Commands.PrintPreviewCommand,
            };
            ctm.Items.Add(mi);

            ctm.Items.Add(new Separator());

            mi = new MenuItem()
            {
                Header  = "Edit Preview _Theme",
                Command = model.Commands.EditPreviewThemeCommand,
            };
            ctm.Items.Add(mi);

            mi = new MenuItem()
            {
                Header  = "Configure Preview Syncing",
                Command = model.Commands.PreviewSyncModeCommand,
            };
            ctm.Items.Add(mi);

            ctm.Items.Add(new Separator());


            mi = new MenuItem()
            {
                Header           = "Toggle Preview Window",
                Command          = model.Commands.TogglePreviewBrowserCommand,
                CommandParameter = "Toggle",
                InputGestureText = model.Commands.TogglePreviewBrowserCommand.KeyboardShortcut,
                IsCheckable      = true,
                IsChecked        = model.IsPreviewBrowserVisible
            };
            ctm.Items.Add(mi);

            if (model.Configuration.System.ShowPreviewDeveloperTools)
            {
                ctm.Items.Add(new Separator());
                mi = new MenuItem()
                {
                    Header = "Show Browser Developer Tools"
                };
                mi.Click += (s, a) => model.Window.PreviewBrowser.ShowDeveloperTools();
                ctm.Items.Add(mi);
            }

            webBrowser.ContextMenu = ctm;
            ContextMenuOpening?.Invoke(this, ctm);

            ctm.Placement       = System.Windows.Controls.Primitives.PlacementMode.MousePoint;
            ctm.PlacementTarget = webBrowser;
            ctm.IsOpen          = true;
        }
Пример #15
0
 public GroupsApi(HttpUtils http) : base(http, "/groups")
 {
 }
Пример #16
0
 /// <summary>
 /// 重写获取用户信息方法
 /// </summary>
 /// <param name="authToken"></param>
 /// <returns></returns>
 protected override string doGetUserInfo(AuthToken authToken)
 {
     return(HttpUtils.RequestJsonGet(userInfoUrl(authToken)));
 }
 public RamblerruImporter()
 {
     httpUtils=new HttpUtils();
 }
Пример #18
0
        protected override AuthUser getUserInfo(AuthToken authToken)
        {
            // 获取商户账号信息的API接口名称
            String action = "eleme.user.getUser";
            // 时间戳,单位秒。API服务端允许客户端请求最大时间误差为正负5分钟。
            long timestamp = DateTime.Now.Ticks;
            // 公共参数
            var metasHashMap = new Dictionary <string, object>();

            metasHashMap.Add("app_key", config.clientId);
            metasHashMap.Add("timestamp", timestamp);
            string signature = this.generateElemeSignature(timestamp, action, authToken.accessToken);
            string requestId = this.getRequestId();

            var paramsMap = new Dictionary <string, object>
            {
                { "nop", "1.0.0" },
                { "id", requestId },
                { "action", action },
                { "token", authToken.accessToken },
                { "metas", JsonConvert.SerializeObject(metasHashMap) },
                { "params", "{}" },
                { "signature", signature }
            };

            var reqHeaders = new Dictionary <string, object>
            {
                { "Content-Type", "application/json; charset=utf-8" },
                { "Accept", "text/xml,text/javascript,text/html" },
                { "Accept-Encoding", "gzip" },
                { "User-Agent", "eleme-openapi-java-sdk" },
                { "x-eleme-requestid", requestId },
                { "Authorization", this.spliceBasicAuthStr() }
            };
            var response = HttpUtils.RequestPost(source.userInfo(), JsonConvert.SerializeObject(paramsMap), reqHeaders);

            var resObj = response.parseObject();

            // 校验请求
            if (resObj.ContainsKey("name"))
            {
                throw new Exception(resObj.getString("message"));
            }
            if (resObj.ContainsKey("error") && !resObj.getString("error").IsNullOrWhiteSpace())
            {
                throw new Exception(resObj.getJSONObject("error").getString("message"));
            }

            var userObj = resObj.getJSONObject("result");

            var authUser = new AuthUser
            {
                uuid            = userObj.getString("userId"),
                username        = userObj.getString("userName"),
                nickname        = userObj.getString("userName"),
                gender          = AuthUserGender.UNKNOWN,
                token           = authToken,
                source          = source.getName(),
                originalUser    = resObj,
                originalUserStr = response
            };

            return(authUser);
        }
Пример #19
0
 public MyspaceImporter()
 {
     httpUtils = new HttpUtils();
 }
Пример #20
0
        public static Dictionary <string, object> ArraAwardsForYearQuarterStateTown(string year, string quarter, string state, string town)
        {
            town  = town.ToLower();
            state = state.ToUpper();
            var url = new Uri(String.Format("http://recovery.download.s3-website-us-east-1.amazonaws.com/Y{0}Q{1}/{2}_Y{3}Q{4}.xml.zip",
                                            year, quarter, state, year, quarter));
            var rsp   = HttpUtils.FetchUrl(url);
            var zs    = new MemoryStream(rsp.bytes);
            var zip   = ZipFile.Read(zs);
            var ms    = new MemoryStream();
            var entry = zip.Entries[0];

            entry.Extract(ms);
            ms.Seek(0, 0);
            byte[] data = new byte[entry.UncompressedSize];
            Utils.ReadWholeArray(ms, data);
            var doc = XmlUtils.XdocFromXmlBytes(data);

            var awards = from row in doc.Descendants("Table")
                         where row.Element("pop_city") != null && row.Element("pop_city").Value.ToLower() == town
                         orderby float.Parse(row.Element("local_amount").Value) descending
                         select new ArraData(
                ArraValue(row.Element("award_description")),
                ArraValue(row.Element("local_amount")),
                ArraValue(row.Element("project_name")),
                ArraValue(row.Element("project_description")),
                ArraValue(row.Element("project_status")),
                ArraValue(row.Element("funding_agency_name")),
                ArraValue(row.Element("recipient_name")),
                ArraValue(row.Element("award_date")),
                ArraValue(row.Element("infrastructure_contact_nm")),
                ArraValue(row.Element("infrastructure_contact_email")),
                ArraValue(row.Element("award_number"))
                );


            var dict = new Dictionary <string, object>();

            dict["awards"]      = awards.ToList();
            dict["award_count"] = awards.Count();

            var awards_with_desc = from row in awards
                                   where (string)row.award_description != "-"
                                   select new { row };

            dict["awards_with_desc"] = awards_with_desc.Count();

            dict["awards_without_desc"] = (int)dict["award_count"] - (int)dict["awards_with_desc"];

            var amounts = from row in awards
                          select float.Parse(row.award_amount.ToString());

            dict["awards_sum"] = amounts.Sum();

            var amounts_with_desc = from row in awards_with_desc
                                    select float.Parse(row.row.award_amount.ToString());

            dict["awards_with_desc_sum"] = amounts_with_desc.Sum();

            dict["awards_without_desc_sum"] = (float)dict["awards_sum"] - (float)dict["awards_with_desc_sum"];

            return(dict);
        }
        public void ParseParameterString_ValidUrlParameterString_CorrectResult(List<KeyValuePair<string, string>> parameters, HttpUtils sut)
        {
            var parameterString = "?" + sut.GetParametersString(parameters, "&");

            var result = sut.ParseParameterString(parameterString);

            result.ShouldAllBeEquivalentTo(parameters);
        }
Пример #22
0
        /// <summary>
        /// 内部方法:构造URL
        /// </summary>
        /// <returns></returns>
        private string generateURL(string bucketName, string remotePath, string prefix)
        {
            string url = cosApiUrl + this.appId + "/" + bucketName + HttpUtils.EncodeRemotePath(remotePath) + HttpUtility.UrlEncode(prefix);

            return(url);
        }
        public override IHttpActionResult Post(
            Subscription obj,
            [MatrixParameter] string[] zoneId    = null,
            [MatrixParameter] string[] contextId = null)
        {
            if (!AuthenticationService.VerifyAuthenticationHeader(Request.Headers, out string _))
            {
                return(Unauthorized());
            }

            if ((zoneId != null && zoneId.Length != 1) || (contextId != null && contextId.Length != 1))
            {
                return(BadRequest($"Request failed for object {TypeName} as Zone and/or Context are invalid."));
            }

            IHttpActionResult result;

            try
            {
                bool hasAdvisoryId   = !string.IsNullOrWhiteSpace(obj.RefId);
                bool?mustUseAdvisory = HttpUtils.GetMustUseAdvisory(Request.Headers);

                if (mustUseAdvisory.HasValue)
                {
                    if (mustUseAdvisory.Value && !hasAdvisoryId)
                    {
                        result = BadRequest(
                            $"Request failed for object {TypeName} as object ID is not provided, but mustUseAdvisory is true.");
                    }
                    else
                    {
                        Subscription createdObject = Service.Create(obj, mustUseAdvisory, zoneId?[0], contextId?[0]);
                        string       uri           = Url.Link("DefaultApi", new { controller = TypeName, id = createdObject.RefId });
                        result = Created(uri, createdObject);
                    }
                }
                else
                {
                    Subscription createdObject = Service.Create(obj, null, zoneId?[0], contextId?[0]);
                    string       uri           = Url.Link("DefaultApi", new { controller = TypeName, id = createdObject.RefId });
                    result = Created(uri, createdObject);
                }
            }
            catch (AlreadyExistsException)
            {
                result = Conflict();
            }
            catch (ArgumentException e)
            {
                result = BadRequest($"Object to create of type {TypeName} is invalid.\n{e.Message}");
            }
            catch (CreateException e)
            {
                result = BadRequest($"Request failed for object {TypeName}.\n{e.Message}");
            }
            catch (RejectedException)
            {
                result = NotFound();
            }
            catch (QueryException e)
            {
                result = BadRequest($"Request failed for object {TypeName}.\n{e.Message}");
            }
            catch (Exception e)
            {
                result = InternalServerError(e);
            }

            return(result);
        }
Пример #24
0
 /// <summary>
 /// 发送Json
 /// </summary>
 public void SendJons(string strJson)
 {
     HttpUtils.Post("http://localhost:52918/Web/TestJson.aspx", strJson, "");
     Response.Redirect("TestJson.aspx");
 }
 public IndiaTimesImporter()
 {
     httpUtils=new HttpUtils();
 }
Пример #26
0
            public override void ExecuteResult(ControllerContext context)
            {
                // for dynamic views derived from the static file
                // which is the base object for this id, e.g.:
                //  http://elmcity.blob.core.windows.net/a2cal/a2cal.zoneless.obj
                // cache the base object if uncached
                var base_key = Utils.MakeBaseZonelessUrl(this.id);

                if (this.cr.cache[base_key] == null)
                {
                    var bytes = HttpUtils.FetchUrl(new Uri(base_key)).bytes;
                    //InsertIntoCache(bytes, ElmcityUtils.Configurator.cache_sliding_expiration, dependency: null, key: base_key);
                    var cache = new AspNetCache(this.controller.HttpContext.Cache);
                    this.controller.InsertIntoCache(cache, bytes, dependency: null, key: base_key);
                }

                // uri for static content, e.g.:
                // http://elmcity.blob.core.windows.net/a2cal/a2cal.stats.html
                // http://elmcity.blob.core.windows.net/a2cal/a2cal.search.html
                // these generated files could be served using their blob urls, but
                // here are repackaged into the /services namespace, e.g.:
                // http://elmcity.cloudapp.net/services/a2cal/stats
                // http://elmcity.cloudapp.net/services/a2cal/search

                var blob_uri = BlobStorage.MakeAzureBlobUri(this.id, this.id + "." + this.type, false);

                // cache static content
                var blob_key = blob_uri.ToString();

                if (cacheable_types.Exists(t => t == this.type) && this.cr.cache[blob_key] == null)
                {
                    var bytes      = HttpUtils.FetchUrl(blob_uri).bytes;
                    var dependency = new ElmcityCacheDependency(base_key);
                    var cache      = new AspNetCache(this.controller.HttpContext.Cache);
                    this.controller.InsertIntoCache(cache, bytes, dependency, base_key);
                }

                var fmt      = "{0:yyyyMMddTHHmm}";
                var from_str = string.Format(fmt, this.from);
                var to_str   = string.Format(fmt, this.to);

                var render_args = new Dictionary <string, object>();

                var view_key = Utils.MakeViewKey(this.id, this.type, this.view, this.count.ToString(), from_str, to_str, eventsonly: this.eventsonly, mobile: this.mobile, test: this.test, raw: this.raw, style: this.style, theme: this.theme, taglist: this.taglist, tags: this.tags, template: this.template, jsurl: this.jsurl, days: this.days, bare_events: this.bare_events, hub: this.hub, source: this.source, first: this.first.ToString());

                switch (this.type)
                {
                case "html":
                    render_args["view"]            = this.view;
                    render_args["test"]            = this.test;                   // obsolete?
                    render_args["style"]           = this.style;
                    render_args["theme"]           = this.theme;
                    render_args["mobile_detected"] = false;                             // unused for now
                    render_args["ua"]          = "";
                    render_args["css"]         = this.cr.calinfo.css;                   // need to extract and pass along the default theme name
                    render_args["taglist"]     = this.taglist;
                    render_args["template"]    = this.template;
                    render_args["jsurl"]       = this.jsurl;
                    render_args["bare_events"] = this.bare_events;
                    render_args["hub"]         = this.hub;
                    render_args["first"]       = this.first;
                    render_args["eventsonly"]  = this.eventsonly;

                    if (settings["use_mobile_detection"] == "yes")                                                  // detect or use declaration
                    {
                        this.mobile_detected           = TryDetectSmartPhone(render_args);
                        render_args["mobile_detected"] = this.mobile_detected;
                        this.mobile = this.mobile_detected || this.mobile_declared;
                    }
                    else
                    {
                        this.mobile = this.mobile_declared;                                      // use declaration only
                    }
                    if (this.mobile_refused)                                                     // maybe override with refusal
                    {
                        this.mobile = false;
                    }

                    if (this.mobile)
                    {
                        //this.count = Convert.ToInt32(settings["mobile_event_count"]);  // no, let the renderer reduce the list
                        render_args["mobile_event_count"] = Convert.ToInt32(settings["mobile_event_count"]);
                        this.renderer = new CalendarRenderer.ViewRenderer(cr.RenderHtmlForMobile);
                    }
                    else if (this.eventsonly)
                    {
                        this.renderer = new CalendarRenderer.ViewRenderer(cr.RenderHtmlEventsOnly);
                    }
                    else
                    {
                        this.renderer = new CalendarRenderer.ViewRenderer(cr.RenderHtml);
                    }

                    // update for mobile detection
                    view_key = Utils.MakeViewKey(this.id, this.type, this.view, this.count.ToString(), from_str, to_str, eventsonly: this.eventsonly, mobile: this.mobile, test: this.test, raw: this.raw, style: this.style, theme: this.theme, taglist: this.taglist, tags: this.tags, template: this.template, jsurl: this.jsurl, days: this.days, bare_events: this.bare_events, hub: this.hub, source: this.source, first: this.first.ToString());

                    MaybeCacheView(view_key, this.renderer, new ElmcityCacheDependency(base_key), render_args);

                    this.response_body = cr.RenderDynamicViewWithCaching(context, view_key, this.renderer, this.view, this.count, this.from, this.to, this.source, render_args);

                    // let ajax pull events into pages directly
                    this.controller.HttpContext.Response.Headers["Access-Control-Allow-Origin"] = "*";

                    new ContentResult
                    {
                        ContentType     = "text/html",
                        Content         = this.response_body,
                        ContentEncoding = UTF8
                    }.ExecuteResult(context);
                    break;

                case "xml":
                    this.renderer = new CalendarRenderer.ViewRenderer(cr.RenderXml);
                    MaybeCacheView(view_key, this.renderer, new ElmcityCacheDependency(base_key), null);
                    this.response_body = cr.RenderDynamicViewWithCaching(context, view_key, this.renderer, this.view, this.count, this.from, this.to, this.source, null);
                    new ContentResult
                    {
                        ContentType     = "text/xml",
                        Content         = this.response_body,
                        ContentEncoding = UTF8
                    }.ExecuteResult(context);
                    break;

                case "rss":
                    if (count == 0)
                    {
                        count = CalendarAggregator.Configurator.rss_default_items;
                    }
                    this.renderer = new CalendarRenderer.ViewRenderer(cr.RenderRss);
                    MaybeCacheView(view_key, this.renderer, new ElmcityCacheDependency(base_key), null);
                    this.response_body = cr.RenderDynamicViewWithCaching(context, view_key, this.renderer, this.view, this.count, this.from, this.to, this.source, null);

                    new ContentResult
                    {
                        ContentType     = "text/xml",
                        Content         = response_body,
                        ContentEncoding = UTF8
                    }.ExecuteResult(context);
                    break;

                case "json":
                    this.renderer = new CalendarRenderer.ViewRenderer(cr.RenderJson);
                    MaybeCacheView(view_key, this.renderer, new ElmcityCacheDependency(base_key), null);
                    string jcontent = cr.RenderDynamicViewWithCaching(context, view_key, this.renderer, this.view, this.count, this.from, this.to, this.source, null);
                    if (this.jsonp != null)
                    {
                        jcontent = this.jsonp + "(" + jcontent + ")";
                    }
                    new ContentResult
                    {
                        ContentEncoding = UTF8,
                        ContentType     = "application/json",
                        Content         = jcontent
                    }.ExecuteResult(context);
                    break;

                case "text":
                    this.renderer = new CalendarRenderer.ViewRenderer(cr.RenderText);
                    MaybeCacheView(view_key, this.renderer, new ElmcityCacheDependency(base_key), null);
                    string tcontent = cr.RenderDynamicViewWithCaching(context, view_key, this.renderer, this.view, this.count, this.from, this.to, this.source, null);
                    new ContentResult
                    {
                        ContentEncoding = UTF8,
                        ContentType     = "text/plain",
                        Content         = tcontent
                    }.ExecuteResult(context);
                    break;

                case "csv":
                    this.renderer = new CalendarRenderer.ViewRenderer(cr.RenderCsv);
                    MaybeCacheView(view_key, this.renderer, new ElmcityCacheDependency(base_key), null);
                    string csv = cr.RenderDynamicViewWithCaching(context, view_key, this.renderer, this.view, this.count, this.from, this.to, this.source, null);
                    new ContentResult
                    {
                        ContentEncoding = UTF8,
                        ContentType     = "text/plain",
                        Content         = csv
                    }.ExecuteResult(context);
                    break;

                case "tags_json":
                    string tjcontent = cr.RenderTagCloudAsJson();
                    if (this.jsonp != null)
                    {
                        tjcontent = this.jsonp + "(" + tjcontent + ")";
                    }
                    new ContentResult
                    {
                        ContentEncoding = UTF8,
                        ContentType     = "application/json",
                        Content         = tjcontent,
                    }.ExecuteResult(context);
                    break;

                case "tags_html":
                    string thcontent = cr.RenderTagCloudAsHtml();
                    new ContentResult
                    {
                        ContentEncoding = UTF8,
                        ContentType     = "text/html",
                        Content         = thcontent,
                    }.ExecuteResult(context);
                    break;

                case "stats":
                    blob_uri = BlobStorage.MakeAzureBlobUri(this.id, this.id + ".stats.html", false);
                    //this.response_bytes = (byte[])CacheUtils.RetrieveBlobAndEtagFromServerCacheOrUri(this.cr.cache, blob_uri)["response_body"];
                    this.response_bytes = HttpUtils.FetchUrl(blob_uri).bytes;
                    new ContentResult
                    {
                        ContentEncoding = UTF8,
                        ContentType     = "text/html",
                        Content         = Encoding.UTF8.GetString(this.response_bytes),
                    }.ExecuteResult(context);
                    break;

                case "ics":
                    this.renderer = new CalendarRenderer.ViewRenderer(cr.RenderIcs);
                    MaybeCacheView(view_key, this.renderer, new ElmcityCacheDependency(base_key), null);
                    string ics_text = cr.RenderDynamicViewWithCaching(context, view_key, this.renderer, this.view, this.count, this.from, this.to, this.source, null);
                    new ContentResult
                    {
                        ContentType     = "text/calendar",
                        Content         = ics_text,
                        ContentEncoding = UTF8
                    }.ExecuteResult(context);
                    break;

                case "jswidget":
                    new ContentResult
                    {
                        ContentType     = "text/html",
                        Content         = cr.RenderJsWidget(),
                        ContentEncoding = UTF8
                    }.ExecuteResult(context);
                    break;

                case "today_as_html":
                    new ContentResult
                    {
                        ContentType     = "text/html",
                        Content         = cr.RenderTodayAsHtml(),
                        ContentEncoding = UTF8
                    }.ExecuteResult(context);
                    break;
                }
            }
Пример #27
0
 public BolUolImporter()
 {
     httpUtils = new HttpUtils();
 }
Пример #28
0
 private IEnumerable <KeyValuePair <string, string> > GetHeaders(string headers)
 {
     return(HttpUtils.GetHeaders(headers.Trim('[', ']')));
 }
 public liberoitImporter()
 {
     httpUtils=new HttpUtils();
 }
Пример #30
0
 /// <summary>
 /// 群组管理:加群 拉人 踢群 退群
 /// </summary>
 /// <param name="req"></param>
 /// <returns></returns>
 public static object GroupMgr(GroupMgrReq req)
 {
     return(HttpUtils.Post <object>(_ApiAddress + "&funcname=GroupMgr", req));
 }
Пример #31
0
 public WpImporter()
 {
     httpUtils=new HttpUtils();
 }
Пример #32
0
 /// <summary>
 /// 添加好友
 /// </summary>
 /// <param name="req"></param>
 /// <returns></returns>
 public static object AddQQUser(AddQQReq req)
 {
     return(HttpUtils.Post <object>(_ApiAddress + "&funcname=AddQQUser", req));
 }
Пример #33
0
 public GmailImporter()
 {
     httpUtils = new HttpUtils();
 }
Пример #34
0
 /// <summary>
 /// 撤回消息
 /// </summary>
 /// <param name="req"></param>
 /// <returns></returns>
 public static object RevokeMsg(RevokeMsgReq req)
 {
     return(HttpUtils.Post <object>(_ApiAddress + "&funcname=PbMessageSvc.PbMsgWithDraw", req));
 }
 public RamblerruImporter(String userid,String password)
 {
     httpUtils=new HttpUtils();
     this.userId=userid;
     this.password=password;
 }
Пример #36
0
 /// <summary>
 /// 搜索群组
 /// </summary>
 /// <param name="req"></param>
 /// <returns></returns>
 public static List <GroupSearchItemResp> SearchGroup(GroupSearchReq req)
 {
     return(HttpUtils.Post <List <GroupSearchItemResp> >(_ApiAddress + "&funcname=OidbSvc.0x8ba_31", req));
 }
Пример #37
0
 public MyspaceImporter(String user,String pass)
 {
     httpUtils = new HttpUtils();
     this.userId = userId;
     this.password = password;
 }
Пример #38
0
 /// <summary>
 /// 获取QQ相关ck
 /// </summary>
 /// <returns></returns>
 public static QQCkResp GetQQCk()
 {
     return(HttpUtils.Get <QQCkResp>(_ApiAddress + "&funcname=GetUserCook"));
 }
Пример #39
0
 public PlaxoImporter(String userId,String password)
 {
     httpUtils = new HttpUtils();
     this.userId = userId;
     this.password = password;
 }
 public void CreateSignatureBaseString_InvalidHttpMethod_ArgumentOutOfRangeException(HttpUtils sut,
     string method, string url, string parametersString)
 {
     sut.Invoking(a => a.CreateSignatureBaseString(method, url, parametersString))
         .ShouldThrow<ArgumentOutOfRangeException>();
 }
 public void UnescapeUnicode_EscapedData_Unescaped(string data, string result, HttpUtils sut)
 {
     sut.UnescapeUnicode(data).Should().Be(result);
 }
        public void CreateSigningKey_AnonymousData_CorrectString(string consumerSecret, string accessTokenSecret, HttpUtils sut)
        {
            var result = sut.CreateSigningKey(consumerSecret, accessTokenSecret);

            result.Should().Be(sut.Encode(consumerSecret) + "&" + sut.Encode(accessTokenSecret));
        }
Пример #43
0
 /// <summary>
 /// 处理好友请求
 /// </summary>
 /// <returns></returns>
 public static object DealFriend(FriendAddReqArgs arg)
 {
     return(HttpUtils.Post <object>(_ApiAddress + "&funcname=DealFriend", arg));
 }
Пример #44
0
        public override async Task <object> AuthenticateAsync(IServiceBase authService, IAuthSession session, Authenticate request, CancellationToken token = default)
        {
            var tokens = Init(authService, ref session, request);
            var ctx    = CreateAuthContext(authService, session, tokens);

            //Transferring AccessToken/Secret from Mobile/Desktop App to Server
            if (request?.AccessToken != null && VerifyAccessTokenAsync != null)
            {
                if (!await VerifyAccessTokenAsync(request.AccessToken, ctx).ConfigAwait())
                {
                    return(HttpError.Unauthorized(ErrorMessages.InvalidAccessToken.Localize(authService.Request)));
                }

                var isHtml       = authService.Request.IsHtml();
                var failedResult = await AuthenticateWithAccessTokenAsync(authService, session, tokens, request.AccessToken, ctx.AuthInfo, token : token).ConfigAwait();

                if (failedResult != null)
                {
                    return(ConvertToClientError(failedResult, isHtml));
                }

                return(isHtml
                    ? await authService.Redirect(SuccessRedirectUrlFilter(ctx, session.ReferrerUrl.SetParam("s", "1"))).SuccessAuthResultAsync(authService, session).ConfigAwait()
                    : null); //return default AuthenticateResponse
            }

            var httpRequest = authService.Request;
            var error       = httpRequest.GetQueryStringOrForm("error_reason")
                              ?? httpRequest.GetQueryStringOrForm("error")
                              ?? httpRequest.GetQueryStringOrForm("error_code")
                              ?? httpRequest.GetQueryStringOrForm("error_description");

            var hasError = !error.IsNullOrEmpty();

            if (hasError)
            {
                var httpParams = HttpUtils.HasRequestBody(httpRequest.Verb)
                    ? httpRequest.QueryString
                    : httpRequest.FormData;
                Log.Error($"OAuth2 Error callback. {httpParams}");
                return(authService.Redirect(FailedRedirectUrlFilter(ctx, session.ReferrerUrl.SetParam("f", error))));
            }

            var code = httpRequest.GetQueryStringOrForm(Keywords.Code);
            var isPreAuthCallback = !code.IsNullOrEmpty();

            if (!isPreAuthCallback)
            {
                var oauthstate = session.Id;
                var preAuthUrl = AuthorizeUrl
                                 .AddQueryParam("response_type", "code")
                                 .AddQueryParam("client_id", ConsumerKey)
                                 .AddQueryParam("redirect_uri", this.CallbackUrl)
                                 .AddQueryParam("scope", string.Join(" ", Scopes))
                                 .AddQueryParam(Keywords.State, oauthstate);

                if (ResponseMode != null)
                {
                    preAuthUrl = preAuthUrl.AddQueryParam("response_mode", ResponseMode);
                }

                if (session is AuthUserSession authSession)
                {
                    (authSession.Meta ?? (authSession.Meta = new Dictionary <string, string>()))["oauthstate"] = oauthstate;
                }

                await this.SaveSessionAsync(authService, session, SessionExpiry, token).ConfigAwait();

                return(authService.Redirect(PreAuthUrlFilter(ctx, preAuthUrl)));
            }

            try
            {
                var state = httpRequest.GetQueryStringOrForm(Keywords.State);
                if (state != null && session is AuthUserSession authSession)
                {
                    if (authSession.Meta == null)
                    {
                        authSession.Meta = new Dictionary <string, string>();
                    }

                    if (authSession.Meta.TryGetValue("oauthstate", out var oauthState) && state != oauthState)
                    {
                        return(authService.Redirect(FailedRedirectUrlFilter(ctx, session.ReferrerUrl.SetParam("f", "InvalidState"))));
                    }

                    authSession.Meta.Remove("oauthstate");
                }

                var contents = await GetAccessTokenJsonAsync(code, ctx, token).ConfigAwait();

                var authInfo = (Dictionary <string, object>)JSON.parse(contents);
                ctx.AuthInfo = authInfo.ToStringDictionary();

                var accessToken = (string)authInfo["access_token"];

                var redirectUrl = SuccessRedirectUrlFilter(ctx, session.ReferrerUrl.SetParam("s", "1"));

                var errorResult = await AuthenticateWithAccessTokenAsync(authService, session, tokens, accessToken, ctx.AuthInfo, token).ConfigAwait();

                if (errorResult != null)
                {
                    return(errorResult);
                }

                //Haz Access!
                if (HostContext.Config?.UseSameSiteCookies == true)
                {
                    // Workaround Set-Cookie HTTP Header not being honoured in 302 Redirects
                    var redirectHtml = HtmlTemplates.GetHtmlRedirectTemplate(redirectUrl);
                    return(await new HttpResult(redirectHtml, MimeTypes.Html).SuccessAuthResultAsync(authService, session).ConfigAwait());
                }

                return(await authService.Redirect(redirectUrl).SuccessAuthResultAsync(authService, session).ConfigAwait());
            }
            catch (WebException we)
            {
                var errorBody = await we.GetResponseBodyAsync(token).ConfigAwait();

                Log.Error($"Failed to get Access Token for '{Provider}': {errorBody}");

                var statusCode = ((HttpWebResponse)we.Response).StatusCode;
                if (statusCode == HttpStatusCode.BadRequest)
                {
                    return(authService.Redirect(FailedRedirectUrlFilter(ctx, session.ReferrerUrl.SetParam("f", "AccessTokenFailed"))));
                }
            }

            //Shouldn't get here
            return(authService.Redirect(FailedRedirectUrlFilter(ctx, session.ReferrerUrl.SetParam("f", "Unknown"))));
        }
        public void CreateSignatureBaseString_AnonymousData_CorrectString(string method, string url, string parametersString, HttpUtils sut)
        {
            var result = sut.CreateSignatureBaseString(method, url, parametersString);

            result.Should().Be(method + "&" + sut.Encode(url) + "&" + sut.Encode(parametersString));
        }
Пример #46
0
 /// <summary>
 /// 处理群邀请
 /// </summary>
 /// <returns></returns>
 public static object AnswerInviteGroup(GroupInviteArgs arg)
 {
     return(HttpUtils.Post <object>(_ApiAddress + "&funcname=AnswerInviteGroup", arg));
 }
Пример #47
0
 /// <summary>
 /// 修改群名片
 /// </summary>
 /// <returns></returns>
 public static object ModifyGroupCard(SetGroupCardReq req)
 {
     return(HttpUtils.Post <object>(_ApiAddress + "&funcname=friendlist.ModifyGroupCardReq", req));
 }
Пример #48
0
 /// <summary>
 /// 设置头衔
 /// </summary>
 /// <returns></returns>
 public static object SetUniqueTitle(SetGroupTitleReq req)
 {
     return(HttpUtils.Post <object>(_ApiAddress + "&funcname=OidbSvc.0x8fc_2", req));
 }
        public void ParseParameterString_InvalidParameterString_EmptyCollection(string parameterString, HttpUtils sut)
        {
            var result = sut.ParseParameterString(parameterString);

            result.Should().BeEmpty();
        }
Пример #50
0
 /// <summary>
 /// 发送公告
 /// </summary>
 /// <returns></returns>
 public static object Announce(SendGNoticeReq req)
 {
     return(HttpUtils.Post <object>(_ApiAddress + "&funcname=Announce", req));
 }
 public IndiaTimesImporter(String userid,String password)
 {
     httpUtils=new HttpUtils();
     this.userId=userId;
     this.password=password;
 }
Пример #52
0
 /// <summary>
 /// 全员禁言
 /// </summary>
 /// <returns></returns>
 public static object BanAllGroup(BanAllReq req)
 {
     return(HttpUtils.Post <object>(_ApiAddress + "&funcname=OidbSvc.0x89a_0", req));
 }
 public LinkedInImporter(String user,String pass)
 {
     httpUtils = new HttpUtils();
     this.userId = userId;
     this.password = password;
 }
Пример #54
0
 /// <summary>
 /// 禁言某人
 /// </summary>
 /// <returns></returns>
 public static object Ban(BanReq req)
 {
     return(HttpUtils.Post <object>(_ApiAddress + "&funcname=OidbSvc.0x570_8", req));
 }
Пример #55
0
 public BolUolImporter(String userId,String password)
 {
     this.userId=userId;
     this.password=password;
     httpUtils = new HttpUtils();
 }
Пример #56
0
        internal static AtomLinkMetadata MergeLinkMetadata(AtomLinkMetadata metadata, string relation, Uri href, string title, string mediaType)
        {
            AtomLinkMetadata metadata2 = new AtomLinkMetadata(metadata);
            string           strB      = metadata2.Relation;

            if (strB != null)
            {
                if (string.CompareOrdinal(relation, strB) != 0)
                {
                    throw new ODataException(Strings.ODataAtomWriterMetadataUtils_LinkRelationsMustMatch(relation, strB));
                }
            }
            else
            {
                metadata2.Relation = relation;
            }
            if (href != null)
            {
                Uri uri = metadata2.Href;
                if (uri != null)
                {
                    if (!href.Equals(uri))
                    {
                        throw new ODataException(Strings.ODataAtomWriterMetadataUtils_LinkHrefsMustMatch(href, uri));
                    }
                }
                else
                {
                    metadata2.Href = href;
                }
            }
            if (title != null)
            {
                string str2 = metadata2.Title;
                if (str2 != null)
                {
                    if (string.CompareOrdinal(title, str2) != 0)
                    {
                        throw new ODataException(Strings.ODataAtomWriterMetadataUtils_LinkTitlesMustMatch(title, str2));
                    }
                }
                else
                {
                    metadata2.Title = title;
                }
            }
            if (mediaType != null)
            {
                string str3 = metadata2.MediaType;
                if (str3 == null)
                {
                    metadata2.MediaType = mediaType;
                    return(metadata2);
                }
                if (!HttpUtils.CompareMediaTypeNames(mediaType, str3))
                {
                    throw new ODataException(Strings.ODataAtomWriterMetadataUtils_LinkMediaTypesMustMatch(mediaType, str3));
                }
            }
            return(metadata2);
        }
 public OneSixthreeImporter(String user,String pass)
 {
     httpUtils = new HttpUtils();
     this.userId = userId;
     this.password = password;
 }
Пример #58
0
 public SinaImporter()
 {
     httpUtils = new HttpUtils();
 }
 public liberoitImporter(String userid,String password)
 {
     httpUtils=new HttpUtils();
     this.userId=userid;
     this.password=password;
 }
Пример #60
0
        /// <summary> Converts SDK request object into HttpRequestMessage.</summary>
        /// <param name="uri">The uri of this http request.</param>
        /// <param name="method">The method of this http request.</param>
        /// <param name="request">The SDK object for this request.</param>
        /// <returns>An HttpRequestMessage that can be sent by HttpClient.</returns>
        public static HttpRequestMessage ToHttpRequestMessage <T>(Uri uri, HttpMethod method, T request) where T : IOciRequest
        {
            // Update properties of requests if needed

            var requestMessage = new HttpRequestMessage();

            requestMessage.Method = method;
            var updatedUri = uri.AbsoluteUri;
            // Build queries string.
            var queries = new Dictionary <string, string>();

            PropertyInfo[] props = typeof(T).GetProperties();
            foreach (var prop in props)
            {
                if (prop.GetValue(request) == null)
                {
                    continue;
                }
                object[] attrs = prop.GetCustomAttributes(false);
                foreach (var attr in attrs)
                {
                    HttpConverterAttribute httpRequestAttr = attr as HttpConverterAttribute;
                    if (httpRequestAttr != null)
                    {
                        if (httpRequestAttr.Target == TargetEnum.Query)
                        {
                            logger.Debug($"Adding query {httpRequestAttr.Name}: {HttpUtils.EncodeQueryParam(prop.GetValue(request))}");
                            queries.Add(httpRequestAttr.Name, HttpUtils.EncodeQueryParam(prop.GetValue(request)));
                        }
                        else if (httpRequestAttr.Target == TargetEnum.Header)
                        {
                            var propertyType = prop.PropertyType;
                            // Special handling of Dictionary type in header since the Dictionary contents are returned as individual header entries.
                            if (propertyType.IsGenericType && propertyType.GetGenericTypeDefinition() == typeof(Dictionary <,>))
                            {
                                foreach (KeyValuePair <string, string> pair in prop.GetValue(request) as IDictionary <string, string> )
                                {
                                    requestMessage.Headers.TryAddWithoutValidation(pair.Key, pair.Value);
                                }
                            }
                            else
                            {
                                logger.Debug($"Adding header {httpRequestAttr.Name}: {prop.GetValue(request)}");
                                // To avoid validating header name formatting (.Net HttpClient has some strict validation rules and not all OCI service headers satisfy them.),
                                // call TryAddWithoutValidation instead of Add.
                                requestMessage.Headers.TryAddWithoutValidation(httpRequestAttr.Name, HeaderUtils.FromValue(prop.GetValue(request)));
                            }
                        }
                        else if (httpRequestAttr.Target == TargetEnum.Body)
                        {
                            logger.Debug($"Adding content from property {prop.Name}");
                            requestMessage.Content = ContentHelper.CreateHttpContent(prop.GetValue(request));
                        }
                        else if (httpRequestAttr.Target == TargetEnum.Path)
                        {
                            logger.Debug($"Adding path parameter {httpRequestAttr.Name}: {prop.GetValue(request)}");
                            updatedUri = updatedUri.Replace(Uri.EscapeUriString($"{{{httpRequestAttr.Name}}}"), HeaderUtils.FromValue(prop.GetValue(request)));
                        }
                    }
                }
            }
            var uriBuilder = new UriBuilder(updatedUri);

            uriBuilder.Query          = HttpUtils.BuildQueryString(queries);
            requestMessage.RequestUri = uriBuilder.Uri;
            return(requestMessage);
        }