Exemple #1
0
        public NewsCurlyBracket(EntityModel.News news)
        {
            Id          = news.Id;
            Title       = news.Title;
            Description = news.Description;
            Content     = news.Content;
            ImageUrl    = news.ImageUrl;
            DetailsUrl  = UrlUtilities.GenerateUrl(HttpContext.Current.Request.RequestContext, "News", "Details",
                                                   new
            {
                id    = news.Id,
                title = news.Title.ToUrlString()
            });
            LastUpdate    = news.Updated ?? news.Created;
            LastUpdatedBy = news.Updated.HasValue ? news.UpdatedBy : news.CreatedBy;
            RecordOrder   = news.RecordOrder;
            Created       = news.Created;
            CreatedBy     = news.CreatedBy;
            Updated       = news.Updated;
            UpdatedBy     = news.UpdatedBy;
            var newsCategories = news.NewsNewsCategories.Select(nc => nc.NewsCategory).ToList();

            Categories = newsCategories.Any()
                             ? newsCategories.Select(c => new CategoryItemModel(c)).ToList()
                             : new List <CategoryItemModel>();
        }
Exemple #2
0
 public List <ServiceCurlyBracket> GetServices(int count)
 {
     return(Fetch(s => s.Status == (int)ServiceEnums.StatusEnums.Active)
            .OrderBy(m => m.RecordOrder)
            .Take(count)
            .ToList().Select(s => new ServiceCurlyBracket
     {
         Id = s.Id,
         Title = s.Title,
         Description = s.Description,
         Content = s.Content,
         ImageUrl = s.ImageUrl,
         DetailsUrl = UrlUtilities.GenerateUrl(HttpContext.Current.Request.RequestContext, "Services", "Details",
                                               new
         {
             area = "Admin",
             id = s.Id
         }),
         RecordOrder = s.RecordOrder,
         Created = s.Created,
         CreatedBy = s.CreatedBy,
         Updated = s.Updated,
         UpdatedBy = s.UpdatedBy
     }).ToList());
 }
Exemple #3
0
        /// <summary>
        /// Gets information about Uber products at a given location.
        /// See <see cref="https://developer.uber.com/docs/riders/references/api/v1.2/products-get"/> for more info.
        /// </summary>
        /// <param name="latitude">The latitude</param>
        /// <param name="longitude">The longitude</param>
        /// <returns>The <see cref="Products"/> information.</returns>
        public async Task <Products> GetProductsAsync(float latitude, float longitude)
        {
            var urlSuffix = string.Format("products?latitude={0}&longitude={1}", latitude.ToString("R"), longitude.ToString("R"));
            var url       = UrlUtilities.FormatUrl(_url, _apiVersion, urlSuffix);

            return(await HttpGetAsync <Products>(url));
        }
Exemple #4
0
        private string GetSetObjectPropertyResponse(string address)
        {
            var queries = UrlUtilities.CrackUrl(address);

            PropertyCache cache;

            if (typeof(TObjectProperty) == typeof(ObjectProperty))
            {
                cache = ObjectPropertyParser.GetPropertyInfoViaTypeLookup((Enum)(object)property);
            }
            else if (typeof(TObjectProperty) == typeof(ChannelProperty))
            {
                cache = ObjectPropertyParser.GetPropertyInfoViaPropertyParameter <Channel>((Enum)(object)property);
            }
            else
            {
                throw new NotImplementedException($"Handler for object property type {nameof(TObjectProperty)} is not implemented");
            }

            var queryName = ObjectPropertyParser.GetObjectPropertyNameViaCache((Enum)(object)property, cache);

            if (typeof(TObjectProperty) == typeof(ChannelProperty))
            {
                queryName += "1"; //Channel ID used for tests
            }
            var val = queries[queryName];

            Assert.IsTrue(val == expectedValue, $"The value of property '{property.ToString().ToLower()}' did not match the expected value. Expected '{expectedValue}', received: '{val}'");

            return("OK");
        }
Exemple #5
0
        internal static void ValidateAddSensorProgressResult(AddSensorProgress p, bool addFull)
        {
            if (p.TargetUrl.StartsWith("addsensorfailed"))
            {
                var parts = UrlUtilities.CrackUrl(p.TargetUrl);

                var message = parts["errormsg"];

                var action = addFull ? "add sensor" : "resolve sensor targets";

                if (message != null)
                {
                    message = message.Trim('\r', '\n');

                    //todo: does this work in other languages? Not sure how to replicate it
                    if (message.StartsWith("Incomplete connection settings"))
                    {
                        throw new PrtgRequestException("Failed to retrieve data from device; required credentials for sensor type may be missing. See PRTG UI for further details.");
                    }

                    throw new PrtgRequestException($"An exception occurred while trying to {action}: {message.EnsurePeriod()}");
                }

                throw new PrtgRequestException($"An unspecified error occurred while trying to {action}. Specified sensor type may not be valid on this device, or sensor query target parameters may be incorrect. Check the Device 'Host' is still valid or try adding sensor with the PRTG UI.");
            }

            if (addFull && p.Percent == -1)
            {
                throw new PrtgRequestException($"PRTG was unable to complete the request. The server responded with the following error: '{p.Error.Replace("<br/><ul><li>", " ").Replace("</li></ul><br/>", " ")}'.");
            }
        }
Exemple #6
0
        public void GetFileName_Nominal()
        {
            const string url      = "https://illumina-usw2-olympia-dev.s3.amazonaws.com/Annotation/input/Mother.vcf.gz?AWSAccessKeyId=AKIAI774CQHRMUZUNE5Q&Signature=W7Rofh4%2BFXPrPE9ONrdk2iKrGqE%3D&Expires=1561072628";
            string       observed = UrlUtilities.GetFileName(url);

            Assert.Equal("Mother.vcf.gz", observed);
        }
        protected override void ExecuteCmdlet()
        {
            var siteUrl = PnPConnection.CurrentConnection.Url;

            if (ParameterSpecified(Site))
            {
                siteUrl = Site;
            }
            var hostUrl = ClientContext.Url;

            if (hostUrl.EndsWith("/"))
            {
                hostUrl = hostUrl.Substring(0, hostUrl.Length - 1);
            }
            var site = this.Tenant.GetSiteByUrl(siteUrl);

            ClientContext.Load(site);
            ClientContext.ExecuteQueryRetry();
            var normalizedUserName = UrlUtilities.UrlEncode($"i:0#.f|membership|{LoginName}");
            var results            = RestHelper.GetAsync <RestResultCollection <ExportEntity> >(this.HttpClient, $"{hostUrl}/_api/sp.userprofiles.peoplemanager/GetSPUserInformation(accountName=@a,siteId=@b)?@a='{normalizedUserName}'&@b='{site.Id}'", ClientContext, false).GetAwaiter().GetResult();
            var record             = new PSObject();

            foreach (var item in results.Items)
            {
                record.Properties.Add(new PSVariableProperty(new PSVariable(item.Key.Split('|')[1], item.Value)));
            }
            WriteObject(record);
        }
Exemple #8
0
        private IWebResponse GetTableResponse(string address)
        {
            var components = UrlUtilities.CrackUrl(address);

            Content content = components["content"].DescriptionToEnum <Content>();

            switch (content)
            {
            case Content.Sensors:
                if (components["filter_objid"] == "1")
                {
                    return(new SensorResponse());
                }
                if (CountOverride != null && CountOverride[Content.Sensors] == 0)
                {
                    return(new SensorResponse());
                }
                return(new SensorResponse(new SensorItem()));

            case Content.Channels:
                return(new ChannelResponse(new ChannelItem()));

            case Content.Triggers:
                return(new NotificationTriggerResponse(NotificationTriggerItem.StateTrigger()));

            case Content.Notifications:
                return(new NotificationActionResponse(new NotificationActionItem("301")));

            case Content.Schedules:
                return(new ScheduleResponse(new ScheduleItem()));

            default:
                throw new NotImplementedException($"Unknown content '{content}' requested from {nameof(SetNotificationTriggerResponse)}");
            }
        }
        private IWebResponse GetTableResponse(string address)
        {
            var components = UrlUtilities.CrackUrl(address);

            Content content = components["content"].DescriptionToEnum <Content>();

            var count = 1;

            var objIds = components.GetValues("filter_objid");

            if (objIds != null)
            {
                count = objIds.Length;
            }

            switch (content)
            {
            case Content.Sensors:
                var type = components["filter_type"] ?? "aggregation";

                if (type.StartsWith("@sub("))
                {
                    type = type.Substring(5, type.Length - 6);
                }

                return(new SensorResponse(Enumerable.Range(0, count).Select(i => new SensorItem(typeRaw: type)).ToArray()));

            case Content.Channels:
                return(new ChannelResponse(new ChannelItem()));

            default:
                throw new NotImplementedException($"Unknown content '{content}' requested from {nameof(SensorFactorySourceResponse)}");
            }
        }
        protected override IWebResponse GetResponse(ref string address, string function)
        {
            switch (function)
            {
            case nameof(XmlFunction.TableData):
                return(GetTableResponse(address));

            case nameof(HtmlFunction.ObjectData):
                return(new SensorSettingsResponse(propertyChanger));

            case nameof(XmlFunction.GetObjectProperty):
                var components = UrlUtilities.CrackUrl(address);

                if (components["name"] == "aggregationchannel")
                {
                    var text = new SensorSettingsResponse(propertyChanger).GetResponseText(ref address);
                    var xml  = HtmlParser.Default.GetXml(text);

                    var value = xml.Descendants("injected_aggregationchannel").First().Value;

                    return(new RawPropertyResponse(value));
                }

                throw new NotImplementedException($"Don't know how to handle object property '{components["name"]}'");

            case nameof(HtmlFunction.ChannelEdit):
                return(new ChannelResponse(new ChannelItem()));

            default:
                throw GetUnknownFunctionException(function);
            }
        }
Exemple #11
0
        public IWebResponse GetResponse(string address, string function)
        {
            var components = UrlUtilities.CrackUrl(address);

            requestNum++;
            return(GetResponse(address));
        }
Exemple #12
0
        protected override void ExecuteCmdlet()
        {
            var url       = SelectedWeb.EnsureProperty(w => w.Url);
            var tenantUrl = UrlUtilities.GetTenantAdministrationUrl(ClientContext.Url);

            using (var tenantContext = ClientContext.Clone(tenantUrl))
            {
                var tenant = new Tenant(tenantContext);
                var webUrl = url;
                if (!string.IsNullOrEmpty(WebUrl))
                {
                    try
                    {
                        var uri = new System.Uri(WebUrl);
                        webUrl = WebUrl;
                    }
                    catch
                    {
                        ThrowTerminatingError(new ErrorRecord(new System.Exception("Invalid URL"), "INVALIDURL", ErrorCategory.InvalidArgument, WebUrl));
                    }
                }
                TenantSiteDesign design = Identity.GetTenantSiteDesign(tenant);
                if (design != null)
                {
                    var results = tenant.ApplySiteDesign(SelectedWeb.Url, design.Id);
                    tenantContext.Load(results);
                    tenantContext.ExecuteQueryRetry();
                    WriteObject(results, true);
                }
            }
        }
Exemple #13
0
        private string GetTableText(string address)
        {
            var components = UrlUtilities.CrackUrl(address);

            var content = MultiTypeResponse.GetContent(address);

            switch (content)
            {
            case Content.Triggers:
                return(base.GetResponseText(ref address));

            case Content.Channels:

                if (Convert.ToInt32(components["id"]) >= 4000)
                {
                    return(new ChannelResponse(channels).GetResponseText(ref address));
                }
                return(new ChannelResponse().GetResponseText(ref address));

            case Content.Notifications:
                return(new NotificationActionResponse(new NotificationActionItem("301"), new NotificationActionItem("302"), new NotificationActionItem("303")).GetResponseText(ref address));

            case Content.Schedules:
                return(new ScheduleResponse(new ScheduleItem()).GetResponseText(ref address));

            default:
                throw new NotImplementedException($"Unknown content '{content}' requested from {nameof(NotificationTriggerResponse)}");
            }
        }
        private IWebResponse GetObjectDataResponse(string address)
        {
            var components = UrlUtilities.CrackUrl(address);

            var objectType = components["objecttype"]?.DescriptionToEnum <ObjectType>();

            if (objectType == null && components["id"] == "810")
            {
                objectType = ObjectType.WebServerOptions;
            }

            switch (objectType)
            {
            case ObjectType.Notification:
                return(new NotificationActionResponse(new NotificationActionItem()));

            case ObjectType.Schedule:
                return(new ScheduleResponse());

            case ObjectType.WebServerOptions:
                return(new WebServerOptionsResponse());

            default:
                throw new NotImplementedException($"Unknown object type '{objectType}' requested from {nameof(MultiTypeResponse)}");
            }
        }
Exemple #15
0
        /// <summary>
        /// Map entities to models
        /// </summary>
        /// <param name="linkTrackers"></param>
        /// <param name="searchModel"></param>
        /// <returns></returns>
        private IQueryable <LinkTrackerModel> Maps(IQueryable <LinkTracker> linkTrackers,
                                                   LinkTrackerSearchModel searchModel)
        {
            var trackerLink = UrlUtilities.GenerateUrl(HttpContext.Current.Request.RequestContext, "SiteApi",
                                                       "LinkTracker", new { area = "" }, true);

            // Caculate the end date from date to
            DateTime?dateTo = null;

            if (searchModel.DateTo.HasValue)
            {
                dateTo = searchModel.DateTo.Value.ToEndDate();
            }

            return(linkTrackers.Select(l => new LinkTrackerModel
            {
                Id = l.Id,
                Name = l.Name,
                TrackerLink = trackerLink + "?id=" + SqlFunctions.StringConvert((double)l.Id).Trim(),
                IsAllowMultipleClick = l.IsAllowMultipleClick,
                RedirectUrl = l.RedirectUrl ?? string.Empty,
                PageId = l.PageId,
                PageTitle = l.PageId.HasValue ? l.Page.Title : string.Empty,
                ClickCount = l.LinkTrackerClicks
                             .Count(lc => (!searchModel.DateFrom.HasValue || lc.Created >= searchModel.DateFrom.Value) &&
                                    (!dateTo.HasValue || lc.Created <= dateTo)),
                RecordOrder = l.RecordOrder,
                Created = l.Created,
                CreatedBy = l.CreatedBy,
                LastUpdate = l.LastUpdate,
                LastUpdateBy = l.LastUpdateBy
            }));
        }
        private IWebResponse GetObjectDataResponse(string address)
        {
            var components = UrlUtilities.CrackUrl(address);

            var objectType = components["objecttype"]?.ToEnum <ObjectType>() ?? ObjectType.Sensor;

            switch (objectType)
            {
            case ObjectType.Sensor:
                return(new SensorSettingsResponse());

            case ObjectType.Device:
                return(new DeviceSettingsResponse());

            case ObjectType.Notification:
                return(new NotificationActionResponse(new NotificationActionItem())
                {
                    HasSchedule = HasSchedule
                });

            case ObjectType.Schedule:
                return(new ScheduleResponse());

            default:
                throw new NotImplementedException($"Unknown object type '{objectType}' requested from {nameof(MultiTypeResponse)}");
            }
        }
        internal override void OnPostAuthorizeRequest(object sender, EventArgs e)
        {
            bool flag = false;

            if (this.onPostAuthorizeRequestChain != null)
            {
                flag = this.onPostAuthorizeRequestChain.ExecuteRequestFilterChain(sender, e, RequestEventType.PostAuthorizeRequest);
            }
            if (flag)
            {
                return;
            }
            HttpApplication httpApplication = (HttpApplication)sender;

            if (UrlUtilities.IsWacRequest(httpApplication.Context.Request))
            {
                return;
            }
            try
            {
                RequestDispatcher.DispatchRequest(OwaContext.Get(httpApplication.Context));
            }
            catch (ThreadAbortException)
            {
                OwaContext.Current.UnlockMinResourcesOnCriticalError();
            }
        }
Exemple #18
0
        protected override void ExecuteCmdlet()
        {
            var url       = SelectedWeb.EnsureProperty(w => w.Url);
            var tenantUrl = UrlUtilities.GetTenantAdministrationUrl(ClientContext.Url);

            using (var tenantContext = ClientContext.Clone(tenantUrl))
            {
                var tenant = new Tenant(tenantContext);
                var webUrl = url;
                if (!string.IsNullOrEmpty(WebUrl))
                {
                    try
                    {
                        var uri = new Uri(WebUrl);
                        webUrl = WebUrl;
                    }
                    catch
                    {
                        ThrowTerminatingError(new ErrorRecord(new System.Exception("Invalid URL"), "INVALIDURL", ErrorCategory.InvalidArgument, WebUrl));
                    }
                }

                tenant.SetWebTheme(Theme.Name, webUrl);
                tenantContext.ExecuteQueryRetry();
            }
        }
Exemple #19
0
        protected override void ExecuteCmdlet()
        {
            var url       = SelectedWeb.EnsureProperty(w => w.Url);
            var tenantUrl = UrlUtilities.GetTenantAdministrationUrl(ClientContext.Url);

            using (var tenantContext = ClientContext.Clone(tenantUrl))
            {
                var tenant = new Tenant(tenantContext);
                var webUrl = url;
                if (!string.IsNullOrEmpty(WebUrl))
                {
                    try
                    {
                        var uri = new System.Uri(WebUrl);
                        webUrl = WebUrl;
                    }
                    catch
                    {
                        ThrowTerminatingError(new ErrorRecord(new System.Exception("Invalid URL"), "INVALIDURL", ErrorCategory.InvalidArgument, WebUrl));
                    }
                }
                var designRun = tenant.GetSiteDesignRun(webUrl, SiteDesignId != null ? SiteDesignId.Id : Guid.Empty);
                tenantContext.Load(designRun);
                tenantContext.ExecuteQueryRetry();
                WriteObject(designRun, true);
            }
        }
Exemple #20
0
        /// <summary>
        /// Send request to service and getting result
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="serviceUrl"></param>
        /// <param name="authorizeCode"></param>
        /// <param name="apiAction"></param>
        /// <param name="method"></param>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public static T SendApiRequest <T>(string serviceUrl, string authorizeCode, string apiAction, HttpMethod method,
                                           RouteValueDictionary parameters)
        {
            var client = new HttpClient
            {
                BaseAddress = new Uri(serviceUrl)
            };

            if (!string.IsNullOrEmpty(authorizeCode))
            {
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
                                                                                           Convert.ToBase64String(System.Text.Encoding.ASCII.GetBytes(authorizeCode)));
            }

            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            HttpResponseMessage responseMessage;

            if (method == HttpMethod.Post)
            {
                responseMessage = client.PostAsJsonAsync(apiAction, parameters).Result;
            }
            else
            {
                var url = UrlUtilities.CombineQueryString(apiAction, parameters);
                responseMessage = client.GetAsync(url).Result;
            }

            var result = responseMessage.Content.ReadAsAsync <T>().Result;

            return(result);
        }
Exemple #21
0
        private string GetSystemInfo(string address)
        {
            var components = UrlUtilities.CrackUrl(address);

            switch (components["category"].DescriptionToEnum <SystemInfoType>())
            {
            case SystemInfoType.System:
                return(GetResponse(SystemInfoType.System));

            case SystemInfoType.Hardware:
                return(GetResponse(SystemInfoType.Hardware));

            case SystemInfoType.Software:
                return(GetResponse(SystemInfoType.Software));

            case SystemInfoType.Processes:
                return(GetResponse(SystemInfoType.Processes));

            case SystemInfoType.Services:
                return(GetResponse(SystemInfoType.Services));

            case SystemInfoType.Users:
                return(GetResponse(SystemInfoType.Users));

            default:
                throw new NotImplementedException();
            }
        }
Exemple #22
0
        protected override IWebResponse GetResponse(ref string address, string function)
        {
            if (function == nameof(XmlFunction.TableData))
            {
                var components = UrlUtilities.CrackUrl(address);

                Content content = components["content"].DescriptionToEnum <Content>();

                if (content == Content.Logs)
                {
                    if (components["columns"] != "objid,name")
                    {
                        components.Remove("content");
                        components.Remove("columns");
                        components.Remove("username");
                        components.Remove("passhash");

                        if (components["start"] != null)
                        {
                            components.Remove("start");
                        }

                        var filtered = WebUtility.UrlDecode(UrlUtilities.QueryCollectionToString(components));

                        if (filtered != str)
                        {
                            Assert.Fail($"Address was '{filtered}' instead of '{str}'");
                        }
                    }
                }
            }

            return(base.GetResponse(ref address, function));
        }
        /// <summary>
        /// Saves files in a MMMM/yyyy/{Guid} structure for observation images, to avoid
        /// a single directory being filled over time.
        /// </summary>
        /// <param name="observation">The observation to save the file path against</param>
        /// <param name="postedFile">A posted file to save</param>
        /// <returns>
        /// the relative path of the file for storage in the database. We do not want
        /// to store the full virtual path so that the files can easily
        /// be migrated elsewhere without having to update the database.
        /// </returns>

        private void SaveFile(DataLayer.Models.Observation observation, HttpPostedFileBase postedFile)
        {
            if (postedFile != null)
            {
                HttpServerUtility server = HttpContext.Current.Server;

                //Use the relative path provided if we already have one, so that we can overwrite
                //the existing upload.

                if (string.IsNullOrWhiteSpace(observation.FilePath))
                {
                    // - {Guid}.jpg
                    string filename = Guid.NewGuid() + Path.GetExtension(postedFile.FileName);

                    // - C:/.../Uploads/
                    var uploadFolder = new DirectoryInfo(server.MapPath(ObservationVirtualDirectory));

                    // - "2012/Feb"
                    string directoryRelativePath = CreateUploadDirectory(uploadFolder.FullName);

                    // - "2012/Feb/{Guid}.jpg"
                    observation.FilePath = UrlUtilities.Combine(directoryRelativePath, filename);
                }

                // - "~/Uploads/2012/Feb/{GUID}.xxx"
                string virtualFilePath = VirtualPathUtility.Combine(ObservationVirtualDirectory, observation.FilePath);

                // - Save the file
                postedFile.SaveAs(server.MapPath(virtualFilePath));
            }
        }
        // Token: 0x060002C9 RID: 713 RVA: 0x0000A280 File Offset: 0x00008480
        public static WacRequest ParseWacRequest(string mailboxSmtpAddress, HttpRequest request)
        {
            if (request == null)
            {
                throw new OwaInvalidRequestException("Request object is null");
            }
            if (!UrlUtilities.IsWacRequest(request))
            {
                throw new OwaInvalidRequestException("Expected a WAC request, but got this instead: " + request.Url.AbsoluteUri);
            }
            WacRequestType requestType       = WacRequest.GetRequestType(request);
            string         text              = request.QueryString["access_token"] ?? string.Empty;
            string         exchangeSessionId = WacUtilities.GetExchangeSessionId(text);
            string         ewsAttachmentId;

            WacRequest.ParseAccessToken(text, out ewsAttachmentId);
            string     fileRepAsString = request.QueryString["owaatt"] ?? string.Empty;
            WacFileRep fileRep         = WacFileRep.Parse(fileRepAsString);
            string     value           = request.Headers["X-WOPI-PerfTraceRequested"] ?? string.Empty;
            bool       perfTraceRequested;

            if (!bool.TryParse(value, out perfTraceRequested))
            {
                perfTraceRequested = false;
            }
            return(new WacRequest(requestType, fileRep, (SmtpAddress)mailboxSmtpAddress, exchangeSessionId, ewsAttachmentId, request.QueryString["ui"] ?? "en-us", request.Headers["X-WOPI-InterfaceVersion"] ?? string.Empty, request.Headers["X-WOPI-MachineName"] ?? string.Empty, perfTraceRequested, request.Headers["X-WOPI-CorrelationID"] ?? string.Empty));
        }
Exemple #25
0
        public IWebResponse GetResponse(string address, string function)
        {
            var     components = UrlUtilities.CrackUrl(address);
            Content content    = components["content"].DescriptionToEnum <Content>();

            requestNum++;
            return(GetResponse(address, content));
        }
        public static Content GetContent(string address)
        {
            var components = UrlUtilities.CrackUrl(address);

            Content content = components["content"].DescriptionToEnum <Content>();

            return(content);
        }
Exemple #27
0
        /// <summary>
        /// Attempts to authenticate using OAuth and hydrate <see cref="AccessToken"/> and <see cref="RefreshToken"/>.
        /// </summary>
        /// <param name="clientId">The client id to authenticate against.</param>
        /// <param name="clientSecret">The client secrete to authenticate with.</param>
        /// <param name="redirectUri">The redirect uri if/when authenticate succeeds.</param>
        /// <param name="authorizationCode">The authorization code.</param>
        /// <returns>The empty task.</returns>
        public async Task AuthenticateOAuthAsync(string clientId, string clientSecret, string redirectUri, string authorizationCode)
        {
            if (string.IsNullOrEmpty(clientId))
            {
                throw new ArgumentNullException($"{nameof(clientId)}");
            }
            if (string.IsNullOrEmpty(clientSecret))
            {
                throw new ArgumentNullException($"{nameof(clientSecret)}");
            }
            if (string.IsNullOrEmpty(redirectUri))
            {
                throw new ArgumentNullException($"{nameof(redirectUri)}");
            }
            if (string.IsNullOrEmpty(authorizationCode))
            {
                throw new ArgumentNullException($"{nameof(authorizationCode)}");
            }
            if (!UrlUtilities.CheckUri(redirectUri))
            {
                throw new ArgumentException($"Invalid {nameof(redirectUri)}");
            }

            var content = new FormUrlEncodedContent(new[]
            {
                new KeyValuePair <string, string>("client_id", clientId),
                new KeyValuePair <string, string>("client_secret", clientSecret),
                new KeyValuePair <string, string>("grant_type", "authorization_code"),
                new KeyValuePair <string, string>("redirect_uri", redirectUri),
                new KeyValuePair <string, string>("code", authorizationCode),
                new KeyValuePair <string, string>("scope", "")    // todo: implement scopes
            });

            var request = new HttpRequestMessage()
            {
                Method     = HttpMethod.Post,
                RequestUri = new Uri(OAuthTokenUrl),
                Content    = content
            };

            var responseMessage = await _httpClient.SendAsync(request).ConfigureAwait(false);

            var response = await responseMessage.Content.ReadAsStringAsync().ConfigureAwait(false);

            if (responseMessage.IsSuccessStatusCode)
            {
                var authToken = JsonConvert.DeserializeObject <AuthToken>(response);

                AccessToken  = authToken.access_token;
                RefreshToken = authToken.refresh_token;
            }
            else
            {
                //TODO: Richer error handling
                throw new Exception($"Error authenticating: \n {response}");
            }
        }
Exemple #28
0
        public FormWidget(Form form)
            : this()
        {
            var encryptId = PasswordUtilities.ComplexEncrypt(form.Id.ToString(CultureInfo.InvariantCulture));

            ScriptUrl = UrlUtilities.GenerateUrl(HttpContext.Current.Request.RequestContext, "SiteApi", "ScriptLoader",
                                                 new { area = "", f = encryptId }, true);
            IframeUrl = UrlUtilities.GenerateUrl(HttpContext.Current.Request.RequestContext, "SiteApi", "IframeLoader",
                                                 new { area = "", f = encryptId }, true);
        }
        private IWebResponse GetTableResponse(ref string address, string function)
        {
            var components = UrlUtilities.CrackUrl(address);

            Content content = components["content"].DescriptionToEnum <Content>();

            IncrementCount(content);

            return(base.GetResponse(ref address, function));
        }
Exemple #30
0
        /// <summary>
        /// Gets information about the Uber user that has authorized with the application.
        /// </summary>
        /// <returns>The authorized <see cref="User"/>.</returns>
        public async Task <User> GetUserAsync()
        {
            if (_tokenType == TokenTypes.Server)
            {
                throw new ArgumentException("This endpoint only supports access token.");
            }

            var url = UrlUtilities.FormatUrl(_url, _apiVersion, "me");

            return(await HttpGetAsync <User>(url));
        }