public static Task Start(HttpContext context) { IUserInfo info = BaseGlobalVariable.Current.UserInfo; WebAppSetting appSetting = WebAppSetting.WebCurrent; string url; if (info.IsLogOn) { if (string.IsNullOrEmpty(appSetting.MainPath)) { url = appSetting.HomePath; } else { url = HttpUtility.UrlEncode(AppUtil.ResolveUrl(appSetting.HomePath)); url = UriUtil.AppendQueryString(appSetting.MainPath, "StartUrl=" + url); } } else { url = appSetting.StartupPath; } url = AppUtil.ResolveUrl(url); context.Response.Redirect(url); return(Task.FromResult(0)); }
/// <summary> /// Applies an entity reference link (value of a navigation link) to an entity. /// </summary> /// <param name="navigationProperty">The navigation property for which the entity reference link was specified.</param> /// <param name="entityResource">The entity resource to apply the value to.</param> /// <param name="entityReferenceLink">The entity reference link to apply.</param> private void ApplyEntityReferenceLinkInNavigationProperty(ResourceProperty navigationProperty, object entityResource, ODataEntityReferenceLink entityReferenceLink) { Debug.Assert( navigationProperty != null && navigationProperty.TypeKind == ResourceTypeKind.EntityType, "navigationProperty != null && navigationProperty.TypeKind == ResourceTypeKind.EntityType"); Debug.Assert(entityResource != null, "entityResource != null"); Debug.Assert(entityReferenceLink != null, "entityReferenceLink != null"); // Ignore entity reference links without any URL (this is effectively ATOM only since in JSON there always has to be some // URL, null would cause failure when reading it, in ATOM this is the case of a link without any href and no content). if (entityReferenceLink.Url == null) { return; } string linkUrl = UriUtil.UriToString(entityReferenceLink.Url); if (this.IsAtomRequest && linkUrl.Length == 0) { // Empty Url for atom:link (without any content in the link) is treated as null entity. this.SetResourceReferenceToNull(entityResource, navigationProperty); } else { // Resolve the link URL and set it to the navigation property. this.SetResourceReferenceToUrl(entityResource, navigationProperty, linkUrl); } }
/// <summary> /// Generates the authentication requests that can satisfy the requirements of some OpenID Identifier. /// </summary> /// <param name="userSuppliedIdentifier"> /// The Identifier supplied by the user. This may be a URL, an XRI or i-name. /// </param> /// <param name="realm"> /// The shorest URL that describes this relying party web site's address. /// For example, if your login page is found at https://www.example.com/login.aspx, /// your realm would typically be https://www.example.com/. /// </param> /// <returns> /// An authentication request object that describes the HTTP response to /// send to the user agent to initiate the authentication. /// </returns> /// <remarks> /// <para>Any individual generated request can satisfy the authentication. /// The generated requests are sorted in preferred order. /// Each request is generated as it is enumerated to. Associations are created only as /// <see cref="IAuthenticationRequest.RedirectingResponse"/> is called.</para> /// <para>No exception is thrown if no OpenID endpoints were discovered. /// An empty enumerable is returned instead.</para> /// </remarks> internal IEnumerable <IAuthenticationRequest> CreateRequests(Identifier userSuppliedIdentifier, Realm realm) { if (HttpContext.Current == null) { throw new InvalidOperationException(Strings.CurrentHttpContextRequired); } // Build the return_to URL UriBuilder returnTo = new UriBuilder(Util.GetRequestUrlFromContext()); // Trim off any parameters with an "openid." prefix, and a few known others // to avoid carrying state from a prior login attempt. returnTo.Query = string.Empty; NameValueCollection queryParams = Util.GetQueryFromContextNVC(); var returnToParams = new Dictionary <string, string>(queryParams.Count); foreach (string key in queryParams) { if (!ShouldParameterBeStrippedFromReturnToUrl(key)) { returnToParams.Add(key, queryParams[key]); } } UriUtil.AppendQueryArgs(returnTo, returnToParams); return(CreateRequests(userSuppliedIdentifier, realm, returnTo.Uri)); }
private async Task <R> Send <T, R>(HttpMethod method, string uri, T postData, IDictionary <string, string> parameters) { // Create content if needed HttpContent content = CreateContent(method, postData); // bind parameters and send string parameterUri = UriUtil.BindParameters(uri, parameters); HttpResponseMessage response = null; if (modifier != null) { var request = new HttpRequestMessage(method, parameterUri); request.Content = content; modifier.ModifyRequest(request, uri, parameters); response = await client.SendAsync(request).ConfigureAwait(false); } else { response = await SendAsync(method, parameterUri, content).ConfigureAwait(false); } if (!response.IsSuccessStatusCode) { throw new HttpResponseException(response); } return(await response.Content.ReadAsAsync <R>()); }
public string GetSectionGroupUrl(string groupName) { string url = UriUtil.AddQueryString(HttpContext.Current.Request.RawUrl, "t", HttpContext.Current.Server.UrlEncode(groupName)); url = UriUtil.AddQueryString(url, "p", "1"); return(url); }
public void Throws_InvalidOperationException_If_QueryStringCollection_Is_Null_When_Needed() { // Assert Assert.Throws <InvalidOperationException>(() => // Act UriUtil.ResolveUriTemplate( "api/cars?name={name}&surname={surname}", null)); }
private PaymentProcessingResult ProcessPaymentCheckout(IPayment payment, ICart cart) { var merchRef = DateTime.Now.Ticks.ToString(); payment.Properties[DataCashMerchantReferencePropertyName] = merchRef; // A unique reference number for each transaction (Min 6, max 30 alphanumeric character) var notifyUrl = UriSupport.AbsoluteUrlBySettings(Utilities.GetUrlFromStartPageReferenceProperty("DataCashPaymentPage")); notifyUrl = UriUtil.AddQueryString(notifyUrl, "accept", "true"); notifyUrl = UriUtil.AddQueryString(notifyUrl, "hash", Utilities.GetSHA256Key(merchRef + "accepted")); var requestDoc = _requestDocumentCreation.CreateDocumentForPaymentCheckout(cart, payment, notifyUrl); var responseDoc = DocumentHelpers.SendTransaction(requestDoc, _dataCashConfiguration.Config); string redirectUrl; if (DocumentHelpers.IsSuccessful(responseDoc)) { redirectUrl = $"{responseDoc.get("Response.HpsTxn.hps_url")}?HPS_SessionID={responseDoc.get("Response.HpsTxn.session_id")}"; payment.Properties[DataCashReferencePropertyName] = responseDoc.get("Response.datacash_reference"); } else { return(PaymentProcessingResult.CreateUnsuccessfulResult(DocumentHelpers.GetErrorMessage(responseDoc))); } _orderRepository.Save(cart); var message = $"---DataCash--. Redirect end user to {redirectUrl}"; _logger.Information(message); return(PaymentProcessingResult.CreateSuccessfulResult(message, redirectUrl)); }
public ActionResult Index() { if (PageEditing.PageIsInEditMode) { return(new EmptyResult()); } var currentCart = _orderRepository.LoadCart <ICart>(PrincipalInfo.CurrentPrincipal.GetContactId(), Cart.DefaultName + SiteDefinition.Current.StartPage.ID); if (!currentCart.Forms.Any() || !currentCart.GetFirstForm().Payments.Any()) { throw new PaymentException(PaymentException.ErrorType.ProviderError, "", "Generic Error"); } var payooConfiguration = new PayooConfiguration(); var payment = currentCart.Forms.SelectMany(f => f.Payments).FirstOrDefault(c => c.PaymentMethodId.Equals(payooConfiguration.PaymentMethodId)); if (payment == null) { throw new PaymentException(PaymentException.ErrorType.ProviderError, "", "Payment Not Specified"); } var orderNumber = payment.Properties[Constant.PayooOrderNumberPropertyName] as string; if (string.IsNullOrEmpty(orderNumber)) { throw new PaymentException(PaymentException.ErrorType.ProviderError, "", "Payment Not Specified"); } // Redirect customer to receipt page var paymentResult = ExtractPaymentResultFromPayoo(); var cancelUrl = _cmsPaymentPropertyService.GetCancelledPaymentUrl(); // get link to Checkout page cancelUrl = UriUtil.AddQueryString(cancelUrl, "success", "false"); cancelUrl = UriUtil.AddQueryString(cancelUrl, "paymentmethod", "payoo"); var redirectUrl = cancelUrl; if (VerifyChecksumIsValid(payooConfiguration.ChecksumKey, orderNumber, paymentResult)) { var gateway = new PayooPaymentGateway(); if (paymentResult.IsSuccess) { var acceptUrl = _cmsPaymentPropertyService.GetAcceptedPaymentUrl(); redirectUrl = gateway.ProcessSuccessfulTransaction(currentCart, payment, acceptUrl, cancelUrl); } else { var message = paymentResult.Status.Equals("0") ? "Payment failed" : "Payment cancelled"; TempData[Constant.ErrorMessages] = $"{message}. Payoo Message: {paymentResult.ErrorCode}-{paymentResult.ErrorMsg}"; redirectUrl = gateway.ProcessUnsuccessfulTransaction(cancelUrl, message); } } else { TempData[Constant.ErrorMessages] = "The Payoo checksum is invalid"; } return(Redirect(redirectUrl)); }
private static Link CreateLink(QueryLink source, RenderContext ctx) { var linkedQuery = ctx.Injector.CreateInstance(source.QueryType); source.Setter?.Invoke(linkedQuery); var targets = from renderer in ctx.PaperRendererRegistry.FindPaperRenderers(source.QueryType) where renderer.PaperRendererType == typeof(QueryRenderer) let argNames = UriUtil.GetArgNames(renderer.PathTemplate) orderby argNames.Length descending select new { renderer, argNames }; foreach (var target in targets) { var pathTemplate = target.renderer.PathTemplate; var argNames = target.argNames; var pathArgs = QueryPathBuilder.SatisfyArgs(linkedQuery, argNames); var isAllArgsSatisfied = !pathArgs.Any(x => x.Value == null); if (isAllArgsSatisfied) { var href = QueryPathBuilder.BuildPath(ctx, linkedQuery, pathTemplate, pathArgs, null); var link = new Link().CopyFrom(source); link.Href = href; return(link); } } return(null); }
/// <summary> /// Processes the successful transaction, will be called when DIBS server processes /// the payment successfully and redirect back. /// </summary> /// <param name="cart">The cart that was processed.</param> /// <param name="payment">The order payment.</param> /// <param name="transactionID">The transaction id.</param> /// <param name="orderNumber">The order number.</param> /// <param name="acceptUrl">The redirect url when finished.</param> /// <param name="cancelUrl">The redirect url when error happens.</param> /// <returns>The redirection url after processing.</returns> public string ProcessSuccessfulTransaction(ICart cart, IPayment payment, string transactionID, string orderNumber, string acceptUrl, string cancelUrl) { if (cart == null) { return(cancelUrl); } string redirectionUrl; // Change status of payments to processed. // It must be done before execute workflow to ensure payments which should mark as processed. // To avoid get errors when executed workflow. PaymentStatusManager.ProcessPayment(payment); var errorMessages = new List <string>(); var cartCompleted = DoCompletingCart(cart, errorMessages); if (!cartCompleted) { return(UriUtil.AddQueryString(cancelUrl, "message", string.Join(";", errorMessages.Distinct().ToArray()))); } // Save the transact from DIBS to payment. payment.TransactionID = transactionID; var purchaseOrder = MakePurchaseOrder(cart, orderNumber); redirectionUrl = UpdateAcceptUrl(purchaseOrder, payment, acceptUrl); return(redirectionUrl); }
public IEnumerable <Label> GetBoundingBoxes(Topic topic, string imageId) { #region validation if (topic == null) { throw new ArgumentNullException(nameof(topic)); } if (string.IsNullOrEmpty(imageId)) { throw new ArgumentNullException(nameof(imageId)); } #endregion var modelId = LoadModel(); MultipartFormDataContent multipartFormDataContent = new MultipartFormDataContent(); using (Stream imageFileStream = ImageFileRepository.GetImageFile(topic, imageId)) { multipartFormDataContent.AddFileAsByteContent(imageFileStream, "image", imageId); } multipartFormDataContent.Add(new StringContent(modelId), "model"); HttpClient httpClient = HttpClientFactory.GetInferenceContainerHttpClient(); Uri uri = UriUtil.GetUri(httpClient.BaseAddress, "detect"); using MemoryStream memoryStream = new MemoryStream(httpClient.PostReadByteArray(uri, multipartFormDataContent)); using StreamReader streamReader = new StreamReader(memoryStream); return(ParseLabelResult(streamReader.ReadToEnd())); }
/// <summary> /// Processes the successful transaction, was called when Payoo Gateway redirect back. /// </summary> /// <param name="orderGroup">The order group that was processed.</param> /// <param name="payment">The order payment.</param> /// <param name="acceptUrl">The redirect url when finished.</param> /// <param name="cancelUrl">The redirect url when error happens.</param> /// <returns>The url redirection after process.</returns> public string ProcessSuccessfulTransaction(IOrderGroup orderGroup, IPayment payment, string acceptUrl, string cancelUrl) { if (HttpContext.Current == null) { return(cancelUrl); } var cart = orderGroup as ICart; if (cart == null) { // return to the shopping cart page immediately and show error messages return(ProcessUnsuccessfulTransaction(cancelUrl, "Commit Tran Error Cart Null")); } // everything is fine var errorMessages = new List <string>(); var cartCompleted = _payooCartService.DoCompletingCart(cart, errorMessages); if (!cartCompleted) { return(UriUtil.AddQueryString(cancelUrl, "message", string.Join(";", errorMessages.Distinct().ToArray()))); } // Place order var purchaseOrder = _payooCartService.MakePurchaseOrder(cart, payment); var redirectionUrl = CreateRedirectionUrl(purchaseOrder, acceptUrl); _logger.Info($"Payoo transaction succeeds, redirect end user to {redirectionUrl}"); return(redirectionUrl); }
public string DisplayValue(object value, Tk5FieldInfoEx field, IFieldValueProvider rowValue, string linkedValue) { if (rowValue == null) { return(linkedValue); } string linkUrl = ResolveRowValue(rowValue, Content); if (string.IsNullOrEmpty(linkUrl)) { return(linkedValue); } else { linkUrl = AppUtil.ResolveUrl(linkUrl); } string target; if (!string.IsNullOrEmpty(Base)) { linkUrl = UriUtil.CombineUri(Base, linkUrl).ToString(); } if (!string.IsNullOrEmpty(Target)) { target = string.Format(ObjectUtil.SysCulture, " target=\"{0}\"", Target); } else { target = string.Empty; } return(string.Format(ObjectUtil.SysCulture, "<a href=\"{0}\"{1}>{2}</a>", StringUtil.EscapeHtmlAttribute(linkUrl), target, StringUtil.EscapeHtml(linkedValue))); }
protected Task <HttpApiResponseMessage <TResult> > PutAsync <TRequestModel>(string uriTemplate, TRequestModel requestModel, object uriParameters, CancellationToken cancellationToken) { string requestUri = UriUtil.BuildRequestUri(_baseUri, uriTemplate, uriParameters: uriParameters); return(_httpClient.PutAsync <TRequestModel>(requestUri, requestModel, _writerMediaTypeFormatter, cancellationToken) .GetHttpApiResponseAsync <TResult>(_formatters)); }
/// <summary> /// Copies the file at the given path to the server, which could be anywhere from /// the local machine to a remote one. /// </summary> /// <param name="virtualPath">The virtual path.</param> public void CopyToServer(VirtualPath virtualPath) { var fromFullPath = _pathFactory.CreateShadwoFullPath4Write(virtualPath); byte[] infoBytes = _serverProxy.Get(new Uri("/BitTorrent/Info")); var infoObj = XmlUtil.FromXml <BitTorrentServiceInfo>( Encoding.UTF8.GetString(infoBytes)); if (infoObj.ServerCacheUri.IsLoopback) { // Server on the same machine, we copy from file system. var relativePath = virtualPath.PathString.Substring( virtualPath.PathString.IndexOf(Path.DirectorySeparatorChar, 1)); var toFullPath = UriUtil.CombinePaths(infoObj.ServerCacheUri.LocalPath, new Uri(relativePath, UriKind.Relative)); IOUtil.PrepareParentDirForPath(toFullPath); if (SysEnvironment.OSVersion == OS.Unix) { // In case of Unix, we actually use symbolic link instead of copying. var symlink = new UnixSymbolicLinkInfo(toFullPath); Logger.WriteLineIf(LogLevel.Verbose, _log_props, string.Format( "Creating Symlink: {0} -> {1}", toFullPath, fromFullPath.PathString)); // Linking toPath to fromPath == Copy fromPath to toPath. symlink.CreateSymbolicLinkTo(fromFullPath.PathString); } else { throw new NotImplementedException("Only Unix hosts are currently supported."); } } else { throw new NotImplementedException("Only local machine is currently supported."); } }
public override void doGetListItemsInfo(int pageIndex) { HtmlNodeCollection items = getItemsInPage(pageIndex); if (items != null) { for (int j = 0; j < items.Count; j++) { while (stopInsertFlag) { Thread.Sleep(10); } string href = items[j].Attributes["href"].Value; movie movieItemInfo = getMovieItemInfo(UriUtil.checkAndAddDomain(href, victimDomain, protocol)); if (movieItemInfo == null) { continue; } saveNewMovie(movieItemInfo); } pageIndex++; doGetListItemsInfo(pageIndex); } else { System.Windows.Forms.MessageBox.Show("[" + victimDomain + "] - doGetListItemsInfo finished!!!"); } }
public void UriUtil_ValidUri_Test() { var relativeUrl = "test/1.html"; Assert.True(UriUtil.IsValidUri(relativeUrl)); var absoluteUrl = "/test/1.html"; Assert.True(UriUtil.IsValidUri(absoluteUrl)); Assert.True(UriUtil.IsValidUri(dataUrl)); var httpUrl = "http://test.com/1"; Assert.True(UriUtil.IsValidUri(httpUrl)); if (UriUtil.IsWin()) { var windowsUrl = @"c:\1\2\"; Assert.True(UriUtil.IsValidUri(windowsUrl)); var windowsUrl2 = @"\1\2\"; Assert.True(UriUtil.IsValidUri(windowsUrl2)); } else { var unixUrl = "/1/2/"; Assert.True(UriUtil.IsValidUri(unixUrl)); } var fileUrl = "file:///d:/1/2"; Assert.True(UriUtil.IsValidUri(fileUrl)); }
/// <summary>uri to edit the entity</summary> /// <param name="baseUriResolver">retrieves the baseUri to use for a given entity set.</param> /// <param name="queryLink">whether to return the query link or edit link</param> /// <returns>absolute uri which can be used to edit the entity</returns> internal Uri GetResourceUri(UriResolver baseUriResolver, bool queryLink) { // If the entity was inserted using the AddRelatedObject API if (this.ParentEntityDescriptor != null) { // This is the batch scenario, where the entity might not have been saved yet, and there is another operation // (for e.g. PUT $1/links/BestFriend or something). Hence we need to generate a Uri with the changeorder number. if (this.ParentEntityDescriptor.Identity == null) { Uri relativeReferenceUri = UriUtil.CreateUri("$" + this.ParentEntityDescriptor.ChangeOrder.ToString(CultureInfo.InvariantCulture), UriKind.Relative); Uri absoluteReferenceUri = baseUriResolver.GetOrCreateAbsoluteUri(relativeReferenceUri); Uri requestUri = UriUtil.CreateUri(this.ParentProperty, UriKind.Relative); return(UriUtil.CreateUri(absoluteReferenceUri, requestUri)); } else { Debug.Assert(this.ParentEntityDescriptor.ParentEntityDescriptor == null, "This code assumes that parentChild relationships will only ever be one level deep"); Debug.Assert(this.ParentProperty != null, "ParentProperty != null"); LinkInfo linkInfo; if (this.ParentEntityDescriptor.TryGetLinkInfo(this.ParentProperty, out linkInfo)) { if (linkInfo.NavigationLink != null) { return(linkInfo.NavigationLink); } } return(UriUtil.CreateUri(this.ParentEntityDescriptor.GetLink(queryLink), this.GetLink(queryLink))); } } else { return(this.GetLink(queryLink)); } }
public void UriUtil_Combine_Test() { var http = "http:/test.com"; var rPath = "test/test.html"; Assert.Equal(http + "/" + rPath, UriUtil.Combine(http, rPath)); if (UriUtil.IsWin()) { var root = @"\test\test"; var rPath2 = @"\test\test.html"; Assert.Equal("/test/test/test/test.html", UriUtil.Combine(root, rPath2)); var rPath3 = @"..\test\test.html"; var cPath = UriUtil.Combine(root, rPath3); var pRoot = Path.GetPathRoot(Path.GetFullPath("/")); Assert.Equal($@"{pRoot}test\test\test.html", Path.GetFullPath(cPath)); } else { var root = "/test/test"; var rPath2 = "/test/test.html"; Assert.Equal("/test/test/test/test.html", UriUtil.Combine(root, rPath2)); var rPath3 = "../test/test.html"; var cPath = UriUtil.Combine(root, rPath3); var pRoot = Path.GetPathRoot(Path.GetFullPath("/")); Assert.Equal($@"{pRoot}test/test/test.html", Path.GetFullPath(cPath)); } }
/// <summary> /// Convert a matched basic path template (/Controller/Namespace/Name) to /// request Uri /// </summary> /// <param name="match">The match.</param> /// <param name="extraParams">Extra parameters as query parameters.</param> /// <returns></returns> private static Uri BasicPathMatch2ReqUri(UriTemplateMatch match, NameValueCollection extraParams) { // The path qualifies for this operation. Now get the real path. var nsStr = match.BoundVariables[1]; var nameStr = match.BoundVariables[2]; match.QueryParameters.Remove(OnDemandParamName); string queryString = ""; if (match.QueryParameters.Count > 0) { queryString = "?" + UriUtil.JoinNvcToQs(match.QueryParameters); } if (extraParams != null && extraParams.Count > 0) { string qs2 = UriUtil.JoinNvcToQs(extraParams); queryString += (string.IsNullOrEmpty(queryString) ? "?" + qs2 : "&" + qs2); } // BitTorrent/nameSpace/name var reqUri = new Uri(string.Format("/{0}/{1}/{2}", ServerControllerName, nsStr, nameStr) + queryString, UriKind.Relative); // Get the meta info for the path. return(reqUri); }
private static void ValidateEncodedImageRequest(ImageRequest imageRequest) { Preconditions.CheckNotNull(imageRequest); Preconditions.CheckArgument(UriUtil.IsNetworkUri(imageRequest.SourceUri)); Preconditions.CheckArgument( imageRequest.LowestPermittedRequestLevel.Value <= RequestLevel.ENCODED_MEMORY_CACHE); }
/// <summary> /// Reads the input request payload and returns the WCF DS value representation of it. /// </summary> /// <param name="segmentInfo">Info about the request to read. For entity reference requests this is null.</param> /// <returns>The WCF DS representation of the value read. For entity reference link this is the Uri of the link.</returns> protected override object Read(SegmentInfo segmentInfo) { Debug.Assert(segmentInfo == null, "segmentInfo == null"); Debug.Assert(this.RequestDescription.LinkUri, "The EntityReferenceLinkDeserializer only supports $ref payloads."); ODataEntityReferenceLink entityReferenceLink = this.MessageReader.ReadEntityReferenceLink(); Debug.Assert(entityReferenceLink != null, "ReadEntityReferenceLink should never return null."); Uri entityReferenceUri = entityReferenceLink.Url; Debug.Assert(entityReferenceUri != null, "The Url of the entity reference link should never be null."); #pragma warning disable 618 AssertReaderFormatIsExpected(this.MessageReader, ODataFormat.Atom, ODataFormat.Json); #pragma warning restore 618 // We must fail on empty URI string entityReferenceUriAsString = UriUtil.UriToString(entityReferenceUri); if (string.IsNullOrEmpty(entityReferenceUriAsString)) { throw DataServiceException.CreateBadRequestError(Microsoft.OData.Service.Strings.BadRequest_MissingUriForLinkOperation); } // Resolve the URI against the service return(RequestUriProcessor.GetAbsoluteUriFromReference(entityReferenceUri, this.Service.OperationContext.AbsoluteServiceUri)); }
private void _showSourceButton_Click(object sender, EventArgs e) { if (UriUtil.IsHttpUri(_sourceTextBox.Text) || UriUtil.IsFileUri(_sourceTextBox.Text)) { Process.Start(_sourceTextBox.Text); } }
private IDataSource <CloseableReference <T> > SubmitFetchRequest <T>( IProducer <CloseableReference <T> > producerSequence, ImageRequest imageRequest, RequestLevel lowestPermittedRequestLevelOnSubmit, object callerContext) { IRequestListener requestListener = GetRequestListenerForRequest(imageRequest); try { RequestLevel lowestPermittedRequestLevel = RequestLevel.GetMax( imageRequest.LowestPermittedRequestLevel, lowestPermittedRequestLevelOnSubmit); SettableProducerContext settableProducerContext = new SettableProducerContext( imageRequest, GenerateUniqueFutureId(), requestListener, callerContext, lowestPermittedRequestLevel.Value, /* isPrefetch */ false, imageRequest.IsProgressiveRenderingEnabled || !UriUtil.IsNetworkUri(imageRequest.SourceUri), imageRequest.Priority); return(CloseableProducerToDataSourceAdapter <T> .Create( producerSequence, settableProducerContext, requestListener)); } catch (Exception exception) { return(DataSources.ImmediateFailedDataSource <CloseableReference <T> >(exception)); } }
private SetExpressCheckoutRequestDetailsType SetupExpressCheckoutReqDetailsType(ICart cart, IPayment payment, string orderNumber) { var setExpressChkOutReqDetails = _payPalAPIHelper.CreateExpressCheckoutReqDetailsType(payment, _paymentMethodConfiguration); // This key is sent to PayPal using https so it is not likely it will come from other because // only PayPal knows this key to send back to us var acceptSecurityKey = Utilities.GetAcceptUrlHashValue(orderNumber); var cancelSecurityKey = Utilities.GetCancelUrlHashValue(orderNumber); _notifyUrl = UriSupport.AbsoluteUrlBySettings(Utilities.GetUrlFromStartPageReferenceProperty("PayPalPaymentPage")); var acceptUrl = UriUtil.AddQueryString(_notifyUrl, "accept", "true"); acceptUrl = UriUtil.AddQueryString(acceptUrl, "hash", acceptSecurityKey); var cancelUrl = UriUtil.AddQueryString(_notifyUrl, "accept", "false"); cancelUrl = UriUtil.AddQueryString(cancelUrl, "hash", cancelSecurityKey); setExpressChkOutReqDetails.CancelURL = cancelUrl; setExpressChkOutReqDetails.ReturnURL = acceptUrl; setExpressChkOutReqDetails.PaymentDetails = new List <PaymentDetailsType>() { _payPalAPIHelper.GetPaymentDetailsType(payment, cart, orderNumber, _notifyUrl) }; setExpressChkOutReqDetails.BillingAddress = AddressHandling.ToAddressType(payment.BillingAddress); return(setExpressChkOutReqDetails); }
/// <summary> /// Translates resource bound expression tree to a URI. /// </summary> /// <param name='context'>Data context used to generate type names for types.</param> /// <param name="addTrailingParens">flag to indicate whether generated URI should include () if leaf is ResourceSet</param> /// <param name="e">The expression to translate</param> /// <param name="uri">uri</param> /// <param name="version">version for query</param> internal static void Translate(DataServiceContext context, bool addTrailingParens, Expression e, out Uri uri, out Version version) { var writer = new UriWriter(context); writer.Visit(e); string fullUri = writer.uriBuilder.ToString(); if (writer.alias.Any()) { if (fullUri.IndexOf(UriHelper.QUESTIONMARK) > -1) { fullUri += UriHelper.AMPERSAND; } else { fullUri += UriHelper.QUESTIONMARK; } foreach (var kv in writer.alias) { fullUri += kv.Key; fullUri += UriHelper.EQUALSSIGN; fullUri += kv.Value; fullUri += UriHelper.AMPERSAND; } fullUri = fullUri.Substring(0, fullUri.Length - 1); } uri = UriUtil.CreateUri(fullUri, UriKind.Absolute); version = writer.uriVersion; }
/// <summary>Loads the collection asynchronously by loading the results from the request Uri.</summary> /// <param name="requestUri">The request uri to download results from.</param> /// <remarks>This method uses the event-based async pattern. /// The method returns immediately without waiting for the query to complete. Then it calls the handler of the /// <see cref="LoadCompleted"/> event exactly once on the UI thread. The event will be raised regradless /// if the query succeeded or not. /// This class only support one asynchronous operation in flight.</remarks> public void LoadAsync(Uri requestUri) { Util.CheckArgumentNull(requestUri, "requestUri"); if (!this.IsTracking) { throw new InvalidOperationException(Strings.DataServiceCollection_OperationForTrackedOnly); } if (this.ongoingAsyncOperation != null) { throw new InvalidOperationException(Strings.DataServiceCollection_MultipleLoadAsyncOperationsAtTheSameTime); } DataServiceContext context = this.observer.Context; requestUri = UriUtil.CreateUri(context.BaseUri, requestUri); this.BeginLoadAsyncOperation( asyncCallback => context.BeginExecute <T>(requestUri, asyncCallback, null), asyncResult => { QueryOperationResponse <T> response = (QueryOperationResponse <T>)context.EndExecute <T>(asyncResult); this.Load(response); return(response); }); }
/// <summary> /// Peforms DELETE method /// </summary> /// <param name="uri"></param> /// <param name="query"></param> public void Delete(string uri, List <KeyValuePair <string, object> > query) { uri = UriUtil.BuildUri(uri, query); try { HttpCompletionOption option = HttpCompletionOption.ResponseContentRead; HttpRequestMessage request = CreateDeleteRequest(uri); Task <HttpResponseMessage> response = _httpClient.SendAsync(request, option); long tStart = DateTime.Now.Ticks; HttpResponseMessage message = response.Result; long time = ((DateTime.Now.Ticks - tStart) / TimeSpan.TicksPerMillisecond); long?requestSize = request.Content == null ? 0L : request.Content.Headers.ContentLength; long?contentSize = message.Content == null ? 0L : message.Content.Headers.ContentLength; LogPerformance(time, request.Method.ToString(), uri, requestSize == null ? 0L : requestSize.Value, contentSize == null ? 0L : contentSize.Value); message.EnsureSuccessStatusCode(); } catch (Exception e) { WriteToLog(LogLevel.ERROR, this.GetType().Name, "Error URI: " + uri, e); if (e.InnerException is TaskCanceledException) { throw new Exception("A timeout occurred waiting on a response from request: " + uri, e.InnerException); } } }
/// <summary> /// Get a new URI string by adding <paramref name="nextSegment"/> to the original one. /// </summary> /// <param name="nextSegment">Name of the action.</param> /// <returns>The new URI string.</returns> #pragma warning disable CA1055 // Uri return values should not be strings public virtual string AppendRequestUri(string nextSegment) #pragma warning restore CA1055 // Uri return values should not be strings { Uri requestUri = this.RequestUri; return(UriUtil.UriToString(requestUri).Replace(requestUri.AbsolutePath, requestUri.AbsolutePath + UriHelper.FORWARDSLASH + nextSegment)); }
public void InvalidUriTest() { Assert.IsFalse(UriUtil.TryBuildUri("this is not a URL", out var result)); Assert.IsNull(result); Assert.IsFalse(UriUtil.TryBuildUri(string.Empty, out result)); Assert.IsNull(result); }