Exemple #1
0
        private IQueryable <TEntity> SyncWith(Sync sync)
        {
            if (!sync.Target.HasProjection)
            {
                var fields = GetSharedColumns(sync.Source, sync.Target.From.Table);
                Func <string, IList <SelectProjection> > createProjection =
                    alias => fields.Select(x => new SelectProjection {
                    Projection = new Projection {
                        Type  = Projection.ProjectionType.Field,
                        Field = new Field {
                            Name       = x.Projection.Field.Name,
                            Key        = x.Projection.Field.Key,
                            HasKey     = x.Projection.Field.HasKey,
                            TableAlias = alias
                        }
                    }
                }).ToList();
                sync.Target.Projection = createProjection(sync.Target.From.Alias);
                sync.Source.Projection = createProjection(sync.Source.From.Alias);
            }

            var statement = SyncWriter <TEntity> .CreateStatement(sync, _map);

            Command.Create(statement, _profiler).ExecuteNonQuery(_connectionManager);
            return(new Table <TEntity>(_connectionManager, sync.Target
                                       .From.Table.Name, _map, _profiler, _noLock));
        }
Exemple #2
0
        public void should_render_sync_include_sql()
        {
            var target = MockQueryable <Entity> .Create(TableName1);

            var source = MockQueryable <Entity> .Create(TableName2);

            var importId = Guid.NewGuid();

            target.Where(x => x.ImportId != importId).SyncWith(source.Where(x => x.ImportId == importId), x => x.Created, SyncFields.Include, x => x.Name, x => x.Flag);
            var query = QueryVisitor <Entity> .CreateModel(target.Expression, x => ((MockQueryable <Entity>)x).Name);

            query.Operation.ShouldEqual(Query.OperationType.SyncWith);
            query.SyncWith.ShouldNotBeNull();

            var sync = query.SyncWith;

            var statement = SyncWriter <Entity> .CreateStatement(sync, Map);

            statement.Result.ShouldEqual(Statement.ResultType.None);
            statement.Parameters.Count.ShouldEqual(2);
            statement.Parameters.First().Value.ShouldEqual(importId);
            statement.Parameters.Skip(1).First().Value.ShouldEqual(importId);
            statement.Text.ShouldEqual(string.Format(
                                           "UPDATE [{0}] SET [{0}].[name] = [{1}].[name], [{0}].[flag] = [{1}].[flag] FROM [{2}] [{0}] INNER JOIN [{3}] [{1}] ON [{0}].[created] = [{1}].[created] AND " +
                                           "([{1}].[import_id] = @{4}) WHERE (([{0}].[import_id] <> @{5}) OR [{0}].[import_id] IS NULL)",
                                           sync.Target.From.Alias, sync.Source.From.Alias, TableName1, TableName2,
                                           statement.Parameters.First().Key, statement.Parameters.Skip(1).First().Key));
        }
Exemple #3
0
        /// <summary>
        /// Callback for the Download HttpWebRequest.beginGetRequestStream
        /// </summary>
        private void WriteDownloadRequestStream(Stream requestStream, AsyncArgsWrapper wrapper)
        {
            try
            {
                // Create a SyncWriter to write the contents
                this.syncWriter = (SerializationFormat == SerializationFormat.ODataAtom)
                    ? new ODataAtomWriter(BaseUri)
                    : (SyncWriter) new ODataJsonWriter(BaseUri);

                //syncWriter = new ODataAtomWriter(BaseUri);

                syncWriter.StartFeed(wrapper.CacheRequest.IsLastBatch, wrapper.CacheRequest.KnowledgeBlob ?? new byte[0]);

                if (SerializationFormat == SerializationFormat.ODataAtom)
                {
                    syncWriter.WriteFeed(XmlWriter.Create(requestStream));
                }
                else
                {
                    this.syncWriter.WriteFeed(new XmlJsonWriter(requestStream));
                }

                requestStream.Flush();
            }
            catch (Exception e)
            {
                if (ExceptionUtility.IsFatal(e))
                {
                    throw;
                }

                wrapper.Error = e;
            }
        }
Exemple #4
0
        /// <summary>
        /// Callback for the Upload HttpWebRequest.beginGetRequestStream
        /// </summary>
        private void WriteUploadRequestStream(Stream requestStream, AsyncArgsWrapper wrapper)
        {
            try
            {
                // Create a SyncWriter to write the contents
                this.syncWriter = (SerializationFormat == SerializationFormat.ODataAtom)
                    ? new ODataAtomWriter(BaseUri)
                    : (SyncWriter) new ODataJsonWriter(BaseUri);


                syncWriter.StartFeed(wrapper.CacheRequest.IsLastBatch, wrapper.CacheRequest.KnowledgeBlob ?? new byte[0]);

                foreach (IOfflineEntity entity in wrapper.CacheRequest.Changes)
                {
                    // Skip tombstones that dont have a ID element.
                    if (entity.GetServiceMetadata().IsTombstone&& string.IsNullOrEmpty(entity.GetServiceMetadata().Id))
                    {
                        continue;
                    }

                    string tempId = null;

                    // Check to see if this is an insert. i.e ServiceMetadata.Id is null or empty
                    if (string.IsNullOrEmpty(entity.GetServiceMetadata().Id))
                    {
                        if (wrapper.TempIdToEntityMapping == null)
                        {
                            wrapper.TempIdToEntityMapping = new Dictionary <string, IOfflineEntity>();
                        }

                        tempId = Guid.NewGuid().ToString();
                        wrapper.TempIdToEntityMapping.Add(tempId, entity);
                    }

                    syncWriter.AddItem(entity, tempId);
                }

                if (SerializationFormat == SerializationFormat.ODataAtom)
                {
                    syncWriter.WriteFeed(XmlWriter.Create(requestStream));
                }
                else
                {
                    this.syncWriter.WriteFeed(new XmlJsonWriter(requestStream));
                }

                requestStream.Flush();
            }
            catch (Exception e)
            {
                if (ExceptionUtility.IsFatal(e))
                {
                    throw;
                }
                wrapper.Error = e;
            }
        }
        /// <summary>
        /// Callback for the Download HttpWebRequest.beginGetRequestStream
        /// </summary>
        /// <param name="asyncResult">IAsyncResult object</param>
        void OnDownloadGetRequestStreamCompleted(IAsyncResult asyncResult)
        {
            AsyncArgsWrapper wrapper = asyncResult.AsyncState as AsyncArgsWrapper;

            try
            {
                Stream requestStream = wrapper.WebRequest.EndGetRequestStream(asyncResult);

                // CreateInstance a SyncWriter to write the contents
                if (ApplicationContext.Current.Settings.BitMobileFormatterDisabled)
                {
                    _syncWriter = new ODataAtomWriter(BaseUri);
                }
                else
                {
                    _syncWriter = new BMWriter(BaseUri);
                }


                this._syncWriter.StartFeed(wrapper.CacheRequest.IsLastBatch, wrapper.CacheRequest.KnowledgeBlob ?? new byte[0]);

                if (base.SerializationFormat == SerializationFormat.ODataAtom)
                {
                    this._syncWriter.WriteFeed(XmlWriter.Create(requestStream));
                }
                else
                {
                    this._syncWriter.WriteFeed(JsonReaderWriterFactory.CreateJsonWriter(requestStream));
                }

                requestStream.Flush();
                requestStream.Close();

                if (this._beforeRequestHandler != null)
                {
                    // Invoke user code and wait for them to call back us when they are done with the input request
                    this._workerManager.PostProgress(wrapper.WorkerRequest, this.FirePreRequestHandler, wrapper);
                }
                else
                {
                    this.GetWebResponse(wrapper);
                }
            }
            catch (Exception e)
            {
                if (ExceptionUtility.IsFatal(e))
                {
                    throw;
                }
                wrapper.Error = e;
                this._workerManager.CompleteWorkRequest(wrapper.WorkerRequest, wrapper);
            }
        }
 /// <summary>
 /// Delegate passed into the custom body writer to form the outgoing response.
 /// </summary>
 /// <param name="writer"></param>
 /// <param name="syncWriter"></param>
 private static void WriteResponse(XmlDictionaryWriter writer, SyncWriter syncWriter)
 {
     try
     {
         syncWriter.WriteFeed(writer);
     }
     catch (Exception exception)
     {
         // An exception at this point seems to be unrecoverable but ideally we should not hit exceptions since we are only
         // writing to the XmlDictionaryWriter.
         SyncServiceTracer.TraceError("Exception in WriteResponse method. Details: {0}", WebUtil.GetExceptionMessage(exception));
     }
 }
        /// <summary>
        /// Callback for the Download HttpWebRequest.beginGetRequestStream
        /// </summary>
        /// <param name="task">Task representing the future request stream</param>
        async Task OnDownloadGetRequestStreamCompleted(Task <Stream> task, AsyncArgsWrapper wrapper)
        {
            try
            {
                Stream requestStream = await task.ConfigureAwait(false);

                // Create a SyncWriter to write the contents
                this._syncWriter = (base.SerializationFormat == SerializationFormat.ODataAtom)
                    ? (SyncWriter) new ODataAtomWriter(base.BaseUri)
                    : (SyncWriter) new ODataJsonWriter(base.BaseUri);

                this._syncWriter.StartFeed(wrapper.CacheRequest.IsLastBatch, wrapper.CacheRequest.KnowledgeBlob ?? new byte[0]);

                if (base.SerializationFormat == SerializationFormat.ODataAtom)
                {
                    this._syncWriter.WriteFeed(XmlWriter.Create(requestStream));
                }
                else
                {
                    this._syncWriter.WriteFeed(JsonReaderWriterFactory.CreateJsonWriter(requestStream));
                }

                requestStream.Flush();
                requestStream.Close();

                if (this._beforeRequestHandler != null)
                {
                    // Invoke user code and wait for them to call back us when they are done with the input request
                    this._workerManager.PostProgress(wrapper.WorkerRequest, this.FirePreRequestHandler, wrapper);
                }
                else
                {
                    this.GetWebResponse(wrapper);
                }
            }
            catch (Exception e)
            {
                if (ExceptionUtility.IsFatal(e))
                {
                    throw;
                }
                wrapper.Error = e;
                this._workerManager.CompleteWorkRequest(wrapper.WorkerRequest, wrapper);
            }
        }
        // This method ensures that we have a valid feed through the formatters. The BodyWriter delegate in WCF
        // seems to not recover from an unhandled exception caused by the formatters and sends out an empty response to the caller.
        // This is a workaround for this issue until we find a better solution.
        private SyncWriter GetSyncWriterWithContents()
        {
            // Get the appropriate SyncWriter instance based on the serialization format.
            SyncWriter oDataWriter = WebUtil.GetSyncWriter(_responseSerializationFormat, _baseUri);

            oDataWriter.StartFeed(_getChangesResponse.IsLastBatch, _getChangesResponse.ServerBlob);

            // Write entities for response.
            foreach (var entity in _getChangesResponse.EntityList)
            {
                // Set the Id and add item with a null tempId.

                entity.ServiceMetadata.Id = WebUtil.GenerateOfflineEntityId(entity);

                oDataWriter.AddItem(entity, null /*tempId*/);
            }

            return(oDataWriter);
        }
 internal DelegateBodyWriter(Action <XmlDictionaryWriter, SyncWriter> writer, SyncWriter syncWriter) : base(false)
 {
     _writerAction = writer;
     _syncWriter   = syncWriter;
 }
        /// <summary>
        /// Callback for the Upload HttpWebRequest.beginGetRequestStream
        /// </summary>
        /// <param name="asyncResult">IAsyncResult object</param>
        void OnUploadGetRequestStreamCompleted(IAsyncResult asyncResult)
        {
            AsyncArgsWrapper wrapper = asyncResult.AsyncState as AsyncArgsWrapper;

            try
            {
                Stream requestStream = wrapper.WebRequest.EndGetRequestStream(asyncResult);

                // CreateInstance a SyncWriter to write the contents

                if (ApplicationContext.Current.Settings.BitMobileFormatterDisabled)
                {
                    _syncWriter = new ODataAtomWriter(BaseUri);
                }
                else
                {
                    _syncWriter = new BMWriter(BaseUri);
                }

                this._syncWriter.StartFeed(wrapper.CacheRequest.IsLastBatch, wrapper.CacheRequest.KnowledgeBlob ?? new byte[0]);

                foreach (IOfflineEntity entity in wrapper.CacheRequest.Changes)
                {
                    var ientity = entity as IEntity;

                    // Skip tombstones that dont have a ID element.
                    if (entity.ServiceMetadata.IsTombstone && string.IsNullOrEmpty(entity.ServiceMetadata.Id))
                    {
                        if (ientity != null)
                        {
                            LogManager.Logger.SyncUpload(ientity.EntityType, true);
                        }
                        continue;
                    }

                    string tempId = null;

                    // Check to see if this is an insert. i.e ServiceMetadata.Id is null or empty
                    if (string.IsNullOrEmpty(entity.ServiceMetadata.Id))
                    {
                        if (wrapper.TempIdToEntityMapping == null)
                        {
                            wrapper.TempIdToEntityMapping = new Dictionary <string, IOfflineEntity>();
                        }
                        tempId = Guid.NewGuid().ToString();
                        wrapper.TempIdToEntityMapping.Add(tempId, entity);
                    }

                    this._syncWriter.AddItem(entity, tempId);

                    if (ientity != null)
                    {
                        LogManager.Logger.SyncUpload(ientity.EntityType);
                    }
                }

                if (base.SerializationFormat == SerializationFormat.ODataAtom)
                {
                    this._syncWriter.WriteFeed(XmlWriter.Create(requestStream));
                }
                else
                {
                    this._syncWriter.WriteFeed(JsonReaderWriterFactory.CreateJsonWriter(requestStream));
                }

                requestStream.Flush();
                requestStream.Close();

                if (this._beforeRequestHandler != null)
                {
                    // Invoke user code and wait for them to call back us when they are done with the input request
                    this._workerManager.PostProgress(wrapper.WorkerRequest, this.FirePreRequestHandler, wrapper);
                }
                else
                {
                    this.GetWebResponse(wrapper);
                }
            }
            catch (Exception e)
            {
                if (ExceptionUtility.IsFatal(e))
                {
                    throw;
                }
                wrapper.Error = e;
                this._workerManager.CompleteWorkRequest(wrapper.WorkerRequest, wrapper);
            }
        }
        private void WriteOutputNoNewLine(string outputType, string txt)
        {
            // we need to add (char)13(char)10 when '\n' occurs in text (this is richText box)
            StringBuilder sb = new StringBuilder();
            foreach (char c in txt)
            {
                if (c == '\n')
                    sb.Append((char)13).Append((char)10);
                else
                    sb.Append(c);
            }
            SyncWriter sw = new SyncWriter(this, sb.ToString());

            Invoke(new MethodInvoker(sw.InternalWriteOutput));
        }
        private object ProcessDownloadRequest(HttpWebRequest webRequest, CacheRequest request)
        {
            using (Stream memoryStream = new MemoryStream())
            {

                // Create a SyncWriter to write the contents
                this._syncWriter = new ODataAtomWriter(base.BaseUri);

                this._syncWriter.StartFeed(true, request.KnowledgeBlob ?? new byte[0]);

                this._syncWriter.WriteFeed(XmlWriter.Create(memoryStream));
                memoryStream.Flush();

                webRequest.ContentLength = memoryStream.Position;
                Stream requestStream = webRequest.GetRequestStream();
                CopyStreamContent(memoryStream, requestStream);

                requestStream.Flush();
                requestStream.Close();

                // Fire the Before request handler
                this.FirePreRequestHandler(webRequest);
            }

            // Get the response
            HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();

            if (webResponse.StatusCode == HttpStatusCode.OK)
            {
                ChangeSet changeSet = new ChangeSet();

                using (Stream responseStream = webResponse.GetResponseStream())
                {
                    // Create the SyncReader
                    this._syncReader = new ODataAtomReader(responseStream, this._knownTypes);

                    // Read the response
                    while (this._syncReader.Next())
                    {
                        switch (this._syncReader.ItemType)
                        {
                            case ReaderItemType.Entry:
                                changeSet.AddItem(this._syncReader.GetItem());
                                break;
                            case ReaderItemType.SyncBlob:
                                changeSet.ServerBlob = this._syncReader.GetServerBlob();
                                break;
                            case ReaderItemType.HasMoreChanges:
                                changeSet.IsLastBatch = !this._syncReader.GetHasMoreChangesValue();
                                break;
                        }
                    }

                    this.FirePostResponseHandler(webResponse);
                }

                webResponse.Close();

                return changeSet;
            }
            else
            {
                throw new CacheControllerException(
                                    string.Format("Remote service returned error status. Status: {0}, Description: {1}",
                                    webResponse.StatusCode,
                                    webResponse.StatusDescription));
            }
        }
Exemple #13
0
        private object ProcessDownloadRequest(HttpWebRequest webRequest, CacheRequest request)
        {
            using (Stream memoryStream = new MemoryStream())
            {
                // Create a SyncWriter to write the contents
                this._syncWriter = new ODataAtomWriter(base.BaseUri);

                this._syncWriter.StartFeed(true, request.KnowledgeBlob ?? new byte[0]);

                this._syncWriter.WriteFeed(XmlWriter.Create(memoryStream));
                memoryStream.Flush();

                webRequest.ContentLength = memoryStream.Position;
                Stream requestStream = webRequest.GetRequestStream();
                CopyStreamContent(memoryStream, requestStream);

                requestStream.Flush();
                requestStream.Close();

                // Fire the Before request handler
                this.FirePreRequestHandler(webRequest);
            }

            // Get the response
            HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();

            if (webResponse.StatusCode == HttpStatusCode.OK)
            {
                ChangeSet changeSet = new ChangeSet();

                using (Stream responseStream = webResponse.GetResponseStream())
                {
                    // Create the SyncReader
                    this._syncReader = new ODataAtomReader(responseStream, this._knownTypes);

                    // Read the response
                    while (this._syncReader.Next())
                    {
                        switch (this._syncReader.ItemType)
                        {
                        case ReaderItemType.Entry:
                            changeSet.AddItem(this._syncReader.GetItem());
                            break;

                        case ReaderItemType.SyncBlob:
                            changeSet.ServerBlob = this._syncReader.GetServerBlob();
                            break;

                        case ReaderItemType.HasMoreChanges:
                            changeSet.IsLastBatch = !this._syncReader.GetHasMoreChangesValue();
                            break;
                        }
                    }

                    this.FirePostResponseHandler(webResponse);
                }

                webResponse.Close();

                return(changeSet);
            }
            else
            {
                throw new CacheControllerException(
                          string.Format("Remote service returned error status. Status: {0}, Description: {1}",
                                        webResponse.StatusCode,
                                        webResponse.StatusDescription));
            }
        }
        /// <summary>
        /// Callback for the Upload HttpWebRequest.beginGetRequestStream
        /// </summary>
        /// <param name="task">Task representing the future request stream</param>
        async Task OnUploadGetRequestStreamCompleted(Task <Stream> task, AsyncArgsWrapper wrapper)
        {
            try
            {
                Stream requestStream = await task.ConfigureAwait(false);

                // Create a SyncWriter to write the contents
                this._syncWriter = (base.SerializationFormat == SerializationFormat.ODataAtom)
                    ? (SyncWriter) new ODataAtomWriter(base.BaseUri)
                    : (SyncWriter) new ODataJsonWriter(base.BaseUri);

                this._syncWriter.StartFeed(wrapper.CacheRequest.IsLastBatch, wrapper.CacheRequest.KnowledgeBlob ?? new byte[0]);

                foreach (IOfflineEntity entity in wrapper.CacheRequest.Changes)
                {
                    // Skip tombstones that dont have a ID element.
                    if (entity.ServiceMetadata.IsTombstone && string.IsNullOrEmpty(entity.ServiceMetadata.Id))
                    {
                        continue;
                    }

                    string tempId = null;

                    // Check to see if this is an insert. i.e ServiceMetadata.Id is null or empty
                    if (string.IsNullOrEmpty(entity.ServiceMetadata.Id))
                    {
                        if (wrapper.TempIdToEntityMapping == null)
                        {
                            wrapper.TempIdToEntityMapping = new Dictionary <string, IOfflineEntity>();
                        }
                        tempId = Guid.NewGuid().ToString();
                        wrapper.TempIdToEntityMapping.Add(tempId, entity);
                    }

                    this._syncWriter.AddItem(entity, tempId);
                }

                if (base.SerializationFormat == SerializationFormat.ODataAtom)
                {
                    this._syncWriter.WriteFeed(XmlWriter.Create(requestStream));
                }
                else
                {
                    this._syncWriter.WriteFeed(JsonReaderWriterFactory.CreateJsonWriter(requestStream));
                }

                requestStream.Flush();
                requestStream.Close();

                if (this._beforeRequestHandler != null)
                {
                    // Invoke user code and wait for them to call back us when they are done with the input request
                    this._workerManager.PostProgress(wrapper.WorkerRequest, this.FirePreRequestHandler, wrapper);
                }
                else
                {
                    this.GetWebResponse(wrapper);
                }
            }
            catch (Exception e)
            {
                if (ExceptionUtility.IsFatal(e))
                {
                    throw;
                }
                wrapper.Error = e;
                this._workerManager.CompleteWorkRequest(wrapper.WorkerRequest, wrapper);
            }
        }
Exemple #15
0
        NSData CreateRequestBody()
        {
            _syncWriter = (SyncWriter) new ODataAtomWriter(base.BaseUri);

            _syncWriter.StartFeed(_wrapper.CacheRequest.IsLastBatch, _wrapper.CacheRequest.KnowledgeBlob ?? new byte[0]);

            MemoryStream requestStream = new MemoryStream();

            if (_wrapper.CacheRequest.RequestType == CacheRequestType.UploadChanges)
            {
                foreach (IOfflineEntity entity in _wrapper.CacheRequest.Changes)
                {
                    // Skip tombstones that dont have a ID element.
                    if (entity.ServiceMetadata.IsTombstone && string.IsNullOrEmpty(entity.ServiceMetadata.Id))
                    {
                        continue;
                    }

                    string tempId = null;

                    // Check to see if this is an insert. i.e ServiceMetadata.Id is null or empty
                    if (string.IsNullOrEmpty(entity.ServiceMetadata.Id))
                    {
                        if (_wrapper.TempIdToEntityMapping == null)
                        {
                            _wrapper.TempIdToEntityMapping = new Dictionary <string, IOfflineEntity> ();
                        }

                        tempId = Guid.NewGuid().ToString();

                        _wrapper.TempIdToEntityMapping.Add(tempId, entity);
                    }

                    _syncWriter.AddItem(entity, tempId);
                }
            }

            if (base.SerializationFormat == SerializationFormat.ODataAtom)
            {
                _syncWriter.WriteFeed(XmlWriter.Create(requestStream));
            }
            else
            {
                _syncWriter.WriteFeed(JsonReaderWriterFactory.CreateJsonWriter(requestStream));
            }

            string result = "";

            requestStream.Seek(0, SeekOrigin.Begin);

            using (StreamReader reader = new StreamReader(requestStream)) {
                result = reader.ReadToEnd();
            }

            requestStream.Flush();
            requestStream.Close();

            NSString dataString = new NSString(result);

            return(dataString.DataUsingEncoding(NSStringEncoding.UTF8));
        }
Exemple #16
0
        private object ProcessUploadRequest(HttpWebRequest webRequest, CacheRequest request)
        {
            using (Stream memoryStream = new MemoryStream())
            {
                // Create a SyncWriter to write the contents
                this._syncWriter = new ODataAtomWriter(base.BaseUri);

                this._syncWriter.StartFeed(true, request.KnowledgeBlob ?? new byte[0]);

                foreach (IOfflineEntity entity in request.Changes)
                {
                    // Skip tombstones that dont have a ID element.
                    if (entity.ServiceMetadata.IsTombstone && string.IsNullOrEmpty(entity.ServiceMetadata.Id))
                    {
                        continue;
                    }

                    string tempId = null;

                    // Check to see if this is an insert. i.e ServiceMetadata.Id is null or empty
                    if (string.IsNullOrEmpty(entity.ServiceMetadata.Id))
                    {
                        if (TempIdToEntityMapping == null)
                        {
                            TempIdToEntityMapping = new Dictionary <string, IOfflineEntity>();
                        }
                        tempId = Guid.NewGuid().ToString();
                        TempIdToEntityMapping.Add(tempId, entity);
                    }

                    this._syncWriter.AddItem(entity, tempId);
                }

                this._syncWriter.WriteFeed(XmlWriter.Create(memoryStream));

                memoryStream.Flush();
                // Set the content length
                webRequest.ContentLength = memoryStream.Position;

                using (Stream requestStream = webRequest.GetRequestStream())
                {
                    CopyStreamContent(memoryStream, requestStream);

                    // Close the request stream
                    requestStream.Flush();
                    requestStream.Close();
                }
            }

            // Fire the Before request handler
            this.FirePreRequestHandler(webRequest);

            // Get the response
            HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();

            if (webResponse.StatusCode == HttpStatusCode.OK)
            {
                ChangeSetResponse changeSetResponse = new ChangeSetResponse();

                using (Stream responseStream = webResponse.GetResponseStream())
                {
                    // Create the SyncReader
                    this._syncReader = new ODataAtomReader(responseStream, this._knownTypes);

                    // Read the response
                    while (this._syncReader.Next())
                    {
                        switch (this._syncReader.ItemType)
                        {
                        case ReaderItemType.Entry:
                            IOfflineEntity entity      = this._syncReader.GetItem();
                            IOfflineEntity ackedEntity = entity;
                            string         tempId      = null;

                            // If conflict only one temp ID should be set
                            if (this._syncReader.HasTempId() && this._syncReader.HasConflictTempId())
                            {
                                throw new CacheControllerException(string.Format("Service returned a TempId '{0}' in both live and conflicting entities.",
                                                                                 this._syncReader.GetTempId()));
                            }

                            // Validate the live temp ID if any, before adding anything to the offline context
                            if (this._syncReader.HasTempId())
                            {
                                tempId = this._syncReader.GetTempId();
                                CheckEntityServiceMetadataAndTempIds(TempIdToEntityMapping, entity, tempId, changeSetResponse);
                            }

                            //  If conflict
                            if (this._syncReader.HasConflict())
                            {
                                Conflict       conflict       = this._syncReader.GetConflict();
                                IOfflineEntity conflictEntity = (conflict is SyncConflict) ?
                                                                ((SyncConflict)conflict).LosingEntity : ((SyncError)conflict).ErrorEntity;

                                // Validate conflict temp ID if any
                                if (this._syncReader.HasConflictTempId())
                                {
                                    tempId = this._syncReader.GetConflictTempId();
                                    CheckEntityServiceMetadataAndTempIds(TempIdToEntityMapping, conflictEntity, tempId, changeSetResponse);
                                }

                                // Add conflict
                                changeSetResponse.AddConflict(conflict);

                                //
                                // If there is a conflict and the tempId is set in the conflict entity then the client version lost the
                                // conflict and the live entity is the server version (ServerWins)
                                //
                                if (this._syncReader.HasConflictTempId() && entity.ServiceMetadata.IsTombstone)
                                {
                                    //
                                    // This is a ServerWins conflict, or conflict error. The winning version is a tombstone without temp Id
                                    // so there is no way to map the winning entity with a temp Id. The temp Id is in the conflict so we are
                                    // using the conflict entity, which has the PK, to build a tombstone entity used to update the offline context
                                    //
                                    // In theory, we should copy the service metadata but it is the same end result as the service fills in
                                    // all the properties in the conflict entity
                                    //

                                    // Add the conflict entity
                                    conflictEntity.ServiceMetadata.IsTombstone = true;
                                    ackedEntity = conflictEntity;
                                }
                            }

                            // Add ackedEntity to storage. If ackedEntity is still equal to entity then add non-conflict entity.
                            if (!String.IsNullOrEmpty(tempId))
                            {
                                changeSetResponse.AddUpdatedItem(ackedEntity);
                            }

                            break;

                        case ReaderItemType.SyncBlob:
                            changeSetResponse.ServerBlob = this._syncReader.GetServerBlob();
                            break;
                        }
                    }
                }

                if (TempIdToEntityMapping != null && TempIdToEntityMapping.Count != 0)
                {
                    // The client sent some inserts which werent ack'd by the service. Throw.
                    StringBuilder builder = new StringBuilder("Server did not acknowledge with a permanant Id for the following tempId's: ");
                    builder.Append(string.Join(",", TempIdToEntityMapping.Keys.ToArray()));
                    throw new CacheControllerException(builder.ToString());
                }

                this.FirePostResponseHandler(webResponse);

                webResponse.Close();

                return(changeSetResponse);
            }
            else
            {
                throw new CacheControllerException(
                          string.Format("Remote service returned error status. Status: {0}, Description: {1}",
                                        webResponse.StatusCode,
                                        webResponse.StatusDescription));
            }
        }
        protected Message CreateResponseMessage(SyncSerializationFormat serializationFormat, SyncWriter oDataWriter)
        {
            var bodyWriter = new DelegateBodyWriter(WriteResponse, oDataWriter);

            Message message = Message.CreateMessage(MessageVersion.None, String.Empty, bodyWriter);

            switch (serializationFormat)
            {
            case SyncSerializationFormat.ODataAtom:
                message.Properties.Add(WebBodyFormatMessageProperty.Name, new WebBodyFormatMessageProperty(WebContentFormat.Xml));
                break;

            case SyncSerializationFormat.ODataJson:
                message.Properties.Add(WebBodyFormatMessageProperty.Name, new WebBodyFormatMessageProperty(WebContentFormat.Json));
                break;
            }

            var property = new HttpResponseMessageProperty {
                StatusCode = HttpStatusCode.OK
            };

            property.Headers[HttpResponseHeader.ContentType] = WebUtil.GetContentType(serializationFormat);

            // Copy the SyncOperationContext's ResponseHeaders if present
            if (this._operationContext != null)
            {
                property.Headers.Add(this._operationContext.ResponseHeaders);
            }

            message.Properties.Add(HttpResponseMessageProperty.Name, property);

            return(message);
        }
Exemple #18
0
        // Write string to the MDbg console.
        // txt - string to write. May contain newlines.
        // outputType -  control string for what type of output (error, std, etc)        
        // highlightStart - index into string txt to begin highlighting at.
        // highlightLen - number of characters to highlight.
        //
        // This may be called on either the UI thread or the Mdbg Worker Thread.
        private void WriteOutputNoNewLine(string outputType, string txt, int highlightStart, int highlightLen)
        {
            // RichTextBox will strip all '\r' values. That will make the Text out of sync 
            // with highlightStart and highlightEnd.             
            
            int highlightStartAdjust = highlightStart;
            int highlightLenAdjust = highlightLen;

            for(int idx = txt.IndexOf('\r'); idx != -1; idx = txt.IndexOf('\r', idx+ 1))
            {
                if (idx < highlightStart)
                {
                    highlightStartAdjust--;
                }
                else if (idx < highlightStart + highlightLen)
                {
                    highlightLenAdjust--;
                }
            }

            string txtAdjust = txt;
            SyncWriter sw = new SyncWriter(this, outputType, txtAdjust, highlightStartAdjust, highlightLenAdjust);

            // Async callback. We can't block the worker thread. These will get queued up in order.
            try
            {
                BeginInvoke(new MethodInvoker(sw.InternalWriteOutput));
            }
            catch (InvalidOperationException)
            {
                // If we can't write out to the GUI, at least write out to the cached IO.  
                this.m_savedIO.WriteOutput(outputType, txt);
            }
        }
        private object ProcessUploadRequest(HttpWebRequest webRequest, CacheRequest request)
        {
            using (Stream memoryStream = new MemoryStream())
            {
                // Create a SyncWriter to write the contents
                this._syncWriter = new ODataAtomWriter(base.BaseUri);

                this._syncWriter.StartFeed(true, request.KnowledgeBlob ?? new byte[0]);

                foreach (IOfflineEntity entity in request.Changes)
                {
                    // Skip tombstones that dont have a ID element.
                    if (entity.ServiceMetadata.IsTombstone && string.IsNullOrEmpty(entity.ServiceMetadata.Id))
                    {
                        continue;
                    }

                    string tempId = null;

                    // Check to see if this is an insert. i.e ServiceMetadata.Id is null or empty
                    if (string.IsNullOrEmpty(entity.ServiceMetadata.Id))
                    {
                        if (TempIdToEntityMapping == null)
                        {
                            TempIdToEntityMapping = new Dictionary<string, IOfflineEntity>();
                        }
                        tempId = Guid.NewGuid().ToString();
                        TempIdToEntityMapping.Add(tempId, entity);
                    }

                    this._syncWriter.AddItem(entity, tempId);
                }

                this._syncWriter.WriteFeed(XmlWriter.Create(memoryStream));

                memoryStream.Flush();
                // Set the content length
                webRequest.ContentLength = memoryStream.Position;

                using (Stream requestStream = webRequest.GetRequestStream())
                {
                    CopyStreamContent(memoryStream, requestStream);

                    // Close the request stream
                    requestStream.Flush();
                    requestStream.Close();
                }
            }

            // Fire the Before request handler
            this.FirePreRequestHandler(webRequest);

            // Get the response
            HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();

            if (webResponse.StatusCode == HttpStatusCode.OK)
            {
                ChangeSetResponse changeSetResponse = new ChangeSetResponse();

                using (Stream responseStream = webResponse.GetResponseStream())
                {
                    // Create the SyncReader
                    this._syncReader = new ODataAtomReader(responseStream, this._knownTypes);

                    // Read the response
                    while (this._syncReader.Next())
                    {
                        switch (this._syncReader.ItemType)
                        {
                            case ReaderItemType.Entry:
                                IOfflineEntity entity = this._syncReader.GetItem();
                                IOfflineEntity ackedEntity = entity;
                                string tempId = null;

                                // If conflict only one temp ID should be set
                                if (this._syncReader.HasTempId() && this._syncReader.HasConflictTempId())
                                {
                                    throw new CacheControllerException(string.Format("Service returned a TempId '{0}' in both live and conflicting entities.",
                                                                       this._syncReader.GetTempId()));
                                }

                                // Validate the live temp ID if any, before adding anything to the offline context
                                if (this._syncReader.HasTempId())
                                {
                                    tempId = this._syncReader.GetTempId();
                                    CheckEntityServiceMetadataAndTempIds(TempIdToEntityMapping, entity, tempId, changeSetResponse);
                                }

                                //  If conflict
                                if (this._syncReader.HasConflict())
                                {
                                    Conflict conflict = this._syncReader.GetConflict();
                                    IOfflineEntity conflictEntity = (conflict is SyncConflict) ?
                                                                    ((SyncConflict)conflict).LosingEntity : ((SyncError)conflict).ErrorEntity;

                                    // Validate conflict temp ID if any
                                    if (this._syncReader.HasConflictTempId())
                                    {
                                        tempId = this._syncReader.GetConflictTempId();
                                        CheckEntityServiceMetadataAndTempIds(TempIdToEntityMapping, conflictEntity, tempId, changeSetResponse);
                                    }

                                    // Add conflict
                                    changeSetResponse.AddConflict(conflict);

                                    //
                                    // If there is a conflict and the tempId is set in the conflict entity then the client version lost the
                                    // conflict and the live entity is the server version (ServerWins)
                                    //
                                    if (this._syncReader.HasConflictTempId() && entity.ServiceMetadata.IsTombstone)
                                    {
                                        //
                                        // This is a ServerWins conflict, or conflict error. The winning version is a tombstone without temp Id
                                        // so there is no way to map the winning entity with a temp Id. The temp Id is in the conflict so we are
                                        // using the conflict entity, which has the PK, to build a tombstone entity used to update the offline context
                                        //
                                        // In theory, we should copy the service metadata but it is the same end result as the service fills in
                                        // all the properties in the conflict entity
                                        //

                                        // Add the conflict entity
                                        conflictEntity.ServiceMetadata.IsTombstone = true;
                                        ackedEntity = conflictEntity;
                                    }
                                }

                                // Add ackedEntity to storage. If ackedEntity is still equal to entity then add non-conflict entity.
                                if (!String.IsNullOrEmpty(tempId)) {
                                    changeSetResponse.AddUpdatedItem(ackedEntity);
                                }

                                break;
                            case ReaderItemType.SyncBlob:
                                changeSetResponse.ServerBlob = this._syncReader.GetServerBlob();
                                break;
                        }
                    }
                }

                if (TempIdToEntityMapping != null && TempIdToEntityMapping.Count != 0)
                {
                    // The client sent some inserts which werent ack'd by the service. Throw.
                    StringBuilder builder = new StringBuilder("Server did not acknowledge with a permanant Id for the following tempId's: ");
                    builder.Append(string.Join(",", TempIdToEntityMapping.Keys.ToArray()));
                    throw new CacheControllerException(builder.ToString());
                }

                this.FirePostResponseHandler(webResponse);

                webResponse.Close();

                return changeSetResponse;
            }
            else
            {
                throw new CacheControllerException(
                                    string.Format("Remote service returned error status. Status: {0}, Description: {1}",
                                    webResponse.StatusCode,
                                    webResponse.StatusDescription));
            }
        }
Exemple #20
0
        NSData CreateRequestBody()
        {
            if (ApplicationContext.Current.Settings.BitMobileFormatterDisabled)
            {
                _syncWriter = new ODataAtomWriter(BaseUri);
            }
            else
            {
                _syncWriter = new BMWriter(BaseUri);
            }

            _syncWriter.StartFeed(_wrapper.CacheRequest.IsLastBatch, _wrapper.CacheRequest.KnowledgeBlob ?? new byte[0]);

            var requestStream = new MemoryStream();

            if (_wrapper.CacheRequest.RequestType == CacheRequestType.UploadChanges)
            {
                foreach (IOfflineEntity entity in _wrapper.CacheRequest.Changes)
                {
                    var ientity = (IEntity)entity;
                    // Skip tombstones that dont have a ID element.
                    if (entity.ServiceMetadata.IsTombstone && string.IsNullOrEmpty(entity.ServiceMetadata.Id))
                    {
                        if (ientity != null)
                        {
                            LogManager.Logger.SyncUpload(ientity.EntityType, true);
                        }
                        continue;
                    }

                    string tempId = null;

                    // Check to see if this is an insert. i.e ServiceMetadata.Id is null or empty
                    if (string.IsNullOrEmpty(entity.ServiceMetadata.Id))
                    {
                        if (_wrapper.TempIdToEntityMapping == null)
                        {
                            _wrapper.TempIdToEntityMapping = new Dictionary <string, IOfflineEntity>();
                        }

                        tempId = Guid.NewGuid().ToString();

                        _wrapper.TempIdToEntityMapping.Add(tempId, entity);
                    }

                    _syncWriter.AddItem(entity, tempId);

                    if (ientity != null)
                    {
                        LogManager.Logger.SyncUpload(ientity.EntityType);
                    }
                }
            }

            _syncWriter.WriteFeed(SerializationFormat == SerializationFormat.ODataAtom
                ? XmlWriter.Create(requestStream)
                : JsonReaderWriterFactory.CreateJsonWriter(requestStream));

            string result;

            requestStream.Seek(0, SeekOrigin.Begin);

            using (var reader = new StreamReader(requestStream))
            {
                result = reader.ReadToEnd();
            }

            requestStream.Flush();
            requestStream.Close();

            var dataString = new NSString(result);

            return(dataString.DataUsingEncoding(NSStringEncoding.UTF8));
        }