public virtual FeedEntry GetFeedEntry(string id)
        {
            FeedEntry result;

            Identity identity;
            Document document;

            identity = GetIdentity(id);
            document = _entity.GetDocument(identity, _emptyToken, _context.Config);
            if (document.LogState == LogState.Deleted)
            {
#warning The empty Feed Entry should have a type...
                result           = getNewFeedEntry();
                result.IsDeleted = true;
                result.Key       = id;
                CorrelatedResSyncInfo[] corr = _correlatedResSyncInfoStore.GetByLocalId(_resourceKind.ToString(), new string[] { id });
                if ((corr != null) && (corr.Length > 0))
                {
                    result.UUID = corr[0].ResSyncInfo.Uuid;
                }
                return(result);
            }
            result = GetTransformedPayload(document);

            return(result);
        }
 private void CheckExisting(ICorrelatedResSyncInfoStore correlatedResSyncInfoStore, string localId)
 {
     CorrelatedResSyncInfo[] existingCorrelations = correlatedResSyncInfoStore.GetByLocalId(_requestContext.ResourceKind.ToString(), new string[] { localId });
     if (existingCorrelations.Length > 0)
     {
         StringBuilder b = new StringBuilder(existingCorrelations.Length + " correlations for " + localId + " already exist ( ");
         foreach (CorrelatedResSyncInfo existingCorrelation in existingCorrelations)
         {
             b.Append(existingCorrelation.ResSyncInfo.Uuid);
             b.Append(" ");
         }
         b.Append(")");
         throw new RequestException(b.ToString());
     }
 }
        protected Guid GetUuid(string localId, string uuidString)
        {
            if (String.IsNullOrEmpty(localId))
            {
                return(Guid.Empty);
            }

            CorrelatedResSyncInfo[] results = _correlatedResSyncInfoStore.GetByLocalId(_resourceKindString, new string[] { localId });
            if (results.Length > 0)
            {
                return(results[0].ResSyncInfo.Uuid);
            }
            Guid result;

            if (string.IsNullOrEmpty(uuidString))
            {
                result = Guid.NewGuid();
            }
            else
            {
                try
                {
                    GuidConverter converter = new GuidConverter();
                    result = (Guid)converter.ConvertFromString(uuidString);
                    if (Guid.Empty.Equals(result))
                    {
                        result = Guid.NewGuid();
                    }
                }
                catch (Exception)
                {
                    result = Guid.NewGuid();
                }
            }

            ResSyncInfo           newResSyncInfo = new ResSyncInfo(result, _originApplication, 0, string.Empty, DateTime.Now);
            CorrelatedResSyncInfo newCorrelation = new CorrelatedResSyncInfo(localId, newResSyncInfo);

            _correlatedResSyncInfoStore.Put(_resourceKindString, newCorrelation);
            return(result);
        }
예제 #4
0
        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);
        }
예제 #5
0
 private void CheckExisting(ICorrelatedResSyncInfoStore correlatedResSyncInfoStore, string localId)
 {
     CorrelatedResSyncInfo[] existingCorrelations = correlatedResSyncInfoStore.GetByLocalId(_requestContext.ResourceKind.ToString(), new string[] { localId });
     if (existingCorrelations.Length > 0)
     {
         StringBuilder b = new StringBuilder(existingCorrelations.Length + " correlations for " + localId + " already exist ( ");
         foreach (CorrelatedResSyncInfo existingCorrelation in existingCorrelations)
         {
             b.Append(existingCorrelation.ResSyncInfo.Uuid);
             b.Append(" ");
         }
         b.Append(")");
         throw new RequestException(b.ToString());
     }
 }
        public void Update(FeedEntry entry)
        {
            // only atom entry supported!!!
            if (_request.ContentType != Sage.Common.Syndication.MediaType.AtomEntry)
            {
                throw new RequestException("Atom entry content type expected");
            }

            // resource key must exist in url
            if (string.IsNullOrEmpty(_requestContext.ResourceKey))
            {
                throw new RequestException("ResourceKey missing in requested url.");
            }

            string         requestEndPointUrl;
            RequestContext entryResourceAsRequestContext;

            string url;             // The url that references an existing resource
            string localId;         // will be parsed from urlAttrValue and set to the key attribute of the result resource payload
            Guid   uuid;            // the new uuid

            // retrieve the feed entry
            //entry = FeedComponentFactory.Create<ILinkingResourceFeedEntry>(request.Stream);


            // Get the uuid from query
            uuid = (Guid)TypeDescriptor.GetConverter(typeof(Guid)).ConvertFrom(_requestContext.ResourceKey);


            if (null == entry)
            {
                throw new RequestException("sdata payload element missing");
            }

            // the consumer MUST provide an sdata:url attribute that references an existing resource.
            url = entry.Uri;
            if (string.IsNullOrEmpty(url))
            {
                throw new RequestException("sdata url attribute missing for resource payload element.");
            }


            // Parse the url of thew url attribute to get the local id.
            // Additionally we check for equality of the urls of the request url and
            // in the linked element up to the resourceKind.
            requestEndPointUrl            = _requestContext.OriginEndPoint;
            entryResourceAsRequestContext = new RequestContext(new Sage.Common.Syndication.SDataUri(url));    // TODO: not really nice here.
            string linkedResourceUrl = entryResourceAsRequestContext.OriginEndPoint;

            if (!string.Equals(requestEndPointUrl, linkedResourceUrl, StringComparison.InvariantCultureIgnoreCase))
            {
                throw new RequestException("Request url and linked entry resource not matching.");
            }

            string resourceKindName = _requestContext.ResourceKind.ToString();

            localId = entryResourceAsRequestContext.ResourceKey;



            // The correlation store
            ICorrelatedResSyncInfoStore correlatedResSyncInfoStore = NorthwindAdapter.StoreLocator.GetCorrelatedResSyncStore(_requestContext.SdataContext);


            // update the correlation entry in the sync store.
            // if uuid is not in use -> throw exception
            // if resource is already linked -> remove existing link, reassign link
            // if resource is not yet linked -> reassign link
            CorrelatedResSyncInfo[] correlations;
            CorrelatedResSyncInfo   correlationToModify = null;

            // retrieve the correlation we want to reassign by given uuid
            correlations = correlatedResSyncInfoStore.GetByUuid(resourceKindName, new Guid[] { uuid });
            if (correlations.Length > 0)
            {
                correlationToModify = correlations[0];
            }
            else
            {
                throw new RequestException("Uuid not in use");
            }

            //remember the old Correlation for the new localId, will be deleted after the update.
            CorrelatedResSyncInfo[] oldCorrelations = correlatedResSyncInfoStore.GetByLocalId(resourceKindName, new string[] { localId });

            // change the local ID to link to the new resource.
            // change the modification stamp and reset the tick
            correlationToModify.LocalId = localId;
            correlationToModify.ResSyncInfo.ModifiedStamp = DateTime.Now;
            correlationToModify.ResSyncInfo.Tick          = 1;

            // update the correlation
            correlatedResSyncInfoStore.Update(resourceKindName, correlationToModify);

            //If updating went OK, delete the old correlation for the new localId (should be only 1, for-loop just to be sure to catch em all)
            foreach (CorrelatedResSyncInfo oldCorrelation in oldCorrelations)
            {
                correlatedResSyncInfoStore.Delete(resourceKindName, oldCorrelation.ResSyncInfo.Uuid);
            }

            // If the service consumer only needs to retrieve the URL, not the actual payload,
            // it may do so by adding an empty select parameter to its request:
            // a) select parameter not exist -> return deep resource payload
            // b) select exists and empty -> return no resource payload
            // c) select exists and not empty -> return deep resource payload as we do not yet support payload filtering
            //    with select parameter.
            string tmpValue;
            // ?select
            bool includeResourcePayloads = true;    // default value, but check for select parameter now

            if (_requestContext.SdataUri.QueryArgs.TryGetValue("select", out tmpValue))
            {
                if (string.IsNullOrEmpty(_requestContext.SdataUri.QueryArgs["select"]))
                {
                    includeResourcePayloads = false;
                }
            }


            // Create an entity wrapper if resource data should be requested. Otherwise
            // leave wrapper null.
            IFeedEntryEntityWrapper wrapper = null;

            //if (includeResourcePayloads) //TODO: Comment this in as soon as there is a possibility to send empty payload objects
            wrapper = FeedEntryWrapperFactory.Create(_requestContext.ResourceKind, _requestContext);

            /* Create the response entry */
            _request.Response.FeedEntry   = (FeedEntry)this.BuildFeedEntryForCorrelation(correlationToModify, wrapper);
            _request.Response.ContentType = MediaType.AtomEntry;
        }