Exemple #1
0
        private void SaveConcrete(object obj)
        {
            if (obj is Document)
            {
                _session.Save(obj);
            }
            else if (obj is IIndex)
            {
                _session.Save(obj);
            }
            else
            {
                var doc = new Document();

                // convert the custom object to a storable document
                _serializer.Serialize(obj, ref doc);

                // if the object is not new, reload to get the old map
                int id;
                if (_documents.TryGetValue(obj, out id))
                {
                    var oldDoc = _session.Get <Document>(id);
                    var oldObj = _serializer.Deserialize(oldDoc);

                    // do nothing if the document hasn't been modified
                    if (oldDoc.Content != doc.Content)
                    {
                        oldDoc.Content = doc.Content;

                        MapDeleted(oldDoc, oldObj);

                        // update document
                        MapNew(oldDoc, obj);
                    }
                }
                else
                {
                    // new document
                    _session.Save(doc);

                    var accessor = _store.GetIdAccessor(obj.GetType(), "Id");

                    // if the object has an Id property, set it back
                    var ident = accessor.Get(obj);
                    if (ident != null)
                    {
                        accessor.Set(obj, doc.Id);
                    }

                    // track the newly created object
                    TrackObject(obj, doc);

                    MapNew(doc, obj);
                }
            }
        }
        public static Commit ToCommit(this BsonDocument doc, IDocumentSerializer serializer)
        {
            if (doc == null)
            {
                return(null);
            }

            BsonDocument id             = doc[MongoFields.Id].AsBsonDocument;
            string       bucketId       = id[MongoFields.BucketId].AsString;
            string       streamId       = id[MongoFields.StreamId].AsString;
            int          commitSequence = id[MongoFields.CommitSequence].AsInt32;

            List <EventMessage> events = doc[MongoFields.Events]
                                         .AsBsonArray
                                         .Select(e =>
                                                 e.AsBsonDocument[MongoFields.Payload].IsBsonDocument
                        ? BsonSerializer.Deserialize <EventMessage>(e.AsBsonDocument[MongoFields.Payload].AsBsonDocument)
                        : serializer.Deserialize <EventMessage>(e.AsBsonDocument[MongoFields.Payload].AsByteArray))
                                         .ToList();
            int streamRevision = doc[MongoFields.Events].AsBsonArray.Last().AsBsonDocument[MongoFields.StreamRevision].AsInt32;

            return(new Commit(
                       bucketId,
                       streamId,
                       streamRevision,
                       doc[MongoFields.CommitId].AsGuid,
                       commitSequence,
                       doc[MongoFields.CommitStamp].ToUniversalTime(),
                       doc[MongoFields.Headers].AsDictionary <string, object>(),
                       events));
        }
        public static ICommit ToCommit_original(this BsonDocument doc, IDocumentSerializer serializer)
        {
            if (doc == null)
            {
                return(null);
            }

            string bucketId       = doc[MongoCommitFields.BucketId].AsString;
            string streamId       = doc[MongoCommitFields.StreamId].AsString;
            int    commitSequence = doc[MongoCommitFields.CommitSequence].AsInt32;

            var events = doc[MongoCommitFields.Events]
                         .AsBsonArray
                         .Select(e =>
            {
                BsonValue payload = e.AsBsonDocument[MongoCommitFields.Payload];
                return(payload.IsBsonDocument
                           ? BsonSerializer.Deserialize <EventMessage>(payload.ToBsonDocument())
                           : serializer.Deserialize <EventMessage>(payload.AsByteArray));
            })
                         .ToArray();

            //int streamRevision = doc[MongoCommitFields.Events].AsBsonArray.Last().AsBsonDocument[MongoCommitFields.StreamRevision].AsInt32;
            int streamRevision = doc[MongoCommitFields.StreamRevisionTo].AsInt32;

            return(new Commit(bucketId,
                              streamId,
                              streamRevision,
                              doc[MongoCommitFields.CommitId].AsGuid,
                              commitSequence,
                              doc[MongoCommitFields.CommitStamp].ToUniversalTime(),
                              doc[MongoCommitFields.CheckpointNumber].ToInt64(),
                              doc[MongoCommitFields.Headers].AsDictionary <string, object>(),
                              events));
        }
Exemple #4
0
        private FlowDocument CloneDocument(FlowDocument flowDocument)
        {
            MathDocument mathDocument             = _serializer.Serialize(flowDocument);
            FlowDocument deserializedFlowDocument = _serializer.Deserialize(mathDocument);

            return(deserializedFlowDocument);
        }
        public static Snapshot ToSnapshot(this BsonDocument doc, IDocumentSerializer serializer)
        {
            if (doc == null)
                return null;

            var id = doc["_id"].AsBsonDocument;
            var streamId = id["StreamId"].AsGuid;
            var streamRevision = id["StreamRevision"].AsInt32;
            var bsonPayload = doc["Payload"];

            object payload;
            switch (bsonPayload.BsonType)
            {
                case BsonType.Binary:
                    payload = serializer.Deserialize<object>(bsonPayload.AsByteArray);
                    break;
                case BsonType.Document:
                    payload = BsonSerializer.Deserialize<object>(bsonPayload.AsBsonDocument);
                    break;
                default:
                    payload = bsonPayload.RawValue;
                    break;
            }

            return new Snapshot(
                streamId,
                streamRevision,
                payload);
        }
Exemple #6
0
        public TDocument Get(string documentName)
        {
            CloudBlobClient    blobStorageType = Account.CreateCloudBlobClient();
            CloudBlobContainer container       = blobStorageType.GetContainerReference(DocumentsContainerName);
            var blobAddressUri = documentName;

            var serializationStream = new MemoryStream();

            //try
            //{
            //	container.GetBlobReference(blobAddressUri).DownloadToStream(serializationStream);
            //}
            //catch (StorageClientException e)
            //{
            //	if (e.StatusCode == HttpStatusCode.NotFound)
            //	{
            //		return null;
            //	}
            //	throw;
            //}
            //TODO: revisar que tipo de exception tira
            try
            {
                container.GetBlockBlobReference(blobAddressUri).DownloadToStream(serializationStream);
            }
            catch (Exception)
            {
                return(null);
            }
            return(_documentSerializer.Deserialize(serializationStream));
        }
        public static Snapshot ToSnapshot(this BsonDocument doc, IDocumentSerializer serializer)
        {
            if (doc == null)
            {
                return(null);
            }

            var id             = doc["_id"].AsBsonDocument;
            var streamId       = id["StreamId"].AsGuid;
            var streamRevision = id["StreamRevision"].AsInt32;
            var bsonPayload    = doc["Payload"];

            object payload;

            switch (bsonPayload.BsonType)
            {
            case BsonType.Binary:
                payload = serializer.Deserialize <object>(bsonPayload.AsByteArray);
                break;

            case BsonType.Document:
                payload = BsonSerializer.Deserialize <object>(bsonPayload.AsBsonDocument);
                break;

            default:
                payload = BsonTypeMapper.MapToDotNetValue(bsonPayload);
                break;
            }

            return(new Snapshot(
                       streamId,
                       streamRevision,
                       payload));
        }
        public static ICommit ToCommit(this BsonDocument doc, IDocumentSerializer serializer)
        {
            if (doc == null)
            {
                return(null);
            }

            var mc = BsonSerializer.Deserialize <MongoCommit>(doc);

            return(new Commit(mc.BucketId,
                              mc.StreamId,
                              mc.StreamRevisionTo,
                              mc.CommitId,
                              mc.CommitSequence,
                              mc.CommitStamp,
                              mc.CheckpointNumber,
                              mc.Headers,
                              mc.Events.Select(e =>
            {
                BsonValue payload = e[MongoCommitFields.Payload];
                return payload.IsBsonDocument
                           ? BsonSerializer.Deserialize <EventMessage>(payload.ToBsonDocument())
                           : serializer.Deserialize <EventMessage>(payload.AsByteArray); // ByteStreamDocumentSerializer ?!?! doesn't work this way!
            }).ToArray()));
        }
Exemple #9
0
        public override async Task ExecuteAsync(IContext context, SendMessageFromHttpSettings settings, CancellationToken cancellationToken)
        {
            var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, settings.Uri);

            if (settings.Headers != null)
            {
                foreach (var header in settings.Headers)
                {
                    httpRequestMessage.Headers.TryAddWithoutValidation(header.Key, header.Value);
                }
            }
            else
            {
                httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(settings.Type));
            }

            using (var cts = new CancellationTokenSource(settings.RequestTimeout ?? DefaultRequestTimeout))
                using (var linkedCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, cts.Token))
                    using (var httpResponseMessage = await _httpClient.SendAsync(httpRequestMessage, linkedCts.Token).ConfigureAwait(false))
                    {
                        httpResponseMessage.EnsureSuccessStatusCode();

                        var body = await httpResponseMessage.Content.ReadAsStringAsync();

                        var message = new Message(EnvelopeId.NewId())
                        {
                            Id      = EnvelopeId.NewId(),
                            To      = context.Input.Message.From,
                            Content = _documentSerializer.Deserialize(body, settings.MediaType)
                        };

                        await _sender.SendMessageAsync(message, cancellationToken);
                    }
        }
        public static Snapshot ToSnapshot(this BsonDocument doc, IDocumentSerializer serializer)
        {
            if (doc == null)
            {
                return(null);
            }

            BsonDocument id             = doc[MongoFields.Id].AsBsonDocument;
            string       bucketId       = id[MongoFields.BucketId].AsString;
            string       streamId       = id[MongoFields.StreamId].AsString;
            int          streamRevision = id[MongoFields.StreamRevision].AsInt32;
            BsonValue    bsonPayload    = doc[MongoFields.Payload];

            object payload;

            switch (bsonPayload.BsonType)
            {
            case BsonType.Binary:
                payload = serializer.Deserialize <object>(bsonPayload.AsByteArray);
                break;

            case BsonType.Document:
                payload = BsonSerializer.Deserialize <object>(bsonPayload.AsBsonDocument);
                break;

            default:
                payload = BsonTypeMapper.MapToDotNetValue(bsonPayload);
                break;
            }

            return(new Snapshot(bucketId, streamId, streamRevision, payload));
        }
Exemple #11
0
        public static Commit ToCommit(this BsonDocument doc, IDocumentSerializer serializer)
        {
            if (doc == null)
            {
                return(null);
            }

            BsonDocument id             = doc["_id"].AsBsonDocument;
            Guid         streamId       = id["StreamId"].AsGuid;
            int          commitSequence = id["CommitSequence"].AsInt32;

            List <EventMessage> events =
                doc["Events"].AsBsonArray.Select(
                    e =>
                    e.AsBsonDocument["Payload"].IsBsonDocument
                                                         ? BsonSerializer.Deserialize <EventMessage>(
                        e.AsBsonDocument["Payload"]
                        .AsBsonDocument)
                                                         : serializer.Deserialize <EventMessage>(e.AsBsonDocument["Payload"].AsByteArray))
                .ToList();
            int streamRevision = doc["Events"].AsBsonArray.Last().AsBsonDocument["StreamRevision"].AsInt32;

            return(new Commit(streamId,
                              streamRevision,
                              doc["CommitId"].AsGuid,
                              commitSequence,
                              doc["CommitStamp"].ToUniversalTime(),
                              doc["Headers"].AsDictionary <string, object>(),
                              events));
        }
    public static Snapshot ToSnapshot(this RavenSnapshot snapshot, IDocumentSerializer serializer)
    {
      if (snapshot == null)
        return null;

      return new Snapshot(snapshot.BucketId, snapshot.StreamId, snapshot.StreamRevision,
        serializer.Deserialize<object>(snapshot.Payload));
    }
Exemple #13
0
 public static Snapshot ToSnapshot(this DocumentSnapshot snapshot, IDocumentSerializer serializer)
 {
     if (snapshot == null)
     {
         return(null);
     }
     return(new Snapshot(snapshot.BucketId, snapshot.StreamRevision,
                         serializer.Deserialize <object>(snapshot.Payload)));
 }
 public static Commit ToCommit(this RavenCommit commit, IDocumentSerializer serializer)
 {
     return new Commit(commit.StreamId,
         commit.StreamRevision,
         commit.CommitId,
         commit.CommitSequence,
         commit.CommitStamp,
         commit.Headers,
         serializer.Deserialize<List<EventMessage>>(commit.Payload));
 }
 public static Commit ToCommit(this RavenCommit commit, IDocumentSerializer serializer)
 {
     return(new Commit(commit.StreamId,
                       commit.StreamRevision,
                       commit.CommitId,
                       commit.CommitSequence,
                       commit.CommitStamp,
                       commit.Headers,
                       serializer.Deserialize <List <EventMessage> >(commit.Payload)));
 }
Exemple #16
0
        public override Task ExecuteAsync(IContext context, SendRawMessageSettings settings, CancellationToken cancellationToken)
        {
            var message = new Message(EnvelopeId.NewId())
            {
                Id       = EnvelopeId.NewId(),
                To       = context.User.ToNode(),
                Content  = _documentSerializer.Deserialize(settings.RawContent, settings.MediaType),
                Metadata = settings.Metadata
            };

            return(_sender.SendMessageAsync(message, cancellationToken));
        }
Exemple #17
0
        private async Task <TModel> TranslateResponse <TModel>(HttpResponseMessage response)
        {
            var responseJson = await response.Content.ReadAsStringAsync();

            var model = _jsonDocumentSerializer.Deserialize <TModel>(responseJson);

            if (model is BaseResponse res)
            {
                res.StatusCode = (int)response.StatusCode;
            }

            return(model);
        }
        protected override Task ExecuteAsync(SendMessageOptions options, IEstablishedChannel channel, CancellationToken cancellationToken)
        {
            var content = _documentSerializer.Deserialize(options.JoinedContent, options.Type);

            return(channel.SendMessageAsync(
                       new Message(options.Id)
            {
                From = options.From,
                To = options.To,
                Content = content
            },
                       cancellationToken));
        }
        public Document ToDocument(IDocumentSerializer documentSerializer, JsonSerializer serializer)
        {
            var mediaType = Type;

            if (mediaType == null)
            {
                // Use the old method to determine the document type
                var jObject = JObject.Parse(Document);
                mediaType = jObject[TYPE_KEY].ToObject <MediaType>(serializer);
            }

            return(documentSerializer.Deserialize(Document, mediaType));
        }
Exemple #20
0
 public static ICommit ToCommit(this DocumentCommit commit, IDocumentSerializer serializer)
 {
     return(new Commit(
                commit.BucketId,
                commit.StreamId,
                commit.StreamRevision,
                commit.CommitId,
                commit.CommitSequence,
                commit.CommitStamp,
                commit.CheckpointNumber.ToString(CultureInfo.InvariantCulture),
                commit.Headers,
                serializer.Deserialize <IList <EventMessage> >(commit.Payload)
                ));
 }
 public static ICommit ToCommit(this RavenCommit commit, IDocumentSerializer serializer)
 {
   return new Commit(
       commit.BucketId,
       commit.StreamId,
       commit.StreamRevision,
       commit.CommitId,
       commit.CommitSequence,
       commit.CommitStamp,
       commit.CheckpointNumber.ToString(CultureInfo.InvariantCulture),
       commit.Headers,
       serializer.Deserialize<IList<EventMessage>>(commit.Payload)
       );
 }
Exemple #22
0
        protected override Task ExecuteAsync(SendCommandOptions options, IEstablishedChannel channel, CancellationToken cancellationToken)
        {
            var resource = _documentSerializer.Deserialize(options.JoinedResource, options.Type);

            return(channel.SendCommandAsync(
                       new Command(options.Id ?? EnvelopeId.NewId())
            {
                From = options.From,
                To = options.To,
                Method = options.Method,
                Uri = new LimeUri(options.Uri),
                Resource = resource
            },
                       cancellationToken));
        }
Exemple #23
0
        public override Task ExecuteAsync(IContext context, SendRawMessageSettings settings, CancellationToken cancellationToken)
        {
            var message = new Message(null)
            {
                To       = context.Input.Message.From,
                Content  = _documentSerializer.Deserialize(settings.RawContent, settings.MediaType),
                Metadata = settings.Metadata
            };

            if (message.Content?.GetMediaType() != ChatState.MediaType)
            {
                message.Id = EnvelopeId.NewId();
            }

            return(_sender.SendMessageAsync(message, cancellationToken));
        }
        public async Task <Image> UploadImage([Base64] string image, string authority)
        {
            var document = _documentSerializer.Deserialize(image);

            var name = $"{Guid.NewGuid()}{document.Extension}";
            var path = Path.Combine($"{_hostingEnvironment.ContentRootPath}/wwwroot/storage");

            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }

            await File.WriteAllBytesAsync($"{path}/{name}", document.Buffer);

            return(new Image()
            {
                ImagePath = $"{authority}/storage/{name}"
            });
        }
        public static Commit ToCommit(this BsonDocument doc, IDocumentSerializer serializer)
        {
            if (doc == null)
                return null;

            var id = doc["_id"].AsBsonDocument;
            var streamId = id["StreamId"].AsGuid;
            var commitSequence = id["CommitSequence"].AsInt32;

            var events = doc["Events"].AsBsonArray.Select(e => e.AsBsonDocument["Payload"].IsBsonDocument ? BsonSerializer.Deserialize<EventMessage>(e.AsBsonDocument["Payload"].AsBsonDocument) : serializer.Deserialize<EventMessage>(e.AsBsonDocument["Payload"].AsByteArray)).ToList();
            var streamRevision = doc["Events"].AsBsonArray.Last().AsBsonDocument["StreamRevision"].AsInt32;
            return new Commit(
                streamId,
                streamRevision,
                doc["CommitId"].AsGuid,
                commitSequence,
                doc["CommitStamp"].AsDateTime,
                BsonSerializer.Deserialize<Dictionary<string, object>>(doc["Headers"].AsBsonDocument),
                events);
        }
Exemple #26
0
        protected override async Task ExecuteAsync(ProcessCommandOptions options, IEstablishedChannel channel, CancellationToken cancellationToken)
        {
            if (options.ExpectedResource != null && options.Method != CommandMethod.Get)
            {
                throw new Exception("The expected resource option can only be used with 'get' method");
            }

            var resource = _documentSerializer.Deserialize(options.JoinedResource, options.Type);

            using (var cts = new CancellationTokenSource(TimeSpan.FromSeconds(options.Timeout)))
                using (var linkedCts = CancellationTokenSource.CreateLinkedTokenSource(cts.Token, cancellationToken))
                {
                    var responseCommand = await channel.ProcessCommandAsync(
                        new Command(options.Id ?? EnvelopeId.NewId())
                    {
                        From     = options.From,
                        To       = options.To,
                        Method   = options.Method,
                        Uri      = new LimeUri(options.Uri),
                        Resource = resource
                    },
                        cancellationToken);

                    if (responseCommand.Status != options.ExpectedStatus)
                    {
                        throw new Exception($"Unexpected response status '{responseCommand.Status}' ({responseCommand.Reason?.ToString()})");
                    }

                    if (options.ExpectedResource != null)
                    {
                        var expectedResourceRegex = new Regex(options.ExpectedResource);
                        var responseResource      = _documentSerializer.Serialize(responseCommand.Resource);

                        if (!expectedResourceRegex.IsMatch(responseResource))
                        {
                            throw new Exception($"Unexpected response resource: {responseResource}");
                        }
                    }
                }
        }
        public async Task <TDocument> Get(string documentName)
        {
            var blobStorageType = Account.CreateCloudBlobClient();
            var container       = blobStorageType.GetContainerReference("finances");
            var blobAddressUri  = documentName;

            var serializationStream = new MemoryStream();

            try
            {
                var blobref = container.GetBlockBlobReference(blobAddressUri);
                await blobref.DownloadToStreamAsync(serializationStream);
            }
            catch (StorageException e)
            {
                if (e.RequestInformation.HttpStatusCode == (int)HttpStatusCode.NotFound)
                {
                    return(null);
                }
                throw;
            }
            return(documentSerializer.Deserialize(serializationStream));
        }
Exemple #28
0
        protected async Task <Document> ParseDocumentAsync(HttpRequest request)
        {
            Document document = null;

            MediaType mediaType;

            if (MediaType.TryParse(request.Headers[HttpRequestHeader.ContentType], out mediaType))
            {
                using (var streamReader = new StreamReader(request.BodyStream))
                {
                    var body = await streamReader.ReadToEndAsync().ConfigureAwait(false);

                    if (_traceWriter != null &&
                        _traceWriter.IsEnabled)
                    {
                        await _traceWriter.TraceAsync(body, DataOperation.Receive).ConfigureAwait(false);
                    }

                    document = _serializer.Deserialize(body, mediaType);
                }
            }

            return(document);
        }
Exemple #29
0
        internal async Task Init()
        {
            var content = await _storage.Read(_ref);

            Data = _serializer.Deserialize <T>(content) ?? new T();
        }