public EntityWrapperBase(RequestContext context, SupportedResourceKinds resourceKind) { _context = context; _resourceKind = resourceKind; _emptyToken = new Token(); _correlatedResSyncInfoStore = RequestReceiver.NorthwindAdapter.StoreLocator.GetCorrelatedResSyncStore(_context.SdataContext); }
public override string[] GetFeed() { string whereClause = string.Empty; OleDbParameter[] oleDbParameters = null; if (this is IEntityQueryWrapper) { QueryFilterBuilder queryFilterBuilder = new QueryFilterBuilder((IEntityQueryWrapper)this); queryFilterBuilder.BuildSqlStatement(_context, out whereClause, out oleDbParameters); } Token emptyToken = new Token(); List<Identity> identities = new List<Identity>(); if (String.IsNullOrEmpty(_context.ResourceKey)) identities = _entity.GetAll(_context.Config, whereClause, oleDbParameters); else identities.Add(GetIdentity(_context.ResourceKey)); string[] result = new string[identities.Count * 2]; for (int i = 0; i < identities.Count; i++) { result[i * 2] = identities[i].Id + Sage.Integration.Northwind.Application.API.Constants.PhoneIdPostfix; } for (int i = 0; i < identities.Count; i++) { result[i * 2 + 1] = identities[i].Id + Sage.Integration.Northwind.Application.API.Constants.FaxIdPostfix; } return result; }
public static int GetId(Token token) { int result; if (Int32.TryParse(token.Id.Id, out result)) return result; return 0; }
public override int FillChangeLog(out DataTable table, NorthwindConfig config, Token lastToken) { table = new DataTable("PriceingList"); table.Columns.Add("ID", typeof(string)); table.Columns.Add("Sequence", typeof(int)); table.Rows.Add(new object[] { Constants.DefaultValues.PriceList.ID, 0 }); //table.Rows.Add(new object[] { Constants.DefaultValues.PriceListSpecial.ID, 0 }); return 1; }
/// <summary> /// Creates a new instance of type <see cref="Token"/> from a token's string representation. /// </summary> /// <param name="strToken">The string representation of a token.</param> /// <returns>The new created token.</returns> public static Token DeserializeToken(string strToken) { Token resultToken = new Token(); Identity identity = new Identity(); identity = new Identity(string.Empty, strToken.Substring(0, 29).TrimEnd(' ')); resultToken.Id = identity; resultToken.SequenceNumber = Int32.Parse(strToken.Substring(29, 10).TrimEnd(' ')); resultToken.InitRequest = (strToken.Substring(39, 1) == "1") ? true : false; return resultToken; }
public override Document GetDocument(Identity identity, Token lastToken, NorthwindConfig config) { PricingListsDocument doc = new PricingListsDocument(); if (identity.Id.Equals(Constants.DefaultValues.PriceList.ID)) { doc.Id = Constants.DefaultValues.PriceList.ID; doc.description.Value = Constants.DefaultValues.PriceList.Name; doc.name.Value = Constants.DefaultValues.PriceList.Name; } else { doc.Id = Constants.DefaultValues.PriceListSpecial.ID; doc.description.Value = Constants.DefaultValues.PriceListSpecial.Name; doc.name.Value = Constants.DefaultValues.PriceListSpecial.Name; } doc.active.Value = "Y"; //Constants.DefaultValues.Active; #warning should be boolean, but as workaround this will filled with "Y" doc.erpdefaultvalue.Value = "Y"; doc.defaultvalue.Value = false; return doc; }
public override Document GetDocument(Identity identity, Token lastToken, NorthwindConfig config) { int recordCount; DataSets.Product product = new DataSets.Product(); int uomFamilyId; uomFamilyId = Identity.GetId(identity); using (OleDbConnection connection = new OleDbConnection(config.ConnectionString)) { Sage.Integration.Northwind.Application.Entities.Product.DataSets.ProductTableAdapters.ProductsTableAdapter tableAdapter; tableAdapter = new Sage.Integration.Northwind.Application.Entities.Product.DataSets.ProductTableAdapters.ProductsTableAdapter(); tableAdapter.Connection = connection; recordCount = tableAdapter.FillBy(product.Products, uomFamilyId); } if (recordCount == 0) return GetDeletedDocument(identity); return GetUOMFamilyDocument((DataSets.Product.ProductsRow)product.Products[0], lastToken, config); }
public String[] GetFeed() { string whereClause = string.Empty; OleDbParameter[] oleDbParameters = null; if (this is IEntityQueryWrapper) //What's dat? { QueryFilterBuilder queryFilterBuilder = new QueryFilterBuilder((IEntityQueryWrapper)this); queryFilterBuilder.BuildSqlStatement(_context, out whereClause, out oleDbParameters); } Token emptyToken = new Token(); List<Identity> identities = new List<Identity>(); identities = this._entity.GetAll(_context.Config, whereClause, oleDbParameters); string[] result = new string[identities.Count]; for (int i = 0; i < identities.Count; i++) result[i] = identities[i].Id; return result; }
public override SyncFeed GetFeed() { bool includeUuid; string whereClause = string.Empty; OleDbParameter[] oleDbParameters = null; if (this is IEntityQueryWrapper) { QueryFilterBuilder queryFilterBuilder = new QueryFilterBuilder((IEntityQueryWrapper)this); queryFilterBuilder.BuildSqlStatement(_context, out whereClause, out oleDbParameters); } SyncFeed feed = new SyncFeed(); feed.Title = _resourceKind.ToString() + ": " + DateTime.Now.ToString(); Token emptyToken = new Token(); List<Identity> identities = new List<Identity>(); if (String.IsNullOrEmpty(_context.ResourceKey)) identities = _entity.GetAll(_context.Config, whereClause, oleDbParameters); else identities.Add(new Identity(_entity.EntityName, _context.ResourceKey)); int totalResult = identities.Count; #region PAGING & OPENSEARCH /* PAGING */ feed.Links = FeedMetadataHelpers.CreatePageFeedLinks(_context, totalResult, FeedMetadataHelpers.RequestKeywordType.none); /* OPENSEARCH */ PageController pageController = FeedMetadataHelpers.GetPageLinkBuilder(_context, totalResult, FeedMetadataHelpers.RequestKeywordType.none); feed.Opensearch_ItemsPerPageElement = pageController.GetOpensearch_ItemsPerPageElement(); feed.Opensearch_StartIndexElement = pageController.GetOpensearch_StartIndexElement(); feed.Opensearch_TotalResultsElement = pageController.GetOpensearch_TotalResultsElement(); #endregion feed.Id = _context.SdataUri.ToString(); string tmpValue; // ?includeUuid includeUuid = false; // default value, but check for settings now if (_context.SdataUri.QueryArgs.TryGetValue("includeUuid", out tmpValue)) includeUuid = System.Xml.XmlConvert.ToBoolean(tmpValue); ICorrelatedResSyncInfoStore correlatedResSyncStore = null; if (includeUuid) // get store to request the correlations correlatedResSyncStore = RequestReceiver.NorthwindAdapter.StoreLocator.GetCorrelatedResSyncStore(_context.SdataContext); for (int pageIndex = pageController.StartIndex; pageIndex <= pageController.LastIndex; pageIndex++) //for (int index = startIndex; index < startIndex + count; index++) { int zeroBasedIndex = pageIndex - 1; Identity identity = identities[zeroBasedIndex]; AccountDocument accountDocument = (AccountDocument)_entity.GetDocument(identity, emptyToken, _context.Config); if (accountDocument.LogState == LogState.Deleted) continue; SyncFeedEntry entry = new SyncFeedEntry(); if (accountDocument.addresses.documents.Count == 0) return null; entry.Id = String.Format("{0}{1}('{2}')", _context.DatasetLink, _resourceKind.ToString(), identity.Id); entry.Title = String.Format("{0}: {1}", _resourceKind.ToString(), identity.Id); entry.Updated = DateTime.Now; if (_context.SdataUri.Precedence == null) { List<SyncFeedEntryLink> links; Document document = accountDocument.addresses.documents[0]; entry.Payload = GetTransformedPayload(document, out links); string taUuid = GetTradingAccountUuid(accountDocument.Id); if (!String.IsNullOrEmpty(taUuid)) { SyncFeedEntryLink tradingAccountLink = SyncFeedEntryLink.CreateRelatedLink( String.Format("{0}{1}('{2}')", _context.DatasetLink, SupportedResourceKinds.tradingAccounts.ToString(), accountDocument.Id), SupportedResourceKinds.tradingAccounts.ToString(), _tradingAccountUuidPayloadPath, taUuid); links.Add(tradingAccountLink); } entry.SyncLinks = links; } if (includeUuid) { CorrelatedResSyncInfo[] infos = correlatedResSyncStore.GetByLocalId(_context.ResourceKind.ToString(), new string[] { identity.Id }); entry.Uuid = (infos.Length > 0) ? infos[0].ResSyncInfo.Uuid : Guid.Empty; } if (entry != null) feed.Entries.Add(entry); } return feed; }
private Document GetDocumentLineItem(DataSets.Order.CalculatedOrderDetailsRow row, Token lastToken, NorthwindConfig config) { #region Declarations LineItemDocument doc; string id; decimal discountPercentage; #endregion id = row.OrderID.ToString() + "-" + row.ProductID.ToString(); doc = new LineItemDocument(); doc.Id = id; if (lastToken.InitRequest) doc.LogState = LogState.Created; else if ((row.CreateID >= lastToken.SequenceNumber) && (row.CreateUser != config.CrmUser)) doc.LogState = LogState.Created; else if ((row.ModifyID >= lastToken.SequenceNumber) && (row.ModifyUser != config.CrmUser)) doc.LogState = LogState.Updated; doc.productid.Value = row.ProductID; //doc.orderquouteid.Value = row.OrderID; doc.uomid.Value = row.ProductID; doc.quantity.Value = row.IsQuantityNull() ? Convert.ToInt16(0) : row.Quantity; doc.listprice.Value = row.IsUnitPriceNull() ? new decimal(0) : row.UnitPrice; discountPercentage = row.IsDiscountNull() ? (decimal)0 : Convert.ToDecimal(row.Discount); //doc.discountsum.Value = (decimal)(short)doc.Quantity.Value * (decimal)doc.ListPrice.Value * discountPercentage; doc.discountsum.Value = (decimal)doc.listprice.Value * discountPercentage; doc.quotedprice.Value = (decimal)doc.listprice.Value * (1 - discountPercentage); //doc.quotedprice.Value = row.IsQuotePriceNull() ? new decimal(0) : Convert.ToDecimal(row.QuotePrice); doc.taxrate.Value = "0"; doc.tax.Value = new decimal(0); doc.quotedpricetotal.Value = Convert.ToDecimal(doc.quantity.Value) * Convert.ToDecimal(doc.quotedprice.Value); return doc; }
public override Document GetDocument(Identity identity, Token lastToken, NorthwindConfig config) { int recordCount; DataSets.Order order = new DataSets.Order(); CalculatedOrdersTableAdapter tableAdapter; tableAdapter = new CalculatedOrdersTableAdapter(); CalculatedOrderDetailsTableAdapter detailTableAdapter; detailTableAdapter = new CalculatedOrderDetailsTableAdapter(); DeletedOrderDetailsTableAdapter deletedDetailTableAdapter; deletedDetailTableAdapter = new DeletedOrderDetailsTableAdapter(); int id; id = Identity.GetId(identity); using (OleDbConnection connection = new OleDbConnection(config.ConnectionString)) { tableAdapter.Connection = connection; recordCount = tableAdapter.FillBy(order.CalculatedOrders, id); if (recordCount == 0) return GetDeletedDocument(identity); detailTableAdapter.Connection = connection; detailTableAdapter.FillBy(order.CalculatedOrderDetails, id); deletedDetailTableAdapter.Connection = connection; deletedDetailTableAdapter.Fill(order.DeletedOrderDetails, id.ToString(), lastToken.SequenceNumber, config.CrmUser); } return GetDocument((DataSets.Order.CalculatedOrdersRow)order.CalculatedOrders[0], order.CalculatedOrderDetails, order.DeletedOrderDetails, lastToken, config); }
public void DoWork(IRequest request) { if (request.ContentType!= Sage.Common.Syndication.MediaType.AtomEntry) throw new RequestException("Atom entry content type expected"); if (String.IsNullOrEmpty(_requestContext.ResourceKey)) throw new RequestException("Please use single resource url"); //SupportedResourceKinds resKind = _requestContext.ResourceKind; //switch (resKind) //{ // case SupportedResourceKinds.tradingAccounts: // case SupportedResourceKinds.contacts: // case SupportedResourceKinds.phoneNumbers: // case SupportedResourceKinds.postalAddresses: // break; // default: // throw new RequestException("Put is not Supported for requested resource"); //} // read entry from stream SyncFeedEntry entry = new SyncFeedEntry(); XmlReader reader = XmlReader.Create(request.Stream); reader.MoveToContent(); entry.ReadXml(reader, ResourceKindHelpers.GetPayloadType(_requestContext.ResourceKind)); IEntityWrapper wrapper = EntityWrapperFactory.Create(_requestContext.ResourceKind, _requestContext); Token emptyToken = new Token(); Identity identity = wrapper.GetIdentity(_requestContext.ResourceKey); Document originalDocument = wrapper.Entity.GetDocument(identity, emptyToken, _requestContext.Config); if (originalDocument.LogState == LogState.Deleted) throw new RequestException("Entity does not exists"); entry.Payload.LocalID = _requestContext.ResourceKey; SdataTransactionResult sdTrResult = wrapper.Update(entry.Payload, entry.SyncLinks); if (sdTrResult == null) { SyncFeedEntry responseEntry = wrapper.GetFeedEntry(_requestContext.ResourceKey); SyncFeed feed = new SyncFeed(); feed.FeedType = FeedType.ResourceEntry; feed.Entries.Add(responseEntry); request.Response.Serializer = new SyncFeedSerializer(); request.Response.Feed = feed; request.Response.ContentType = Sage.Common.Syndication.MediaType.AtomEntry; } else if (sdTrResult.HttpStatus == System.Net.HttpStatusCode.OK) { SyncFeedEntry responseEntry = wrapper.GetFeedEntry(_requestContext.ResourceKey); SyncFeed feed = new SyncFeed(); feed.FeedType = FeedType.ResourceEntry; feed.Entries.Add(responseEntry); request.Response.Serializer = new SyncFeedSerializer(); request.Response.Feed = feed; request.Response.ContentType = Sage.Common.Syndication.MediaType.AtomEntry; } else { throw new RequestException(sdTrResult.HttpMessage); } }
/// <summary> /// fill up a datatable with the next 11 id's of inserted, modified and deleted accounts since the given token. /// </summary> /// <param name="table">tha DataTable to filled up. The first column contains the identity</param> /// <param name="config">The configuration object</param> /// <param name="lastToken">the last token</param> /// <returns>The count of all the identities available</returns> public override int FillChangeLog(out DataTable table, NorthwindConfig config, Token lastToken) { #region Declarations int recordCount = 0; AccountDataset changelog = new AccountDataset(); #endregion // get the first 11 rows of the changelog using (OleDbConnection connection = new OleDbConnection(config.ConnectionString)) { ChangeLogsTableAdapter tableAdapter; tableAdapter = new ChangeLogsTableAdapter(); tableAdapter.Connection = connection; // fill the Changelog dataset // if the last token was an init request, the changelog will also return changes done by the crm User if (lastToken.InitRequest) recordCount = tableAdapter.Fill(changelog.ChangeLogs, lastToken.Id.Id, lastToken.SequenceNumber, lastToken.SequenceNumber, ""); else recordCount = tableAdapter.Fill(changelog.ChangeLogs, lastToken.Id.Id, lastToken.SequenceNumber, lastToken.SequenceNumber, config.CrmUser); } // set the out table to the filled account data table table = changelog.ChangeLogs; // return the count of the existing records return recordCount; }
// Asynchronous called method private void Execute(NorthwindConfig config, SyncFeedDigest syncDigestInfo) { #region Declaration SdataContext sdataContext; SupportedResourceKinds resource; IAppBookmarkInfoStore appBookmarkInfoStore; ICorrelatedResSyncInfoStore correlatedResSyncInfoStore; ISyncSyncDigestInfoStore syncDigestStore; ISyncTickProvider tickProvider; string resourceKind; string endpoint; int nextTick = 0; Token lastToken; Token nextToken; Identity[] changedIdentites; IEntityWrapper wrapper; #endregion #region init sdataContext = _parentPerformer._requestContext.SdataContext; resource = _parentPerformer._requestContext.ResourceKind; resourceKind = resource.ToString(); endpoint = _parentPerformer._requestContext.DatasetLink + resourceKind; appBookmarkInfoStore = RequestReceiver.NorthwindAdapter.StoreLocator.GetAppBookmarkStore(sdataContext); correlatedResSyncInfoStore = RequestReceiver.NorthwindAdapter.StoreLocator.GetCorrelatedResSyncStore(sdataContext); syncDigestStore = RequestReceiver.NorthwindAdapter.StoreLocator.GetSyncDigestStore(sdataContext); tickProvider = RequestReceiver.NorthwindAdapter.StoreLocator.GetTickProvider(sdataContext); wrapper = EntityWrapperFactory.Create(resource, _parentPerformer._requestContext); #endregion #region get last token or create a new one if (!appBookmarkInfoStore.Get<Token>(resourceKind, out lastToken)) { lastToken = new Token(); lastToken.InitRequest = true; } #endregion #region Get local identities of changed entries since last synchronisation changedIdentites = wrapper.Entity.GetLastChanges(lastToken, config, out nextToken); #endregion if (resource == SupportedResourceKinds.phoneNumbers) { #region workaround for phones for (int index = 0; index < changedIdentites.Length; index++) { string phoneid = changedIdentites[index].Id + Sage.Integration.Northwind.Application.API.Constants.PhoneIdPostfix; string faxId = changedIdentites[index].Id + Sage.Integration.Northwind.Application.API.Constants.FaxIdPostfix; // receive the feed entry for local identity SyncFeedEntry phoneentry = wrapper.GetFeedEntry(phoneid); SyncFeedEntry faxentry = wrapper.GetFeedEntry(faxId); if (phoneentry == null && faxentry == null) continue; // receive the correlation for the local identity if (phoneentry != null) { CorrelatedResSyncInfo[] correlatedResSyncInfos = correlatedResSyncInfoStore.GetByLocalId(resourceKind, new string[] { phoneid }); string etag = EtagServices.ComputeEtag(phoneentry.Payload, true); // new etag if (correlatedResSyncInfos.Length == 0) { nextTick = tickProvider.CreateNextTick(resourceKind); // create next tick ResSyncInfo resyncInfo = new ResSyncInfo(Guid.NewGuid(), endpoint, nextTick, etag, DateTime.Now); CorrelatedResSyncInfo info = new CorrelatedResSyncInfo(phoneid, resyncInfo); correlatedResSyncInfoStore.Put(resourceKind, info); syncDigestStore.PersistNewer(resourceKind, info.ResSyncInfo); } else if (!correlatedResSyncInfos[0].ResSyncInfo.Etag.Equals(etag)) { nextTick = tickProvider.CreateNextTick(resourceKind); correlatedResSyncInfos[0].ResSyncInfo.Etag = etag; correlatedResSyncInfos[0].ResSyncInfo.Tick = nextTick; correlatedResSyncInfos[0].ResSyncInfo.Endpoint = endpoint; correlatedResSyncInfos[0].ResSyncInfo.ModifiedStamp = DateTime.Now; correlatedResSyncInfoStore.Put(resourceKind, correlatedResSyncInfos[0]); syncDigestStore.PersistNewer(resourceKind, correlatedResSyncInfos[0].ResSyncInfo); } } if (faxentry != null) { CorrelatedResSyncInfo[] correlatedResSyncInfos = correlatedResSyncInfoStore.GetByLocalId(resourceKind, new string[] { faxId }); string etag = EtagServices.ComputeEtag(faxentry.Payload, true); // new etag if (correlatedResSyncInfos.Length == 0) { nextTick = tickProvider.CreateNextTick(resourceKind); // create next tick ResSyncInfo resyncInfo = new ResSyncInfo(Guid.NewGuid(), endpoint, nextTick, etag, DateTime.Now); CorrelatedResSyncInfo info = new CorrelatedResSyncInfo(faxId, resyncInfo); correlatedResSyncInfoStore.Put(resourceKind, info); syncDigestStore.PersistNewer(resourceKind, info.ResSyncInfo); } else if (!correlatedResSyncInfos[0].ResSyncInfo.Etag.Equals(etag)) { nextTick = tickProvider.CreateNextTick(resourceKind); correlatedResSyncInfos[0].ResSyncInfo.Etag = etag; correlatedResSyncInfos[0].ResSyncInfo.Tick = nextTick; correlatedResSyncInfos[0].ResSyncInfo.Endpoint = endpoint; correlatedResSyncInfos[0].ResSyncInfo.ModifiedStamp = DateTime.Now; correlatedResSyncInfoStore.Put(resourceKind, correlatedResSyncInfos[0]); syncDigestStore.PersistNewer(resourceKind, correlatedResSyncInfos[0].ResSyncInfo); } } } #endregion } else { for (int index = 0; index < changedIdentites.Length; index++) { string id = changedIdentites[index].Id; // receive the feed entry for local identity SyncFeedEntry entry = wrapper.GetFeedEntry(id); if (entry == null) continue; // receive the correlation for the local identity CorrelatedResSyncInfo[] correlatedResSyncInfos = correlatedResSyncInfoStore.GetByLocalId(resourceKind, new string[] { id }); string etag = EtagServices.ComputeEtag(entry.Payload, true); // new etag if (correlatedResSyncInfos.Length == 0) { nextTick = tickProvider.CreateNextTick(resourceKind); // create next tick ResSyncInfo resyncInfo = new ResSyncInfo(Guid.NewGuid(), endpoint, nextTick, etag, DateTime.Now); CorrelatedResSyncInfo info = new CorrelatedResSyncInfo(id, resyncInfo); correlatedResSyncInfoStore.Put(resourceKind, info); syncDigestStore.PersistNewer(resourceKind, info.ResSyncInfo); } else if (!correlatedResSyncInfos[0].ResSyncInfo.Etag.Equals(etag)) { nextTick = tickProvider.CreateNextTick(resourceKind); correlatedResSyncInfos[0].ResSyncInfo.Etag = etag; correlatedResSyncInfos[0].ResSyncInfo.Tick = nextTick; correlatedResSyncInfos[0].ResSyncInfo.Endpoint = endpoint; correlatedResSyncInfos[0].ResSyncInfo.ModifiedStamp = DateTime.Now; correlatedResSyncInfoStore.Put(resourceKind, correlatedResSyncInfos[0]); syncDigestStore.PersistNewer(resourceKind, correlatedResSyncInfos[0].ResSyncInfo); } } } #region store next token appBookmarkInfoStore.Put(resourceKind, nextToken); #endregion // set tracking phase lock (_parentPerformer._asyncStateObj) { _parentPerformer._asyncStateObj.Tracking.Phase = TrackingPhase.GETCHANGESBYTICK; } // Receive syncDigestInfo if (null != syncDigestInfo) { ICorrelatedResSyncInfoEnumerator enumerator; List<string> endpoints = new List<string>(); foreach (SyncFeedDigestEntry digestEntry in syncDigestInfo.Entries) { endpoints.Add(digestEntry.Endpoint); enumerator = correlatedResSyncInfoStore.GetSinceTick(resourceKind, digestEntry.Endpoint, digestEntry.Tick-2); while (enumerator.MoveNext()) { // No lock needed, as we expect that CorrelatedResSyncInfos list is // only acceeded anywhere else when Tracking phase is 'finish'. //lock(_parentPerformer._asyncStateObj) //{ _parentPerformer._asyncStateObj.CorrelatedResSyncInfos.Add(enumerator.Current); //} } } SyncDigestInfo sourceSyncDigestInfo = syncDigestStore.Get(resourceKind); foreach (SyncDigestEntryInfo digestEntry in sourceSyncDigestInfo) { if (endpoints.Contains(digestEntry.Endpoint)) continue; endpoints.Add(digestEntry.Endpoint); enumerator = correlatedResSyncInfoStore.GetSinceTick(resourceKind, digestEntry.Endpoint, -1); while (enumerator.MoveNext()) { // No lock needed, as we expect that CorrelatedResSyncInfos list is // only acceeded anywhere else when Tracking phase is 'finish'. //lock(_parentPerformer._asyncStateObj) //{ _parentPerformer._asyncStateObj.CorrelatedResSyncInfos.Add(enumerator.Current); //} } } if (!endpoints.Contains(endpoint)) { enumerator = correlatedResSyncInfoStore.GetSinceTick(resourceKind, endpoint, -1); while (enumerator.MoveNext()) { // No lock needed, as we expect that CorrelatedResSyncInfos list is // only acceeded anywhere else when Tracking phase is 'finish'. //lock(_parentPerformer._asyncStateObj) //{ _parentPerformer._asyncStateObj.CorrelatedResSyncInfos.Add(enumerator.Current); //} } } } // Set tracking phase lock (_parentPerformer._asyncStateObj.Tracking) { _parentPerformer._asyncStateObj.Tracking.Phase = TrackingPhase.FINISH; } }
/// <summary> /// /// </summary> /// <param name="config"></param> /// <returns></returns> /// <remarks>This method is not threadsafe as the performer must be finished when calling this method.</remarks> public SyncFeed GetFeed(NorthwindConfig config, int startIndex, int count) { SyncFeed feed; SdataContext sdataContext; SupportedResourceKinds resource; string resourceKind; string endpoint; Guid trackingId; List<CorrelatedResSyncInfo> correlatedResSyncInfos; sdataContext = _parentPerformer._requestContext.SdataContext; resource = _parentPerformer._requestContext.ResourceKind; resourceKind = resource.ToString(); correlatedResSyncInfos = _parentPerformer._asyncStateObj.CorrelatedResSyncInfos; endpoint = _parentPerformer._requestContext.DatasetLink + resourceKind; trackingId = _parentPerformer._requestContext.TrackingId; ISyncSyncDigestInfoStore syncDigestStore = RequestReceiver.NorthwindAdapter.StoreLocator.GetSyncDigestStore(sdataContext); SyncDigestInfo syncDigestInfo = syncDigestStore.Get(resourceKind); if (count == 0) count = 10; feed = new SyncFeed(); Token emptyToken = new Token(); feed.Digest = new SyncFeedDigest(); feed.Digest.Origin = _parentPerformer._requestContext.OriginEndPoint; feed.Digest.Entries = new List<SyncFeedDigestEntry>(); if (syncDigestInfo != null) { foreach (SyncDigestEntryInfo entryinfo in syncDigestInfo) { SyncFeedDigestEntry entry = new SyncFeedDigestEntry(); entry.ConflictPriority = entryinfo.ConflictPriority; entry.Endpoint = entryinfo.Endpoint; entry.Tick = entryinfo.Tick; entry.Stamp = DateTime.Now; feed.Digest.Entries.Add(entry); } } IEntityWrapper wrapper = EntityWrapperFactory.Create(resource, _parentPerformer._requestContext); for (int index = startIndex; index < ((startIndex + count > correlatedResSyncInfos.Count) ? correlatedResSyncInfos.Count : startIndex + count); index++) { CorrelatedResSyncInfo resSyncInfo = (CorrelatedResSyncInfo)correlatedResSyncInfos[index]; SyncFeedEntry entry = wrapper.GetFeedEntry(resSyncInfo); if (entry != null) feed.Entries.Add(entry); else { entry = new SyncFeedEntry(); entry.HttpMethod = "DELETE"; entry.Uuid = resSyncInfo.ResSyncInfo.Uuid; feed.Entries.Add(entry); } } // initialize the feed string url = string.Format("{0}/$syncSource('{1}')", endpoint, trackingId); feed.Id = url; feed.Title = resourceKind; #region PAGING & OPENSEARCH int totalResults = correlatedResSyncInfos.Count; PageController pageController = new PageController(startIndex+1, FeedMetadataHelpers.DEFAULT_ITEMS_PER_PAGE, totalResults, count, url); /* PAGING */ FeedLinkCollection feedLinks = new FeedLinkCollection(); feedLinks.Add(new FeedLink(pageController.GetLinkSelf(), LinkType.Self, MediaType.Atom, "Current Page")); feedLinks.Add(new FeedLink(pageController.GetLinkFirst(), LinkType.First, MediaType.Atom, "First Page")); feedLinks.Add(new FeedLink(pageController.GetLinkLast(), LinkType.Last, MediaType.Atom, "Last Page")); string linkUrl; if (pageController.GetLinkNext(out linkUrl)) feedLinks.Add(new FeedLink(linkUrl, LinkType.Next, MediaType.Atom, "Next Page")); if (pageController.GetLinkPrevious(out linkUrl)) feedLinks.Add(new FeedLink(linkUrl, LinkType.Previous, MediaType.Atom, "Previous Page")); feed.Links = feedLinks; /* OPENSEARCH */ feed.Opensearch_ItemsPerPageElement = pageController.GetOpensearch_ItemsPerPageElement(); feed.Opensearch_StartIndexElement = pageController.GetOpensearch_StartIndexElement(); feed.Opensearch_TotalResultsElement = pageController.GetOpensearch_TotalResultsElement(); #endregion //feed.Id = url; //if (startIndex + count < correlatedResSyncInfos.Count) //{ // FeedLink linkNext = new FeedLink(string.Format("{0}?startIndex={1}&count=10", url, startIndex + count), LinkType.Next); // feed.Links.Add(linkNext); //} //FeedLink linkFirst = new FeedLink(String.Format("{0}?startIndex=0&count=10", url), LinkType.First); //feed.Links.Add(linkFirst); //FeedLink linkSelf = new FeedLink(String.Format("{0}?startIndex={1}&count=10", url, startIndex), LinkType.Self); //feed.Links.Add(linkSelf); return feed; }
/// <summary> /// returns a filled document by the identity /// </summary> /// <param name="identity">the identity</param> /// <param name="lastToken">the last token to set the logstate</param> /// <param name="config">the configuration object</param> /// <returns>returns a filled document by the identity</returns> public abstract Document GetDocument(Identity identity, Token lastToken, NorthwindConfig config);
public Identity[] GetLastChanges(Token lastToken, NorthwindConfig config, out Token nextToken) { #region Declarations int recordCount = 0; DataTable dataTable; Identity identity; DataRow row; List<Identity> identites = new List<Identity>(); #endregion recordCount = 11; nextToken = lastToken; while (recordCount == 11) { lastToken = nextToken; recordCount = FillChangeLog(out dataTable, config, lastToken); for (int i = 0; i < ((recordCount == 11) ? recordCount - 1 : recordCount); i++) { //get the next changelog entry row = dataTable.Rows[i]; identity = new Identity(this.EntityName, (string)row[0]); identites.Add(identity); nextToken = new Token(identity, (int)row[1], lastToken.InitRequest); } } return identites.ToArray(); }
/// <summary> /// The GetDocument verb retuns an complete AccountDocument containing the data associated with /// an existing account instance. /// /// Should no account instance be found in the data-store that matches the identity /// passed as a parameter it will return an empty account document marked as deleted within the given identity. /// </summary> /// <param name="identity">Identity of the account</param> /// <param name="lastToken">the last given Token to mark the account status as updated or created</param> /// <param name="config">The configuration object</param> /// <returns>an account document</returns> public override Document GetDocument(Identity identity, Token lastToken, NorthwindConfig config) { #region declarations int recordCount; AccountsTableAdapter tableAdapter; AccountDataset account = new AccountDataset(); #endregion // get the Account by the given identity using (OleDbConnection connection = new OleDbConnection(config.ConnectionString)) { tableAdapter = new AccountsTableAdapter(); tableAdapter.Connection = connection; recordCount = tableAdapter.FillBy(account.Accounts, identity.Id); } // when the record does not exists return an deleted document of the given identity if (recordCount == 0) return GetDeletedDocument(identity); // convert the dataset row to an account document and return it return GetDocument((AccountDataset.AccountsRow)account.Accounts[0], lastToken, config); }
public override int FillChangeLog(out DataTable table, NorthwindConfig config, Token lastToken) { #region declarations DataSets.Order order; int lastId; int recordCount; #endregion order = new DataSets.Order(); lastId = Token.GetId(lastToken); using (OleDbConnection connection = new OleDbConnection(config.ConnectionString)) { ChangeLogsTableAdapter tableAdapter; tableAdapter = new ChangeLogsTableAdapter(); tableAdapter.Connection = connection;// fill the Changelog dataset if (lastToken.InitRequest) recordCount = tableAdapter.Fill(order.ChangeLogs, lastId, lastToken.SequenceNumber, lastToken.SequenceNumber, ""); else recordCount = tableAdapter.Fill(order.ChangeLogs, lastId, lastToken.SequenceNumber, lastToken.SequenceNumber, config.CrmUser); } table = order.ChangeLogs; return recordCount; }
/// <summary> /// returns a complete account document without using a token /// </summary> /// <param name="accountId">the account id</param> /// <param name="config"></param> /// <returns></returns> private Document GetDocument(string accountId, NorthwindConfig config) { Identity identity = new Identity(this.EntityName, accountId); Token lastToken = new Token(new Identity(EntityName, ""), 0, true); return GetDocument(identity, lastToken, config); }
private Document GetDocument(DataSets.Order.CalculatedOrdersRow row, DataSets.Order.CalculatedOrderDetailsDataTable detailDataTable, DataSets.Order.DeletedOrderDetailsDataTable deletedOrderDetailsDataTable, Token lastToken, NorthwindConfig config) { #region Declarations OrderDocument doc; string id; LogState logState = LogState.Updated; Document lineItemDoc; CountryCodes countryCodes = new CountryCodes(); #endregion id = row.OrderID.ToString(); if (lastToken.InitRequest) logState = LogState.Created; else if (row.IsCreateIDNull() || row.IsModifyIDNull() || row.IsCreateUserNull() || row.IsModifyUserNull()) logState = LogState.Created; else if ((row.CreateID > lastToken.SequenceNumber) && (row.CreateUser != config.CrmUser)) logState = LogState.Created; else if ((row.CreateID == lastToken.SequenceNumber) && (row.CreateUser != config.CrmUser) && (id.CompareTo(lastToken.Id.Id) > 0)) logState = LogState.Created; else if ((row.ModifyID >= lastToken.SequenceNumber) && (row.ModifyUser != config.CrmUser)) logState = LogState.Updated; doc = new OrderDocument(); doc.Id = id; doc.LogState = logState; doc.currency.Value = config.CurrencyCode; doc.pricinglistid.Value = Constants.DefaultValues.PriceList.ID; doc.reference.Value = id; if (row.IsCustomerIDNull()) doc.accountid.Value = null; else doc.accountid.Value = Constants.CustomerIdPrefix + row.CustomerID; if (row.IsOrderDateNull()) doc.opened.Value = null; else doc.opened.Value = row.OrderDate; if (row.IsShippedDateNull()) doc.status.Value = Constants.OrderStatus.Active; else doc.status.Value = Constants.OrderStatus.Completed; //doc.DiscountPercentage.Value = new decimal(0); //doc.grossamt.Value = row.IsTotalQuotedPriceNull() ? new decimal(0) : Convert.ToDecimal(row.TotalQuotedPrice); doc.discountamt.Value = new decimal(0); doc.lineitemdisc.Value = row.IsDiscountAmountNull() ? new decimal(0) : Convert.ToDecimal(row.DiscountAmount); doc.nettamt.Value = row.IsTotalNetPriceNull() ? new decimal(0) : Convert.ToDecimal(row.TotalNetPrice); doc.freight.Value = row.IsFreightNull() ? new decimal(0) : row.Freight; doc.tax.Value = new decimal(0); doc.grossamt.Value = doc.nettamt.Value; if (row.IsRequiredDateNull()) doc.deliverydate.Value = null; else doc.deliverydate.Value = row.RequiredDate; if (row.IsEmployeeIDNull()) doc.salesrepr.Value = null; else doc.salesrepr.Value = Convert.ToString(row.EmployeeID); if (row.IsShipViaNull()) doc.shippedvia.Value = null; else doc.shippedvia.Value = row.ShipVia; OrderAddress orderAddress = new OrderAddress(); orderAddress.SetNorthwindAddress(row.IsShipAddressNull() ? "" : row.ShipAddress, row.IsShipCityNull() ? "" : row.ShipCity, row.IsShipPostalCodeNull() ? "" : row.ShipPostalCode, row.IsShipCountryNull() ? "" : row.ShipCountry); doc.shipaddress.Value = orderAddress.CrmOrderAddress; foreach (DataSets.Order.CalculatedOrderDetailsRow detailRow in detailDataTable.Rows) { lineItemDoc = GetDocumentLineItem(detailRow, lastToken, config); if ((doc.LogState != LogState.Created) && (lineItemDoc.HasNoLogStatus)) continue; doc.orderitems.Add(lineItemDoc); } foreach (DataSets.Order.DeletedOrderDetailsRow deletedRow in deletedOrderDetailsDataTable.Rows) { lineItemDoc = new LineItemDocument(); lineItemDoc.Id = deletedRow[0].ToString(); lineItemDoc.LogState = LogState.Deleted; doc.orderitems.Add(lineItemDoc); } return doc; }
private AccountDocument GetDocument(AccountDataset.AccountsRow row, Token lastToken, NorthwindConfig config) { #region Declarations CountryCodes countryCodes = new CountryCodes(); AccountDocument accDoc; PersonDocument persDoc; PhoneDocument phoneDoc; AddressDocument addrDoc; Address address; Phone phone; string identity; ContactName contactName; #endregion identity = row.ID; // create Account Doc accDoc = new AccountDocument(); // set the account id accDoc.Id = identity; // change the the log state regarding the timestamps stored in the northwind database. // for an init request the logstate is always created if (lastToken.InitRequest) accDoc.LogState = LogState.Created; // if something wrong, than it is created else if (row.IsCreateIDNull() || row.IsModifyIDNull() || row.IsCreateUserNull() || row.IsModifyUserNull()) accDoc.LogState = LogState.Created; // the log state is created if the create id is greater // than the sequence number of the last token and it was not created by the crm user else if ((row.CreateID > lastToken.SequenceNumber) && (row.CreateUser != config.CrmUser)) accDoc.LogState = LogState.Created; else if ((row.CreateID == lastToken.SequenceNumber) && (row.CreateUser != config.CrmUser) && (identity.CompareTo(lastToken.Id.Id) > 0)) accDoc.LogState = LogState.Created; // the log state is modified if the modify id is greater // than the sequence number of the last token and it was not created by the crm user else if ((row.ModifyID >= lastToken.SequenceNumber) && (row.ModifyUser != config.CrmUser)) accDoc.LogState = LogState.Updated; // set the account type //accDoc.type.Value = GetAccountType(identity); // set the account name accDoc.name.Value = row.IsCompanyNameNull() ? null : row.CompanyName; // set the customerSupplierFlag accDoc.customerSupplierFlag.Value = row.IsCustomerSupplierFlagNull() ? null : row.CustomerSupplierFlag; // set default values if it is no update if (accDoc.LogState != LogState.Updated) { accDoc.onhold.Value = !accDoc.Id.StartsWith(Constants.CustomerIdPrefix); accDoc.currencyid.Value = config.CurrencyCode; } // create person Doc persDoc = new PersonDocument(); // since there is only one person in Northwind, the Identity of the person is the same as // the account id persDoc.Id = identity; // set the log state if the account also has a logstate if (!accDoc.HasNoLogStatus) persDoc.LogState = accDoc.LogState; // set the transaction status for the person doc. persDoc.SetTransactionStatus(TransactionStatus.Success); // set the first and lst name to null if the contact in northwind is null if (row.IsContactNameNull() || string.IsNullOrEmpty(row.ContactName)) { persDoc.firstname.Value = null; persDoc.lastname.Value = null; persDoc.fullname.Value = null; } else { persDoc.fullname.Value = row.ContactName; // create an object to splitt the contact name contactName = new ContactName(); // initiate the object with the northwind contact name contactName.NorthwindContacName = row.ContactName; // get the splitted values persDoc.salutation.Value = contactName.CrmSalutation; persDoc.firstname.Value = contactName.CrmFirstName; persDoc.middlename.Value = contactName.CrmMiddleName; persDoc.lastname.Value = contactName.CrmLastName; persDoc.suffix.Value = contactName.CrmSuffix; } if (row.IsContactTitleNull()) persDoc.title.Value = null; else persDoc.title.Value = row.ContactTitle; // set the person type to billing persDoc.primaryperson.Value = "True"; // add the person to the people collection of the account document accDoc.people.Add(persDoc); // create Phone Doc phoneDoc = new PhoneDocument(); // since there are exact 2 phone numbers stored in northwind // the id for the phone number ist the account id plus a postfix phoneDoc.Id = identity + Constants.PhoneIdPostfix; // set the log state if the account also has a logstate if (!accDoc.HasNoLogStatus) phoneDoc.LogState = accDoc.LogState; // set the person type to business phoneDoc.type.Value = CRMSelections.Link_PersPhon_Business; phoneDoc.SetTransactionStatus(TransactionStatus.Success); if (!row.IsPhoneNull()) { phoneDoc.fullnumber.Value = row.Phone; phone = new Phone(); phone.NorthwindPhone = row.Phone; phoneDoc.countrycode.Value = phone.CrmCountryCode; phoneDoc.areacode.Value = phone.CrmAreaCode; phoneDoc.number.Value = phone.CrmPhone; accDoc.phones.Add(phoneDoc); } // create Fax Doc phoneDoc = new PhoneDocument(); phoneDoc.Id = identity + Constants.FaxIdPostfix; if (!accDoc.HasNoLogStatus) phoneDoc.LogState = accDoc.LogState; phoneDoc.type.Value = CRMSelections.Link_PersPhon_Fax; phoneDoc.SetTransactionStatus(TransactionStatus.Success); if (!row.IsFaxNull()) { phoneDoc.fullnumber.Value = row.Fax; phone = new Phone(); phone.NorthwindPhone = row.Fax; phoneDoc.countrycode.Value = phone.CrmCountryCode; phoneDoc.areacode.Value = phone.CrmAreaCode; phoneDoc.number.Value = phone.CrmPhone; accDoc.phones.Add(phoneDoc); } // create Address Doc addrDoc = new AddressDocument(); addrDoc.Id = identity; if (!accDoc.HasNoLogStatus) addrDoc.LogState = accDoc.LogState; //addrDoc.AddressType.Value = CRMSelections.Link_CompAddr_Billing; addrDoc.primaryaddress.Value = "True"; addrDoc.SetTransactionStatus(TransactionStatus.Success); if (row.IsAddressNull()) { addrDoc.address1.Value = null; addrDoc.address2.Value = null; addrDoc.address3.Value = null; addrDoc.address4.Value = null; } else { address = new Address(); address.NorthwindAddress = row.Address; addrDoc.address1.Value = address.CrmAddressLine1; addrDoc.address2.Value = address.CrmAddressLine2; addrDoc.address3.Value = address.CrmAddressLine3; addrDoc.address4.Value = address.CrmAddressLine4; } addrDoc.City.Value = row.IsCityNull() ? null : row.City; addrDoc.state.Value = row.IsRegionNull() ? null : row.Region; if (row.IsCountryNull()) addrDoc.country.Value = null; else addrDoc.country.Value = countryCodes.GetCountryCode(row.Country); addrDoc.postcode.Value = row.IsPostalCodeNull() ? null : row.PostalCode; if (accDoc.Id.StartsWith(Constants.CustomerIdPrefix)) accDoc.emails = GetEmailsCollectionFromCustomer(accDoc.Id.Substring(Constants.CustomerIdPrefix.Length), lastToken, config); accDoc.addresses.Add(addrDoc); return accDoc; }
/// <summary> ///• Account /// • Order /// • Product /// • ProductFamily /// • Price /// • UnitOfMesure /// • UnitOfMeasureFamily /// </summary> /// <param name="EntityName">The name of the entity</param> /// <param name="Token"></param> /// <param name="config">the configuration object</param> /// <returns></returns> public ChangeLog GetChangeLog(string entityName, string token, NorthwindConfig config) { Token intToken; // create an new token for the requested entity intToken = new Token(new Identity(entityName, ""), 0, true); // if an serialzed tokenstring passed in, deserialize and use this one if (!((token == null) || (token.Length == 0))) //token = (Token)XmlHelper.DeserializeXmlToObject(token, Token); intToken = (Token)Token.DeserializeToken(token); // get a new entity object of the requestet entity EntityBase entity = EntityFactory.GetEntity(entityName); // if the entityname is not supported by the connector an error will thrown if (entity == null) throw new Exception(string.Format(Resources.ErrorMessages_OperationNotImplementedForEntity, entityName)); // get the changelog an an entity return entity.GetChangelog(intToken, config); }
private EmailsDocumentCollection GetEmailsCollectionFromCustomer(string customerId, Token lastToken, NorthwindConfig config) { int recordCount; Emails emails = new Emails(); DeleteHistoryDataset history = new DeleteHistoryDataset(); using (OleDbConnection connection = new OleDbConnection(config.ConnectionString)) { Sage.Integration.Northwind.Application.Entities.Account.DataSets.EmailsTableAdapters.CustomerEmailsTableAdapter tableAdapter; tableAdapter = new Sage.Integration.Northwind.Application.Entities.Account.DataSets.EmailsTableAdapters.CustomerEmailsTableAdapter(); tableAdapter.Connection = connection; recordCount = tableAdapter.FillByCustomerId(emails.CustomerEmails, customerId); DeleteHistoryTableAdapter tableAdapterDeleted; tableAdapterDeleted = new DeleteHistoryTableAdapter(); tableAdapterDeleted.Connection = connection; recordCount += tableAdapterDeleted.FillCustomerEmailsBy(history.DeleteHistory, customerId.ToString()); } if (recordCount == 0) return new EmailsDocumentCollection(); return GetEmailsCollectionFromCustomer(emails, history, lastToken, config.CrmUser); }
/// <summary> /// /// </summary> /// <param name="config"></param> /// <returns></returns> /// <remarks>This method is not threadsafe as the performer must be finished when calling this method.</remarks> public SyncFeed GetFeed(NorthwindConfig config, int startIndex, int count) { SyncFeed feed; SdataContext sdataContext; SupportedResourceKinds resource; string resourceKind; string endpoint; Guid trackingId; List<SdataTransactionResult> transactinResults; sdataContext = _parentPerformer._requestContext.SdataContext; resource = _parentPerformer._requestContext.ResourceKind; resourceKind = resource.ToString(); transactinResults = _parentPerformer._asyncStateObj.TransactionResults; endpoint = _parentPerformer._requestContext.DatasetLink + resourceKind; ; trackingId = _parentPerformer._requestContext.TrackingId; if (count == 0) count = 10; feed = new SyncFeed(); Token emptyToken = new Token(); IEntityWrapper wrapper = EntityWrapperFactory.Create(resource, _parentPerformer._requestContext); for (int index = startIndex; index < ((startIndex + count > transactinResults.Count) ? transactinResults.Count : startIndex + count); index++) { SdataTransactionResult transactionResult = (SdataTransactionResult)transactinResults[index]; SyncFeedEntry entry = wrapper.GetFeedEntry(transactionResult); if (entry != null) feed.Entries.Add(entry); else { entry = new SyncFeedEntry(); entry.Uuid = transactionResult.Uuid; entry.HttpStatusCode = transactionResult.HttpStatus; entry.HttpMessage = transactionResult.HttpMessage; ; entry.HttpMethod = transactionResult.HttpMethod; entry.HttpLocation = transactionResult.Location; entry.HttpETag = transactionResult.Etag; feed.Entries.Add(entry); } } // initialize the feed string url = string.Format("{0}/$syncTarget('{1}')", endpoint, trackingId); feed.Title = resourceKind; feed.Id = url; #region PAGING & OPENSEARCH int totalResults = transactinResults.Count; PageController pageController = new PageController(startIndex+1, FeedMetadataHelpers.DEFAULT_ITEMS_PER_PAGE, totalResults, count, url); /* PAGING */ FeedLinkCollection feedLinks = new FeedLinkCollection(); feedLinks.Add(new FeedLink(pageController.GetLinkSelf(), LinkType.Self, MediaType.Atom, "Current Page")); feedLinks.Add(new FeedLink(pageController.GetLinkFirst(), LinkType.First, MediaType.Atom, "First Page")); feedLinks.Add(new FeedLink(pageController.GetLinkLast(), LinkType.Last, MediaType.Atom, "Last Page")); string linkUrl; if (pageController.GetLinkNext(out linkUrl)) feedLinks.Add(new FeedLink(linkUrl, LinkType.Next, MediaType.Atom, "Next Page")); if (pageController.GetLinkPrevious(out linkUrl)) feedLinks.Add(new FeedLink(linkUrl, LinkType.Previous, MediaType.Atom, "Previous Page")); feed.Links = feedLinks; /* OPENSEARCH */ feed.Opensearch_ItemsPerPageElement = pageController.GetOpensearch_ItemsPerPageElement(); feed.Opensearch_StartIndexElement = pageController.GetOpensearch_StartIndexElement(); feed.Opensearch_TotalResultsElement = pageController.GetOpensearch_TotalResultsElement(); #endregion //if (startIndex + count < transactinResults.Count) //{ // FeedLink linkNext = new FeedLink(string.Format("{0}?startIndex={1}&count=10", url, startIndex + count), LinkType.Next); // feed.Links.Add(linkNext); //} //FeedLink linkFirst = new FeedLink(String.Format("{0}?startIndex=0&count=10", url), LinkType.First); //feed.Links.Add(linkFirst); //FeedLink linkSelf = new FeedLink(String.Format("{0}?startIndex={1}&count=10", url, startIndex), LinkType.Self); //feed.Links.Add(linkSelf); return feed; }
private EmailsDocumentCollection GetEmailsCollectionFromCustomer(Emails emails, DeleteHistoryDataset history, Token lastToken, string crmUser) { EmailsDocumentCollection emailCollection = new EmailsDocumentCollection(); EmailDocument email; foreach (DeleteHistoryDataset.DeleteHistoryRow dr in history.DeleteHistory) { if (dr.DeleteUser == crmUser) continue; if (dr.DeleteID <= lastToken.SequenceNumber) continue; email = new EmailDocument(); email.Id = dr.Identity; email.LogState = LogState.Deleted; emailCollection.Add(email); } int index = 0; foreach (Emails.CustomerEmailsRow er in emails.CustomerEmails) { email = new EmailDocument(); if ((er.CreateUser != crmUser) && (er.CreateID > lastToken.SequenceNumber)) email.LogState = LogState.Created; else if ((er.ModifyUser != crmUser) && (er.ModifyID > lastToken.SequenceNumber)) email.LogState = LogState.Updated; email.Id = er.ID.ToString(); try { email.emailaddress.Value = er.Email; if (index == 0) email.type.Value = "Business"; if (index == 1) email.type.Value = "Private"; index++; } catch (StrongTypingException) { email.emailaddress.Value = null; } emailCollection.Add(email); } return emailCollection; }
/* ChangeLog */ public override int FillChangeLog(out System.Data.DataTable table, NorthwindConfig config, Token lastToken) { #region Declarations int recordCount = 0; DataSets.Product changelog = new DataSets.Product(); int lastUomID = 0; #endregion lastUomID = Token.GetId(lastToken); // get the first 11 rows of the changelog using (OleDbConnection connection = new OleDbConnection(config.ConnectionString)) { ChangeLogsTableAdapter tableAdapter; tableAdapter = new ChangeLogsTableAdapter(); tableAdapter.Connection = connection; // fill the Changelog dataset if (lastToken.InitRequest) recordCount = tableAdapter.Fill(changelog.ChangeLogs, lastUomID, lastToken.SequenceNumber, lastToken.SequenceNumber, ""); else recordCount = tableAdapter.Fill(changelog.ChangeLogs, lastUomID, lastToken.SequenceNumber, lastToken.SequenceNumber, config.CrmUser); } table = changelog.ChangeLogs; return recordCount; }
/// <summary> /// get the next changes from an entity /// </summary> /// <param name="table">the datatable to fill</param> /// <param name="config">the configuration object</param> /// <param name="lastToken">the last token to get the next 10 changelog entries</param> /// <returns>retunrs a recordcount and a filled datatable</returns> public abstract int FillChangeLog(out DataTable table, NorthwindConfig config, Token lastToken);
private UnitOfMeasureFamilyDocument GetUOMFamilyDocument(Sage.Integration.Northwind.Application.Entities.Product.DataSets.Product.ProductsRow productRow, Token lastToken, NorthwindConfig config) { #region Declarations UnitOfMeasureFamilyDocument uomDoc; string identity; #endregion identity = productRow.ProductID.ToString(); // create Account Doc uomDoc = new UnitOfMeasureFamilyDocument(); uomDoc.Id = identity; if (lastToken.InitRequest) uomDoc.LogState = LogState.Created; else if (productRow.IsCreateIDNull() || productRow.IsModifyIDNull() || productRow.IsCreateUserNull() || productRow.IsModifyUserNull()) uomDoc.LogState = LogState.Created; else if ((productRow.CreateID > lastToken.SequenceNumber) && (productRow.CreateUser != config.CrmUser)) uomDoc.LogState = LogState.Created; else if ((productRow.CreateID == lastToken.SequenceNumber) && (productRow.CreateUser != config.CrmUser) && (identity.CompareTo(lastToken.Id.Id) > 0)) uomDoc.LogState = LogState.Created; else if ((productRow.ModifyID >= lastToken.SequenceNumber) && (productRow.ModifyUser != config.CrmUser)) uomDoc.LogState = LogState.Updated; uomDoc.active.Value = Constants.DefaultValues.Active; uomDoc.defaultvalue.Value = true; uomDoc.name.Value = productRow.IsQuantityPerUnitNull() ? null : productRow.QuantityPerUnit.ToString(); ; uomDoc.description.Value = uomDoc.name.Value; return uomDoc; }
/// <summary> /// GetChangeLog is a request to the ERP system for changes to /// a specific named entity instance for specified time durations. /// A change can be either create, update, or delete. /// </summary> /// <param name="lastToken">the last passed token</param> /// <param name="config">the configuration object</param> /// <returns> /// The response to GetChangeLog is a GetChangeLogResponse, /// which returns a list of changes (creates, deletes and updates), /// in a complex type called ArrayofChangeLogEntries /// ArrayofChangeLogEntries contains a list of ChangeLogEntry’s /// which contain details of the changes. /// </returns> public ChangeLog GetChangelog(Token lastToken, NorthwindConfig config) { #region Declarations int recordCount = 0; Token token; Identity identity; Document doc; ChangeLog result = new ChangeLog(); DataTable dataTable; DataRow row; XmlDocument xmlDoc = new XmlDocument(); #endregion // get the first 11 rows of the changelog recordCount = FillChangeLog(out dataTable, config, lastToken); // set the attend flag if the changlog contains less then 11 recorde result.AtEnd = (recordCount < 11); // if there are 11 instances, only 100 will retuned in this request result.ChangeLogInstances = new ChangeLogEntry[recordCount == 11 ? 10 : recordCount]; token = lastToken; // go thru at least 10 records of the changelog for (int i = 0; i < result.ChangeLogInstances.Length; i++) { //get the next changelog entry row = dataTable.Rows[i]; identity = new Identity(this.EntityName, (string)row[0]); // create a token from the changelog data token = new Token(identity, (int)row[1], lastToken.InitRequest); // get the Document by id doc = GetDocument(identity, lastToken, config); // create a changelog entry result.ChangeLogInstances[i] = new ChangeLogEntry(); // set the token of this entry result.ChangeLogInstances[i].Token = Token.SerializeTokenToString(token); // add the xmldocument of the account document to the result result.ChangeLogInstances[i].Instance = doc.GetXmlNode(xmlDoc); } if (result.AtEnd) token.InitRequest = false; // update the nextpass token to the current one result.NextPassToken = Token.SerializeTokenToString(token); if (result.ChangeLogInstances.Length > 0) result.ChangeLogInstances[result.ChangeLogInstances.Length - 1].Token = result.NextPassToken; return result; }