protected override Stream LoadFile() { if (string.IsNullOrEmpty(_document.Key)) { return(Stream.Null); } if (_formMode) { var results = _client.Execute <byte[]>(new SDataParameters { Path = "libraryDocuments(" + SDataUri.FormatConstant(_document.Key) + ")/file" }); return(results.Content != null ? new MemoryStream(results.Content) : Stream.Null); } else { var results = _client.Execute(new SDataParameters { Path = "libraryDocuments(" + SDataUri.FormatConstant(_document.Key) + ")", Precedence = 0, ExtensionArgs = { { "includeFile", "true" } } }); return(results.Files.Count == 1 ? results.Files[0].Stream : Stream.Null); } }
protected override void BuildUrl(SDataUri uri) { base.BuildUrl(uri); uri.AppendPath("$system"); uri.AppendPath("registry"); uri.AppendPath("endpoints"); }
/// <summary> /// Adds a url to the batch for processing /// </summary> /// <param name="item">url for batch item</param> /// <returns>True if an appropriate pending batch operation was found</returns> public bool AddToBatch(SDataBatchRequestItem item) { Guard.ArgumentNotNull(item, "item"); var uri = new SDataUri(item.Url) { CollectionPredicate = null, Query = null }; if (uri.PathSegments.Length > 4) { uri.TrimRange(4, uri.PathSegments.Length - 4); } uri.AppendPath("$batch"); var baseUri = uri.ToString(); var request = _requests.LastOrDefault(x => string.Equals(x.ToString(), baseUri, StringComparison.InvariantCultureIgnoreCase)); if (request != null) { request.Items.Add(item); return(true); } return(false); }
/// <summary> /// Asynchronous PUT to the server /// </summary> /// <param name="request">The request that identifies the resource within the syndication data source.</param> /// <param name="resource">The resource that should be created asynchronously.</param> public virtual AsyncRequest CreateAsync(SDataBaseRequest request, ISyndicationResource resource) { Guard.ArgumentNotNull(request, "request"); Guard.ArgumentNotNull(resource, "resource"); try { var url = new SDataUri(request.ToString()) { TrackingId = Guid.NewGuid().ToString() }.ToString(); var operation = new RequestOperation(HttpMethod.Post, resource); var response = ExecuteRequest(url, operation, MediaType.Xml); var tracking = response.Content as Tracking; if (tracking == null) { throw new SDataClientException("Unexpected content: " + response.Content); } return(new AsyncRequest(this, response.Location, tracking)); } catch (SDataClientException) { throw; } catch (Exception ex) { throw new SDataClientException(ex.Message, ex); } }
private SDataRequest CreateRequest(SDataUri uri, HttpMethod method, object content) { var request = _requestFactory(uri.AbsoluteUri); request.Method = method; request.Content = content; request.UserName = UserName; request.Password = Password; request.Authenticator = Authenticator; request.Credentials = Credentials; request.NamingScheme = NamingScheme; request.Cookies = _cookies; request.UseHttpMethodOverride = UseHttpMethodOverride; request.MaxGetUriLength = MaxGetUriLength; #if !PCL && !SILVERLIGHT request.Proxy = Proxy; #endif #if !PCL && !NETFX_CORE && !SILVERLIGHT request.UserAgent = UserAgent; if (Timeout != null) { request.Timeout = Timeout.Value; } #endif if (TimeoutRetryAttempts != null) { request.TimeoutRetryAttempts = TimeoutRetryAttempts.Value; } return(request); }
/// <summary> /// function to format url string for the request /// </summary> /// <returns>formatted string</returns> public override string ToString() { var uri = new SDataUri(Uri.Uri.AbsoluteUri); BuildUrl(uri); return(uri.Uri.AbsoluteUri.Replace("%20", " ")); }
private void _resultExecutionButton_Click(object sender, EventArgs e) { var refresh = false; foreach (var execution in SelectedExecutions) { try { var results = _client.Execute <string>(new SDataParameters { Path = "executions(" + SDataUri.FormatConstant(execution.Key) + ")/result" }); using (var form = new ResultForm()) { form.ShowDialog(results.Content, this); } } catch (SDataException ex) { MessageBox.Show(string.Format("Error getting execution '{0}' result\r\n{1}", execution.Key, ex.Message)); if (ex.StatusCode == HttpStatusCode.Gone) { ((ICollection <Execution>)_executionsGrid.DataSource).Remove(execution); refresh = true; } } } if (refresh) { _executionsGrid.Refresh(); _executionsGrid.AutoResizeColumns(); } }
private IEnumerable <TEntity> GetEntitiesFromSData(string sdataQuery) { var request = CreateCollectionRequest(); SDataUri uri = new SDataUri(sdataQuery); if (!string.IsNullOrEmpty(uri.Where)) { request.QueryValues["where"] = uri.Where; } if (uri.QueryArgs.ContainsKey("select")) { request.QueryValues["select"] = uri.QueryArgs["select"]; } Type concreteEntityType = FindConcreteEntityType(); var reader = request.ExecuteReader(); var currentEntry = reader.Current; //resorting to a while loop since the reader seems to have a bug where it modifies the enumeration while (currentEntry != null) { var entity = Activator.CreateInstance(concreteEntityType) as IPersistentEntity; CopyAtomEntryToEntity(currentEntry, entity); yield return((TEntity)entity); currentEntry = reader.Next() ? reader.Current : null; } }
private void FormatURL() { try { var server = tbServer.Text; var pos = server.IndexOf(':'); var uri = new SDataUri(); int port; if (pos >= 0 && int.TryParse(server.Substring(pos + 1), out port)) { server = server.Substring(0, pos); uri.Port = port; } uri.Scheme = cbProtocol.Text; uri.Host = server; uri.Server = tbVirtualDirectory.Text; uri.Product = tbApplication.Text; uri.Contract = tbContract.Text; uri.CompanyDataset = tbDataSet.Text; tbURL.Text = uri.ToString(); } catch (UriFormatException) { } }
private void btnInitialize_Click(object sender, EventArgs e) { var server = tbServer.Text; var pos = server.IndexOf(':'); int port; if (pos >= 0 && int.TryParse(server.Substring(pos + 1), out port)) { server = server.Substring(0, pos); } else { port = 80; } var uri = new SDataUri { Scheme = cbProtocol.Text, Host = server, Port = port }; uri.AppendPath(tbVirtualDirectory.Text, tbApplication.Text, tbContract.Text, tbDataSet.Text); Client.Uri = uri.ToString(); Client.UserName = tbUserName.Text; Client.Password = tbPassword.Text; StatusLabel.Text = "SData client initialized."; }
private string buildId(SDataUri uri, string p) { if (!uri.HasCollectionPredicate) { return(uri.FullPath + "('" + p + "')"); } return(uri.ToString()); }
protected override void BuildUrl(SDataUri uri) { base.BuildUrl(uri); foreach (var value in ResourceProperties) { uri.AppendPath(value); } }
protected override void BuildUrl(SDataUri uri) { base.BuildUrl(uri); if (!string.IsNullOrEmpty(ResourceKind)) { uri.AppendPath(ResourceKind); } }
public override void Save(Stream stream) { if (stream == null) { _document = string.IsNullOrEmpty(_document.Key) ? _client.Post(_document) : _client.Put(_document); return; } var parms = new SDataParameters { Files = { new AttachedFile(null, _document.FileName, stream) } }; if (string.IsNullOrEmpty(_document.Key)) { parms.Method = HttpMethod.Post; parms.Path = "libraryDocuments"; } else { parms.Method = HttpMethod.Put; parms.Path = "libraryDocuments(" + SDataUri.FormatConstant(_document.Key) + ")"; parms.ETag = _document.ETag; } if (_formMode) { foreach (var prop in typeof(LibraryDocument).GetProperties()) { var name = _client.NamingScheme.GetName(prop); if (!name.StartsWith("$", StringComparison.Ordinal) && !new[] { "createDate", "createUser", "modifyDate", "modifyUser" }.Contains(name, StringComparer.Ordinal)) { var value = prop.GetValue(_document, null); if (value != null) { parms.Form[name] = value.ToString(); } } } parms.Path += "/file"; var results = _client.Execute(parms); if (!string.IsNullOrEmpty(results.Location)) { var selector = new SDataUri(results.Location).GetPathSegment(4).Selector; _document.Key = selector.Substring(1, selector.Length - 2); _document.ETag = results.ETag; } } else { parms.Content = _document; _document = _client.Execute <LibraryDocument>(parms).Content; } }
static commodityFeedEntry GetCommodity(string productName, int productCount) { // Look up the first commodity (product) record string url = dataSourceTest + "commodities"; SDataUri commodityUri = new SDataUri(url); commodityUri.Count = productCount; SDataRequest commodityRequest = new SDataRequest(commodityUri.Uri); commodityRequest.Username = username; commodityRequest.Password = password; commodityFeed commodities = new commodityFeed(); commodityRequest.RequestFeed <commodityFeedEntry>(commodities); // If we found a record return it if (commodityRequest.IsStatusValidForVerb && commodities.Entries != null && commodities.Entries.Count > 0) { foreach (commodityFeedEntry commodity in commodities.Entries) { if (commodity.name.Equals(productName, StringComparison.InvariantCultureIgnoreCase)) { Console.WriteLine(string.Format("name: {0}", commodity.name)); Console.WriteLine(string.Format("name: {0}", commodity.UUID)); return(commodity); } else { continue; } } Console.ReadKey(); return(null); } else { // There was a problem Console.WriteLine("Commodity lookup failed. Response was {0}", commodityRequest.HttpStatusCode.ToString()); if (commodityRequest.Diagnoses != null) { foreach (Diagnosis diagnosis in commodityRequest.Diagnoses) { Console.WriteLine(diagnosis.Message); } } Console.ReadLine(); return(null); } }
public void Appending_Segments_To_Specific_Service_Urls_Test() { var uri = new SDataUri("http://test.com/sdata/-/-/-/resource/$service/name"); uri.AppendPath("test"); Assert.AreEqual("resource", uri.CollectionType); Assert.AreEqual("name", uri.ServiceMethod); Assert.AreEqual("-/-/-/resource/$service/name/test", uri.DirectPath); Assert.AreEqual("http://test.com/sdata/-/-/-/resource/$service/name/test", uri.ToString()); }
protected override void BuildUrl(SDataUri uri) { base.BuildUrl(uri); uri.AppendPath(ServiceTerm); if (!string.IsNullOrEmpty(OperationName)) { uri.AppendPath(OperationName); } }
public void Appending_Segments_To_Specific_Service_Urls_Test() { var uri = new SDataUri("http://test.com/sdata/-/-/-/resource/$service/name"); uri.AppendPath("test"); Assert.AreEqual("resource", uri.GetPathSegment(4).Text); Assert.AreEqual("name", uri.GetPathSegment(6).Text); Assert.AreEqual("sdata/-/-/-/resource/$service/name/test", uri.DirectPath); Assert.AreEqual("http://test.com/sdata/-/-/-/resource/$service/name/test", uri.ToString()); }
protected SDataBaseRequest(ISDataService service) { Guard.ArgumentNotNull(service, "service"); _service = service; _uri = new SDataUri(); Protocol = service.Protocol; ServerName = service.ServerName; Port = service.Port; VirtualDirectory = !string.IsNullOrEmpty(service.VirtualDirectory) ? service.VirtualDirectory : "sdata"; }
public void Assign_Ampersand_In_Query_Test() { var uri = new SDataUri("http://localhost:2001/sdata/aw/dynamic/-/accounts") { Query = "a=%26&b=%26" }; Assert.That(uri.Query, Is.EqualTo("a=%26&b=%26")); Assert.That(uri["a"], Is.EqualTo("&")); Assert.That(uri["b"], Is.EqualTo("&")); }
private void UpdateUrl() { var uri = new SDataUri(Client.Uri); if (!string.IsNullOrEmpty(tbTemplateResourceKind.Text)) { uri.AppendPath(tbTemplateResourceKind.Text); } uri.AppendPath("$template"); tbTemplateURL.Text = uri.ToString(); }
private static SDataParameters GetDeleteParameters <T>(ISDataClient client, T content, string path) { Guard.ArgumentNotNull(client, "client"); Guard.ArgumentNotNull(content, "content"); Guard.ArgumentNotNullOrEmptyString(path, "path"); return(new SDataParameters { Method = HttpMethod.Delete, Path = string.Format("{0}({1})", path, SDataUri.FormatConstant(GetKey(content))), ETag = GetETag(content) }); }
protected override Expression VisitConstantExpression(ConstantExpression expression) { var value = expression.Value; if (ContentHelper.IsObject(value) && !ContentHelper.IsCollection(value)) { value = ContentHelper.GetProtocolValue <string>(value, SDataProtocolProperty.Key); } Append(SDataUri.FormatConstant(value)); return(expression); }
static taxCodeFeedEntry GetTaxCode(string productCode, int productCount) { // Look up the tax code record string taxUrl = dataSourceTest + "taxcodes"; SDataUri taxCodeUri = new SDataUri(taxUrl); // taxCodeUri.Where = "reference eq 'T1'"; taxCodeUri.Count = 2; SDataRequest taxcodeRequest = new SDataRequest(taxCodeUri.Uri); taxcodeRequest.Username = username; taxcodeRequest.Password = password; // taxcodeRequest.Password = "******"; taxCodeFeed taxcodes = new taxCodeFeed(); taxcodeRequest.RequestFeed <taxCodeFeedEntry>(taxcodes); // If we found a customer record return it if (taxcodeRequest.IsStatusValidForVerb && taxcodes.Entries != null && taxcodes.Entries.Count > 0) { if (productCode.Equals(taxcodes.Entries[0].reference)) { return(taxcodes.Entries[0]); } else { return(taxcodes.Entries[1]); } } else { // There was a problem Console.WriteLine("Tax code lookup failed. Response was {0}", taxcodeRequest.HttpStatusCode.ToString()); if (taxcodeRequest.Diagnoses != null) { foreach (Diagnosis diagnosis in taxcodeRequest.Diagnoses) { Console.WriteLine(diagnosis.Message); } } return(null); } }
private void btnPropertiesRead_Click(object sender, EventArgs e) { if (cbIsFeed.Checked) { var parts = new List <string>(); if (!string.IsNullOrEmpty(tbRPResourceKind.Text)) { var selector = tbRPResourceSelector.Text; if (!string.IsNullOrEmpty(selector)) { selector = SDataUri.FormatConstant(selector); } parts.Add(new UriPathSegment(tbRPResourceKind.Text, selector).Segment); } if (lbProperties.Items.Count > 0) { parts.AddRange(lbProperties.Items.Cast <string>()); } var collection = Client.Execute <SDataCollection <SDataResource> >( new SDataParameters { Path = string.Join("/", parts) }).Content; gridRPPayloads.SelectedObject = null; rpGridEntries.Rows.Clear(); rpGridEntries.Columns.Clear(); if (collection.Count > 0) { foreach (var key in collection[0].Keys) { rpGridEntries.Columns.Add(key, key); } foreach (var item in collection) { rpGridEntries.Rows.Add(item.Values.ToArray()); } } rpGridEntries.Refresh(); rpGridEntries.AutoResizeColumns(); } else { var resource = Client.Get(tbRPResourceSelector.Text, tbRPResourceKind.Text); rpGridEntries.Rows.Clear(); rpGridEntries.Columns.Clear(); gridRPPayloads.SelectedObject = resource; } }
private void UpdateUrl() { var uri = new SDataUri(Client.Uri) { StartIndex = (int)numStartIndex.Value, Count = (int)numCount.Value }; if (!string.IsNullOrEmpty(tbCollectionResourceKind.Text)) { uri.AppendPath(tbCollectionResourceKind.Text); } tbCollectionURL.Text = uri.ToString(); }
/// <summary> /// Initialises a new instance of the <see cref="SDataService"/> class, initialized with a target url, user name and password. /// </summary> /// <param name="url"></param> /// <param name="userName">user name used for credentials</param> /// <param name="password">password for user</param> public SDataService(string url, string userName, string password) { _uri = url != null ? new SDataUri(url) : new SDataUri { Server = "sdata", Product = "-", Contract = "-", CompanyDataset = "-" }; UserName = userName; Password = password; Timeout = 120000; UserAgent = "Sage"; }
private void HandlePaging(IRequest request, Feed <FeedEntry> result, string[] ids) { SDataUri baseUri = request.Uri; int max = ids.Length; long startIndex = baseUri.StartIndex == 0 ? 1 : baseUri.StartIndex; result.TotalResults = max; result.StartIndex = request.Uri.StartIndex == 0 ? 1 : request.Uri.StartIndex; result.ItemsPerPage = (int?)request.Uri.Count ?? max; FeedLink link; if (request.Uri.Count != null) { long count = (long)request.Uri.Count; if (count > 0) { SDataUri uri = new SDataUri(baseUri); uri.StartIndex = 1; link = new FeedLink(uri.ToString(), LinkType.First, MediaType.Atom, "First Page"); result.Links.Add(link); uri = new SDataUri(baseUri); uri.StartIndex = max % count == 0 ? max - count + 1 : ((max / count) * count) + 1; link = new FeedLink(uri.ToString(), LinkType.Last, MediaType.Atom, "Last Page"); result.Links.Add(link); if (startIndex + count < max) { uri = new SDataUri(baseUri); uri.StartIndex = startIndex + count; link = new FeedLink(uri.ToString(), LinkType.Next, MediaType.Atom, "Next Page"); result.Links.Add(link); } if (startIndex > 1) //Startindex is 1-based { uri = new SDataUri(baseUri); uri.StartIndex = Math.Max(1, startIndex - count); link = new FeedLink(uri.ToString(), LinkType.Previous, MediaType.Atom, "Previous Page"); result.Links.Add(link); } } } }
private static SDataParameters GetGetParameters(ISDataClient client, string key, string etag, string path, SDataPayloadOptions options) { Guard.ArgumentNotNull(client, "client"); Guard.ArgumentNotNullOrEmptyString(key, "key"); Guard.ArgumentNotNullOrEmptyString(path, "path"); if (options == null) { options = new SDataPayloadOptions(); } return(new SDataParameters { Path = string.Format("{0}({1})", path, SDataUri.FormatConstant(key)), ETag = etag, Include = options.Include, Select = options.Select, Precedence = options.Precedence }); }
private static IEnumerable RenderContainsOperator(MethodCallExpression expression) { var argExpr = expression.Arguments[0] as ConstantExpression; if (argExpr == null) { throw new NotSupportedException("Contains must be passed a literal string"); } return(new object[] { "(", expression.Object, " like ", SDataUri.FormatConstant("%" + argExpr.Value + "%"), ")" }); }
public RequestContext(SDataUri sdataUri) { this.SdataUri = sdataUri; // config NorthwindConfig newConfig = new NorthwindConfig(sdataUri.CompanyDataset); newConfig.CurrencyCode = "EUR"; newConfig.CrmUser = "******"; newConfig.Path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Northwind"); this.Config = newConfig; // initialize requestType this.RequestType = RequestType.None; // hasTrackingId this.HasTrackingId = false; // baseLink string newBaseLink = string.Empty; if (String.IsNullOrEmpty(sdataUri.Scheme)) newBaseLink += "http://"; else newBaseLink += sdataUri.Scheme + "://"; if (String.IsNullOrEmpty(sdataUri.Host)) newBaseLink += "localhost"; else newBaseLink += sdataUri.Host; if (sdataUri.Port > 0) newBaseLink += ":" + sdataUri.Port.ToString(); if (String.IsNullOrEmpty(sdataUri.Server)) newBaseLink += "/sdata/"; else newBaseLink += "/" + sdataUri.Server + "/"; this.BaseLink = newBaseLink; // application this.Application = (sdataUri.PathSegments.Length > 0) ? sdataUri.PathSegments[0].Text : ""; // applicationLink this.ApplicationLink = this.BaseLink + this.Application + "/"; if (sdataUri.PathSegments.Length == 1) { this.RequestType = RequestType.Contract; // -> Type: contract return; } // contract string newContract = sdataUri.PathSegments[1].Text; if (newContract == "*") { this.RequestType = RequestType.Contract; // -> Type: contract this.Contract = string.Empty; return; } this.Contract = newContract; // contractLink this.ContractLink = this.ApplicationLink + this.Contract + "/"; if (sdataUri.PathSegments.Length == 2) { this.RequestType = RequestType.Dataset; // -> Type: dataset return; } // dataset string newDataset = sdataUri.PathSegments[2].Text; if (newDataset == "*") { this.RequestType = RequestType.Dataset; // -> Type: dataset this.Dataset = string.Empty; return; } this.Dataset = newDataset; // datasetLink this.DatasetLink = this.ContractLink + this.Dataset + "/"; // sdataContext this.SdataContext = new SdataContext(this.Application, this.Dataset, this.Contract, this.DatasetLink); if (this.SdataUri.PathSegments.Length == 3) { if (!string.IsNullOrEmpty(this.SdataUri.ServiceMethod)) { this.RequestType = RequestType.Service; // -> Type: Service return; } this.RequestType = RequestType.ResourceCollection; // -> Type: ResourceCollection return; } string temp; temp = this.SdataUri.PathSegments[3].Text; if (temp == "*") { this.RequestType = RequestType.ResourceCollection; // -> Type: ResourceCollection return; } if (temp.Equals(Constants.schema, StringComparison.InvariantCultureIgnoreCase)) { // check whether it is an import schema if (this.SdataUri.PathSegments.Length == 4) { this.RequestType = RequestType.ResourceCollectionSchema; // -> Type: ResourceCollectionSchema return; } else if (this.SdataUri.PathSegments.Length == 6 && this.SdataUri.PathSegments[4].Text.Equals("import", StringComparison.InvariantCultureIgnoreCase) && (!string.IsNullOrEmpty(this.SdataUri.PathSegments[5].Text))) { this.ImportSchemaName = this.SdataUri.PathSegments[5].Text; this.RequestType = RequestType.ImportSchema; // -> Type: ImportSchema return; } } if (temp.Equals(Constants.service, StringComparison.InvariantCultureIgnoreCase)) { if (this.SdataUri.PathSegments.Length >= 6) { this.SdataUri.ServiceMethod = this.SdataUri.PathSegments[4].Text; if (this.SdataUri.PathSegments[5].Text.Equals(Constants.schema, StringComparison.InvariantCultureIgnoreCase)) { this.RequestType = RequestType.ServiceSchema; return; } } else { throw new RequestException(string.Format("Url {0} cannot be parsed.", this.SdataUri.ToString())); } } try { // resourceKind this.ResourceKind = (SupportedResourceKinds)Enum.Parse(typeof(SupportedResourceKinds), temp, true); if (sdataUri.PathSegments.Length > 4 && sdataUri.PathSegments[4].Text.Equals(Constants.linked, StringComparison.InvariantCultureIgnoreCase)) { this.RequestType = RequestType.Linked; // -> Type: Linked // resourceKey if (sdataUri.PathSegments[4].HasPredicate) { if (sdataUri.PathSegments[4].PredicateExpression is StringLiteralExpression) { this.ResourceKey = ((StringLiteralExpression)sdataUri.PathSegments[4].PredicateExpression).Value.ToString(); return; } else { this.RequestType = RequestType.None; // -> Type: None this.ResourceKind = SupportedResourceKinds.None; this.ErrorMessage = "please specify the primary Key inside the predicate as string"; return; } } } else if (!string.IsNullOrEmpty(this.SdataUri.ServiceMethod)) { if (sdataUri.PathSegments.Length >= 7 && sdataUri.PathSegments[6].Text.Equals(Constants.schema, StringComparison.InvariantCultureIgnoreCase)) this.RequestType = RequestType.ServiceSchema; // currently we do not enter here, but we don't know if SIF will be changed to set the service name else this.RequestType = RequestType.Service; // -> Type: Service return; } else if (sdataUri.PathSegments.Length >= 7 && sdataUri.PathSegments[4].Text.Equals(Constants.service, StringComparison.InvariantCultureIgnoreCase) && sdataUri.PathSegments[6].Text.Equals(Constants.schema, StringComparison.InvariantCultureIgnoreCase)) { this.SdataUri.ServiceMethod = sdataUri.PathSegments[5].Text; this.RequestType = RequestType.ServiceSchema; return; } else { this.RequestType = RequestType.Resource; // -> Type. Resource // resourceKey if (sdataUri.PathSegments[3].HasPredicate) { if (sdataUri.PathSegments[3].PredicateExpression is StringLiteralExpression) { this.ResourceKey = ((StringLiteralExpression)sdataUri.PathSegments[3].PredicateExpression).Value.ToString(); return; } else { this.RequestType = RequestType.None; // -> Type: None this.ResourceKind = SupportedResourceKinds.None; this.ErrorMessage = "please specify the primary Key inside the predicate as string"; return; } } } } catch (Exception e) { this.RequestType = RequestType.None; this.ResourceKind = SupportedResourceKinds.None; this.ErrorMessage = e.Message; return; } if (this.SdataUri.PathSegments.Length == 4) return; temp = sdataUri.PathSegments[4].Text; if (temp.Equals(Constants.schema, StringComparison.InvariantCultureIgnoreCase)) { this.RequestType = RequestType.ResourceSchema; // -> Type: ResourceSchema return; } if (temp.Equals(Constants.template, StringComparison.InvariantCultureIgnoreCase)) { this.RequestType = RequestType.Template; // -> Type: template return; } if (temp.Equals(Constants.syncDigest, StringComparison.InvariantCultureIgnoreCase)) { this.RequestType = RequestType.SyncDigest; // -> Type: syncDigest return; } if (temp.Equals(Constants.syncResults, StringComparison.InvariantCultureIgnoreCase)) { this.RequestType = RequestType.SyncResults; // -> Type: SyncResults return; } if ((temp.Equals(Constants.syncSource, StringComparison.InvariantCultureIgnoreCase)) || (temp.Equals(Constants.syncTarget, StringComparison.InvariantCultureIgnoreCase))) { if (temp.Equals(Constants.syncSource, StringComparison.InvariantCultureIgnoreCase)) this.RequestType = RequestType.SyncSource; // -> Type: syncSource if (temp.Equals(Constants.syncTarget, StringComparison.InvariantCultureIgnoreCase)) this.RequestType = RequestType.SyncTarget; // -> Type: syncTarget if (!string.IsNullOrEmpty(sdataUri.TrackingID)) { try { GuidConverter converter = new GuidConverter(); this.TrackingId = (Guid)converter.ConvertFrom(sdataUri.TrackingID); this.HasTrackingId = true; } catch (Exception) { } } else if (this.SdataUri.PathSegments[4].HasPredicate) { try { GuidConverter converter = new GuidConverter(); this.TrackingId = (Guid)converter.ConvertFrom(((StringLiteralExpression)this.SdataUri.PathSegments[4].PredicateExpression).Value); this.HasTrackingId = true; } catch (Exception) { } } return; } }
private void HandlePaging(IRequest request, Feed<FeedEntry> result, string[] ids) { SDataUri baseUri = request.Uri; int max = ids.Length; long startIndex = baseUri.StartIndex == 0 ? 1 : baseUri.StartIndex; result.TotalResults = max; result.StartIndex = request.Uri.StartIndex == 0 ? 1 : request.Uri.StartIndex; result.ItemsPerPage = (int?)request.Uri.Count ?? max; FeedLink link; if (request.Uri.Count != null) { long count = (long)request.Uri.Count; if (count > 0) { SDataUri uri = new SDataUri(baseUri); uri.StartIndex = 1; link = new FeedLink(uri.ToString(), LinkType.First, MediaType.Atom, "First Page"); result.Links.Add(link); uri = new SDataUri(baseUri); uri.StartIndex = max % count == 0 ? max - count + 1 : ((max / count) * count) + 1; link = new FeedLink(uri.ToString(), LinkType.Last, MediaType.Atom, "Last Page"); result.Links.Add(link); if (startIndex + count < max) { uri = new SDataUri(baseUri); uri.StartIndex = startIndex + count; link = new FeedLink(uri.ToString(), LinkType.Next, MediaType.Atom, "Next Page"); result.Links.Add(link); } if (startIndex > 1) //Startindex is 1-based { uri = new SDataUri(baseUri); uri.StartIndex = Math.Max(1, startIndex - count); link = new FeedLink(uri.ToString(), LinkType.Previous, MediaType.Atom, "Previous Page"); result.Links.Add(link); } } } }