コード例 #1
0
 public IssueAssociatedWithNewBacklogItem(TenantId tenantId, ProductId productId, IssueId issueId)
 {
     TenantId = tenantId;
     ProductId = productId;
     IssueId = issueId;
     OccurredOn = DateTime.Now;
 }
コード例 #2
0
ファイル: Product.cs プロジェクト: rmoorman/SaasOvation
 void MustBeActive(TenantId tenant = null, ProductId product = null, IssueId ticket = null,IssueAssignerId assigner=null)
 {
     if (tenant != null) Guard.That(Queries.IsActive(tenant), "This is an inactive tenant");
     if (product != null) Guard.That(Queries.IsActive(tenant,product), "This is an inactive product");
     if (ticket != null) Guard.That(Queries.IsActive(tenant, product, ticket), "This is an inactive ticket");
     if (assigner != null) Guard.That(Queries.IsActive(tenant, assigner), "This is an inactive assigner");
 }
コード例 #3
0
ファイル: Messages.cs プロジェクト: jcwrequests/btw-gtd
 public ActionAssignedToProject(TenantId id, ActionId action, ProjectId newProject, DateTime timeUtc)
 {
     Id = id;
     Action = action;
     NewProject = newProject;
     TimeUtc = timeUtc;
 }
コード例 #4
0
        /// <summary>
        /// Called by the scheduler at the time of the trigger firing, in order to
        ///                         produce a <see cref="T:Quartz.IJob"/> instance on which to call Execute.
        /// 
        /// </summary>
        /// 
        /// <remarks>
        /// It should be extremely rare for this method to throw an exception -
        ///                         basically only the the case where there is no way at all to instantiate
        ///                         and prepare the Job for execution.  When the exception is thrown, the
        ///                         Scheduler will move all triggers associated with the Job into the
        ///                         <see cref="F:Quartz.TriggerState.Error"/> state, which will require human
        ///                         intervention (e.g. an application restart after fixing whatever
        ///                         configuration problem led to the issue wih instantiating the Job.
        /// 
        /// </remarks>
        /// <param name="bundle">The TriggerFiredBundle from which the <see cref="T:Quartz.IJobDetail"/>
        ///                           and other info relating to the trigger firing can be obtained.
        ///                         </param><param name="scheduler">a handle to the scheduler that is about to execute the job</param><throws>SchedulerException if there is a problem instantiating the Job. </throws>
        /// <returns>
        /// the newly instantiated Job
        /// 
        /// </returns>
        public IJob NewJob(TriggerFiredBundle bundle, IScheduler scheduler)
        {
            var jobType = bundle.JobDetail.JobType.FullName;
            TenantId tenantId = null;
            if (bundle.JobDetail.JobDataMap.ContainsKey(JobKeys.TenantId))
            {
                tenantId = new TenantId(
                    bundle.JobDetail.JobDataMap.GetString(JobKeys.TenantId)
                    );
                Logger.DebugFormat("new job {0} on tenant {1}", jobType, tenantId );
            }
            else
            {
                if (typeof (ITenantJob).IsAssignableFrom(bundle.JobDetail.JobType))
                {
                    string message = String.Format("Job {0}: missing tenantId", jobType);
                    Logger.Error(message);
                    throw new Exception(message);
                }

                Logger.DebugFormat("new job {0} without tenant", jobType);
            }

            var kernel = SelectKernel(tenantId);
            var job = this.ResolveByJobName ? 
                (IJob)kernel.Resolve(bundle.JobDetail.Key.ToString(), typeof(IJob)) :
                (IJob)kernel.Resolve(bundle.JobDetail.JobType);

            if (job is ITenantJob)
            {
                (job as ITenantJob).TenantId = new TenantId(tenantId);
            }

            return job;
        }
コード例 #5
0
 public String[] GetPending(TenantId tenantId, DocumentHandle handle)
 {
     using (Metric.Timer("queue-getPending", Unit.Requests).NewContext(handle))
     {
         if (QueueManager == null) return null;
         return QueueManager.GetPendingJobs(tenantId, handle);
     }
 }
コード例 #6
0
        /// <summary>
        /// Handle a <see cref="StreamReadModel" /> and generates job for the queue
        /// if needed.
        /// </summary>
        /// <param name="streamElement"></param>
        /// <param name="tenantId"></param>
        /// <param name="forceReSchedule"></param>
        public void Handle(
            StreamReadModel streamElement, 
            TenantId tenantId,
            Boolean forceReSchedule = false)
        {
            if (_info.ShouldCreateJob(streamElement)) 
            {
                if (!forceReSchedule)
                {
                    //look for already existing job with the same blobid, there is no need to re-queue again
                    //because if a job with the same blobid was already fired for this queue there is no need
                    //to re-issue
                    var existing = _collection.Find(
                        Builders< QueuedJob>.Filter.And(
                            Builders< QueuedJob>.Filter.Eq(j => j.BlobId, streamElement.FormatInfo.BlobId),
                            Builders<QueuedJob>.Filter.Eq(j => j.TenantId, tenantId)
                        )
                    ).Count() > 0;
                    if (existing) return;
                }
                if (Logger.IsDebugEnabled) Logger.DebugFormat("Create queue for readmodel stream id {0} and queue {1}", streamElement.Id, _info.Name);
                QueuedJob job = new QueuedJob();
                var id = new QueuedJobId(Guid.NewGuid().ToString());
                job.Id = id;
                job.SchedulingTimestamp = DateTime.Now;
                job.StreamId = streamElement.Id;
                job.TenantId = tenantId;
                job.DocumentDescriptorId = streamElement.DocumentDescriptorId;
                job.BlobId = streamElement.FormatInfo.BlobId;
                job.Handle = new DocumentHandle( streamElement.Handle);
                job.Parameters = new Dictionary<string, string>();
                job.Parameters.Add(JobKeys.FileExtension, streamElement.Filename.Extension);
                job.Parameters.Add(JobKeys.Format, streamElement.FormatInfo.DocumentFormat);
                job.Parameters.Add(JobKeys.FileName, streamElement.Filename);
                job.Parameters.Add(JobKeys.TenantId, tenantId);
                job.Parameters.Add(JobKeys.MimeType, MimeTypes.GetMimeType(streamElement.Filename));
                job.HandleCustomData = streamElement.DocumentCustomData;
                if (_info.Parameters != null) 
                {
                    foreach (var parameter in _info.Parameters)
                    {
                        job.Parameters.Add(parameter.Key, parameter.Value);
                    }
                }

                _collection.InsertOne(job);
            }
        }
コード例 #7
0
        public HttpResponseMessage GetStream(TenantId tenantId, string aggregateId)
        {
            if (string.IsNullOrEmpty(aggregateId))
                return null;

            String identity = aggregateId;
            try
            {
                _identityConverter.ToIdentity(aggregateId);
            }
            catch (Exception)
            {
                //it could be a handle
                var handle = _handleMapper.TryTranslate(aggregateId);
                if (handle == null)
                    throw new ArgumentException("Invalid aggregateId", "aggregateId");

                identity = handle.AsString();
            }
      

            var commits = _commits.GetFrom("Jarvis", identity, 0, int.MaxValue);
            
            var commitsList = new List<CommitModel>();
            foreach (var commit in commits)
            {
                _enhancer.Enhance(commit);
                commitsList.Add(new CommitModel(commit));
            }
            EventStreamResult result = new EventStreamResult();
            result.Commits = commitsList;
            result.AggregateId = identity;
             
            var all = result.ToJson()
                .Replace("\"_t\"", "\"Type\"")
                .Replace("ISODate(", "")
                .Replace("CSUUID(", "")
                .Replace("\")", "\"");          
            
            var sc = new StringContent(all);
            sc.Headers.ContentType = new MediaTypeHeaderValue("application/json");

            var resp = new HttpResponseMessage {Content = sc};
            return resp;
        }
コード例 #8
0
        void Update(TenantId id, Action<TenantAggregate> executeCommandUsingThis)
        {
            var streamId = id.Id.ToString();
            var eventStream = _eventStore.LoadEventStream(streamId);

            var state = TenantState.BuildStateFromHistory(eventStream.Events);

            var aggregate = new TenantAggregate(state);

            // HACK
            if (eventStream.Events.Count == 0)
            {
                aggregate.Create(id);
            }

            executeCommandUsingThis(aggregate);
            _eventStore.AppendEventsToStream(streamId, eventStream.StreamVersion, aggregate.EventsThatHappened);
        }
コード例 #9
0
        public HttpResponseMessage GetFeed(TenantId tenantId, Int64 startId, Int32 numOfResults, [ModelBinder] List<Int32> types)
        {
            var baseQuery = _streamReadModel.AllUnsorted
                .Where(s => s.Id >= startId);

            if (types != null && types.Count > 0)
            {
                baseQuery = baseQuery.Where(r => types.Contains((Int32) r.EventType));
            }

            var result = baseQuery.Take(numOfResults)
                .ToList()
                .Select(rm => new FeedForStreamReadModel(rm))
                .ToList();
            var sc = new StringContent(JsonConvert.SerializeObject(result));
            sc.Headers.ContentType = new MediaTypeHeaderValue("application/json");

            var resp = new HttpResponseMessage { Content = sc };
            return resp;
        }
コード例 #10
0
        public async Task<HttpResponseMessage> GetFormat(
            TenantId tenantId,
            String documentId
        )
        {
            var slot = _recycleBin.Slots.SingleOrDefault(s => s.Id.StreamId == documentId);
            if (slot == null)
            {
                return NotFound(String.Format("Document {0} Not Found", documentId));
            }

            var fileName = slot.Data["FileName"] as String;
            var blobId = slot.Data["OriginalBlobId"] as string;
            
            return StreamFile(
                new BlobId(blobId),
                fileName ?? "blob.bin"
            );

        }
コード例 #11
0
 public async Task<HttpResponseMessage> Compose(
     TenantId tenantId,
     Model.ComposeDocumentsModel dto)
 {
     QueuedJob job = new QueuedJob();
     var id = new QueuedJobId(Guid.NewGuid().ToString());
     job.Id = id;
     job.SchedulingTimestamp = DateTime.Now;
     job.StreamId = 0;
     job.TenantId = tenantId;
     job.Parameters = new Dictionary<string, string>();
     job.Parameters.Add("documentList", String.Join<Object>("|", dto.DocumentList));
     job.Parameters.Add("resultingDocumentHandle", dto.ResultingDocumentHandle);
     job.Parameters.Add("resultingDocumentFileName", dto.ResultingDocumentFileName ?? dto.ResultingDocumentHandle);
     job.Parameters.Add(JobKeys.TenantId, tenantId);
     _queueDispatcher.QueueJob("pdfComposer", job);
     return Request.CreateResponse(
         HttpStatusCode.OK, 
         new  { result = "ok"}
     );
 }
コード例 #12
0
        public RecycleBinResponse GetRecycleBin(
                TenantId tenantId,
                RecycleBinRequest request
            )
        {
            var page = request.Page - 1;
            var start = page * request.PageSize;

            var query = _recycleBin.Slots
                .Where(s => s.Id.StreamId.StartsWith("Document_"));

            var recycledDocuments = query
                .OrderByDescending(s => s.DeletedAt)
                .Skip(start)
                .Take(request.PageSize)
                .ToList()
                .Select(r =>
                {
                    return new RecycleBinData()
                    {
                        Handle = r.Data["Handle"].ToString(),
                        FileName = r.Data["FileName"] as String,
                        DeletedAt = r.DeletedAt,
                        CustomData = r.Data["CustomData"],
                        DocumentId = r.Id.StreamId
                    };
                })
                .ToList();

            var count = query.Count();

            return new RecycleBinResponse
            {
                Documents = recycledDocuments,
                Count = count,
            };
        }
コード例 #13
0
        public IHttpActionResult GetStats(TenantId tenantId)
        {
            var totals = BlobStore.GetInfo();

            var result = DocStats.Collection.Aggregate()
                .Group(BsonDocument.Parse("{_id:1, bytes:{$sum:'$Bytes'}, documents:{$sum:'$Files'}}"))
                .SingleOrDefault();

            int documents = result != null ? result["documents"].AsInt32 : 0;
            long bytes = result != null ? result["bytes"].AsInt64 : 0;
            long files = totals != null ? totals.Files : 0;


            var stats = new
            {
                Tenant = tenantId,
                Documents = documents,
                DocBytes = bytes,
                Handles = Handles.Count(),
                Files = files
            };

            return Ok(stats);
        }
コード例 #14
0
ファイル: Program.cs プロジェクト: ddd-cqrs-es/DDDWorkshop
        static void Main()
        {
            //Make sure you start an instance of EventStore before running this!!
            var credentials = new UserCredentials("admin", "changeit");
            var connection  = EventStoreConnection.Create(
                ConnectionSettings.Create().
                UseConsoleLogger().
                SetDefaultUserCredentials(
                    credentials),
                new IPEndPoint(IPAddress.Loopback, 1113),
                "EventStoreShopping");

            connection.Connect();



            var productUow        = new UnitOfWork();
            var productRepository = new Repository <Product>(
                Product.Factory,
                productUow,
                connection,
                new EventReaderConfiguration(
                    new SliceSize(512),
                    new JsonDeserializer(),
                    new PassThroughStreamNameResolver(),
                    new FixedStreamUserCredentialsResolver(credentials)));

            var tenantId  = new TenantId(Guid.NewGuid().ToString());
            var productId = new ProductId();

            productRepository.Add(productId.ToString(),
                                  new Product(tenantId,
                                              productId,
                                              "dolphin-tuna",
                                              "non-dolphin free",
                                              new ProductManager(Guid.NewGuid().ToString()),
                                              new IssueAssigner(Guid.NewGuid().ToString())));

            var product = productRepository.Get(productId.ToString());

            List <Issue> issues  = new List <Issue>();
            var          issueId = new IssueId();

            issues.Add(product.ReportDefect(issueId, "shit be bad yo", "fo real"));
            issues.Add(product.ReportDefect(new IssueId(), "shit be bad yo", "fo real"));
            issues.Add(product.ReportDefect(new IssueId(), "shit be bad yo", "fo real"));
            issues.Add(product.ReportDefect(new IssueId(), "shit be bad yo", "fo real"));
            issues.Add(product.ReportDefect(new IssueId(), "shit be bad yo", "fo real"));

            DefectStatistics stats1 = new DefectStatistics(issues);

            var release1 = product.ScheduleRelease("new relased", stats1);



            var density = release1.CalculateDefectDensity(new KlocMEasurement(10));

            issues.Add(product.ReportDefect(new IssueId(), "shit be bad yo", "fo real"));
            issues.Add(product.ReportDefect(new IssueId(), "shit be bad yo", "fo real"));

            issues.First().Resolve("cool");

            DefectStatistics stats2 = new DefectStatistics(issues);

            var release2 = product.ScheduleRelease("new relased", stats2);

            var density2 = release2.CalculateDefectDensity(new KlocMEasurement(10));

            var product2 = productRepository.Get(productId.ToString());

            var issueIdForProduct2 = new IssueId();

            issues.Add(product2.ReportDefect(issueIdForProduct2, "shit be bad yo", "fo real"));
            issues.Add(product2.ReportDefect(new IssueId(), "shit be bad yo", "fo real"));
            issues.Add(product2.ReportDefect(new IssueId(), "shit be bad yo", "fo real"));
            issues.Add(product2.ReportDefect(new IssueId(), "shit be bad yo", "fo real"));
            issues.Add(product2.ReportDefect(new IssueId(), "shit be bad yo", "fo real"));

            ProductDefectivenessRanker ranker = new ProductDefectivenessRanker(issues);

            ProductDefectiveness mostDefective = ranker.MostDefectiveProductFrom(tenantId);
        }
コード例 #15
0
        public async Task<HttpResponseMessage> GetFormat(
            TenantId tenantId,
            DocumentHandle handle,
            DocumentFormat format,
            string fname = null
        )
        {
            var mapping = _handleWriter.FindOneById(handle);

            //If mapping is not present return not found
            if (mapping == null || mapping.DocumentDescriptorId == null)
            {
                var deleted = _documentDeletedReader.AllUnsorted.Where(d => d.Handle == handle).ToList();

                if (deleted.Count == 0)
                    return DocumentNotFound(handle);

                return DocumentDeleted(handle, deleted);
            }
               

            var document = _documentDescriptorReader.FindOneById(mapping.DocumentDescriptorId);

            if (document == null)
            {
                return DocumentNotFound(handle);
            }

            var fileName = fname != null ? new FileNameWithExtension(fname) : null;

            if (format == DocumentFormats.Original)
            {
                return StreamFile(
                    document.GetFormatBlobId(format),
                    fileName ?? mapping.FileName
                );
            }

            BlobId formatBlobId = document.GetFormatBlobId(format);
            if (formatBlobId == BlobId.Null)
            {
                return Request.CreateErrorResponse(
                    HttpStatusCode.NotFound,
                    string.Format("Document {0} doesn't have format {1}",
                        handle,
                        format
                    )
                );
            }

            return StreamFile(formatBlobId, fileName);
        }
コード例 #16
0
 internal static partial void DroppingStatesForTenant(ILogger logger, ScopeId scope, ProjectionId projection, TenantId tenant);
コード例 #17
0
 public override int GetHashCode()
 {
     return(TenantId.GetHashCode() ^ EntityId.GetHashCode());
 }
コード例 #18
0
 public UserEntity(TenantId tenant, UserId id)
 {
     PartitionKey = tenant.ToString();
     RowKey       = id.ToString();
 }
コード例 #19
0
 private UserId(TenantId tenantId = null) : base(tenantId)
 {
 }
コード例 #20
0
ファイル: Product.cs プロジェクト: guruvn/SaasOvation
 public void ActivateProduct(TenantId Tenant, ProductId Id, string Name, string Description)
 {
     MustBeActive(Tenant);
     Guard.Against(Queries.IsActive(Tenant, Id), "This product is already active.");
     Changes.ProductActivated(Tenant, Id, Name, Description);
 }
コード例 #21
0
 internal static partial void ReplayingEventsForTenant(ILogger logger, ScopeId scope, ProjectionId projection, TenantId tenant);
コード例 #22
0
        public void Should_Convert_To_Dto()
        {
            var feedstock = Domain.Entities.Feedstock.New("test", StatusEnum.Enable, MeasureId.New(), 2, ColorId.New(), TenantId.New());
            var dto       = FeedstockMapper.Map(feedstock);

            Assert.NotNull(dto);
        }
コード例 #23
0
        public void Should_Convert_To_List_Of_Dto()
        {
            var feedstocks = new Domain.Entities.Feedstock[]
            {
                Domain.Entities.Feedstock.New("test 1", StatusEnum.Enable, MeasureId.New(), 2, ColorId.New(), TenantId.New()),
                Domain.Entities.Feedstock.New("test 2", StatusEnum.Enable, MeasureId.New(), 2, ColorId.New(), TenantId.New())
            };
            var dtos = FeedstockMapper.Map(feedstocks).ToList();

            Assert.NotEmpty(dtos);
            Assert.NotNull(dtos);
        }
コード例 #24
0
        /// <summary>
        /// Handle a <see cref="StreamReadModel" /> and generates job for the queue
        /// if needed.
        /// </summary>
        /// <param name="streamElement"></param>
        /// <param name="tenantId"></param>
        /// <param name="forceReSchedule"></param>
        public QueuedJobId Handle(
            StreamReadModel streamElement,
            TenantId tenantId,
            Boolean forceReSchedule = false)
        {
            if (_info.ShouldCreateJob(streamElement))
            {
                if (!forceReSchedule)
                {
                    //look for already existing job with the same blobid, there is no need to re-queue again
                    //because if a job with the same blobid was already fired for this queue there is no need
                    //to re-issue
                    var existing = _collection.Find(
                        Builders <QueuedJob> .Filter.And(
                            Builders <QueuedJob> .Filter.Eq(j => j.BlobId, streamElement.FormatInfo.BlobId),
                            Builders <QueuedJob> .Filter.Eq(j => j.TenantId, tenantId)
                            )
                        ).Count() > 0;
                    if (existing)
                    {
                        return(null);
                    }
                }
                if (Logger.IsInfoEnabled)
                {
                    Logger.Info($"Queue {_info.Name} CREATE JOB to process {streamElement.Describe()}");
                }

                QueuedJob job = new QueuedJob();
                job.Id = new QueuedJobId(Guid.NewGuid().ToString());
                job.SchedulingTimestamp  = DateTime.Now;
                job.StreamId             = streamElement.Id;
                job.TenantId             = tenantId;
                job.DocumentDescriptorId = streamElement.DocumentDescriptorId;
                job.BlobId     = streamElement.FormatInfo.BlobId;
                job.Handle     = new DocumentHandle(streamElement.Handle);
                job.Parameters = new Dictionary <string, string>();
                job.Parameters.Add(JobKeys.FileExtension, streamElement.Filename.Extension);
                job.Parameters.Add(JobKeys.Format, streamElement.FormatInfo.DocumentFormat);
                job.Parameters.Add(JobKeys.FileName, streamElement.Filename);
                job.Parameters.Add(JobKeys.TenantId, tenantId);
                job.Parameters.Add(JobKeys.MimeType, MimeTypes.GetMimeType(streamElement.Filename));
                job.Parameters.Add(JobKeys.PipelineId, streamElement.FormatInfo?.PipelineId?.ToString());
                if (forceReSchedule)
                {
                    job.Parameters.Add(JobKeys.Force, "true");
                }
                job.HandleCustomData = streamElement.DocumentCustomData;
                if (_info.Parameters != null)
                {
                    foreach (var parameter in _info.Parameters)
                    {
                        job.Parameters.Add(parameter.Key, parameter.Value);
                    }
                }

                _collection.InsertOne(job);

                return(job.Id);
            }
            else
            {
                if (Logger.IsDebugEnabled)
                {
                    Logger.Debug($"Queue {_info.Name} do not need to process {streamElement.Describe()}");
                }
            }
            return(null);
        }
コード例 #25
0
 public TenantCreated(TenantId tenantId, DateTimeOffset createdAt)
 {
     TenantId  = tenantId;
     CreatedAt = createdAt;
 }
コード例 #26
0
 public BookingTenderEvent(TenantId tenantId, BookingId bookingId)
     : base(tenantId, bookingId)
 {
 }
コード例 #27
0
        public HttpResponseMessage DeleteFile(TenantId tenantId, DocumentHandle handle)
        {
            var documentDescritptor = GetDocumentDescriptorByHandle(handle);
            if (documentDescritptor == null)
                return DocumentNotFound(handle);

            CommandBus.Send(new DeleteDocument(handle), "api");

            return Request.CreateResponse(
                HttpStatusCode.Accepted,
                string.Format("Document marked for deletion {0}", handle)
            );
        }
コード例 #28
0
ファイル: BpmnDefinition.cs プロジェクト: chubbyerror/BpmNet
        public bool Equals(BpmnDefinition other)
        {
            // Check for null
            if (ReferenceEquals(other, null))
            {
                return(false);
            }

            // Check for same reference
            if (ReferenceEquals(this, other))
            {
                return(true);
            }

            // Not Check DeploymentId, because generated Guid

            // Check for same value
            return(((DeploymentId == null && other.DeploymentId == null) || (DeploymentId != null && other.DeploymentId != null && DeploymentId.Equals(other.DeploymentId))) &&
                   ((Name == null && other.Name == null) || (Name != null && other.Name != null && Name.Equals(other.Name))) &&
                   ((DefinitionKey == null && other.DefinitionKey == null) || (DefinitionKey != null && other.DefinitionKey != null && DefinitionKey.Equals(other.DefinitionKey))) &&
                   ((ProcessDefinitionDescription == null && other.ProcessDefinitionDescription == null) || (ProcessDefinitionDescription != null && other.ProcessDefinitionDescription != null && ProcessDefinitionDescription.Equals(other.ProcessDefinitionDescription))) &&
                   ((ProcessDefinitionDiagramResourceName == null && other.ProcessDefinitionDiagramResourceName == null) || (ProcessDefinitionDiagramResourceName != null && other.ProcessDefinitionDiagramResourceName != null && ProcessDefinitionDiagramResourceName.Equals(other.ProcessDefinitionDiagramResourceName))) &&
                   (ProcessDefinitionHasStartFormKey.Equals(other.ProcessDefinitionHasStartFormKey)) &&
                   (ProcessDefinitionHasGraphicalNotation.Equals(other.ProcessDefinitionHasGraphicalNotation)) &&
                   (IsSuspended.Equals(other.IsSuspended)) &&
                   ((TenantId == null && other.TenantId == null) || (TenantId != null && other.TenantId != null && TenantId.Equals(other.TenantId))));
        }
コード例 #29
0
 public async Task<HttpResponseMessage> Upload(TenantId tenantId, DocumentHandle handle)
 {
     return await InnerUploadDocument(tenantId, handle, null, null);
 }
コード例 #30
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="tenantId"></param>
        /// <param name="handle"></param>
        /// <param name="fatherHandle">Different from null only when you want to upload
        /// a document that is an attachment of another document</param>
        /// <param name="fatherHandleDescriptorId">Descriptor id that contains reference
        /// to <paramref name="fatherHandle"/></param>
        /// <returns></returns>
        private async Task<HttpResponseMessage> InnerUploadDocument(
            TenantId tenantId,
            DocumentHandle handle,
            DocumentHandle fatherHandle,
            DocumentDescriptorId fatherHandleDescriptorId)
        {
            var documentId = _identityGenerator.New<DocumentDescriptorId>();

            Logger.DebugFormat("Incoming file {0}, assigned {1}", handle, documentId);
            var errorMessage = await UploadFromHttpContent(Request.Content);
            Logger.DebugFormat("File {0} processed with message {1}", _blobId, errorMessage ?? "OK");

            if (errorMessage != null)
            {
                return Request.CreateErrorResponse(
                    HttpStatusCode.BadRequest,
                    errorMessage
                );
            }

            CreateDocument(documentId, _blobId, handle, fatherHandle, fatherHandleDescriptorId, _fileName, _customData);

            Logger.DebugFormat("File {0} uploaded as {1}", _blobId, documentId);

            var storedFile = _blobStore.GetDescriptor(_blobId);

            return Request.CreateResponse(
                HttpStatusCode.OK,
                new UploadedDocumentResponse
                {
                    Handle = handle,
                    Hash = storedFile.Hash,
                    HashType = "md5",
                    Uri = Url.Content("/" + tenantId + "/documents/" + handle)
                }
            );
        }
コード例 #31
0
 internal static partial void PersistingProjectionDefinition(ILogger logger, ScopeId scope, ProjectionId projection, TenantId tenant);
コード例 #32
0
        public async Task<HttpResponseMessage> AddFormatToDocument(TenantId tenantId, DocumentFormat format)
        {
            var errorMessage = await AddFormatFromHttpContent(Request.Content, format);
            Logger.DebugFormat("File {0} processed with message {1}", _blobId, errorMessage);

            if (errorMessage != null)
            {
                Logger.Error("Error Adding format To Document: " + errorMessage);
                return Request.CreateErrorResponse(
                    HttpStatusCode.BadRequest,
                    errorMessage
                );
            }

            String queueName = _customData[AddFormatToDocumentParameters.QueueName] as String;
            String jobId = _customData[AddFormatToDocumentParameters.JobId] as String;
            DocumentDescriptorId documentId;
            if (String.IsNullOrEmpty(queueName))
            {
                //user ask for handle, we need to grab the handle
                var documentHandle = new DocumentHandle(_customData[AddFormatToDocumentParameters.DocumentHandle] as String);
                var handle = _handleWriter.FindOneById(documentHandle);
                documentId = handle.DocumentDescriptorId;
                if (documentId == null)
                {
                    Logger.ErrorFormat("Trying to add a format for Handle {0} with a null DocumentId", documentHandle);
                    return Request.CreateErrorResponse(
                       HttpStatusCode.BadRequest,
                       ""
                   );
                }
                Logger.DebugFormat("Add format {0} to handle {1} and document id {2}", format, handle, documentId);
            }
            else
            {
                var job = _queueDispatcher.GetJob(queueName, jobId);

                if (job == null)
                {
                    Logger.WarnFormat("Job id {0} not found in queue {1}", jobId, queueName);
                    return Request.CreateErrorResponse(
                        HttpStatusCode.BadRequest,
                        String.Format("Job id {0} not found in queue {1}", jobId, queueName));
                }
                documentId = job.DocumentDescriptorId;
                if (documentId == null)
                {
                    Logger.ErrorFormat("Trying to add a format for Job Id {0} queue {1} - Job has DocumentDescriptorId null", jobId, queueName);
                    return Request.CreateErrorResponse(
                       HttpStatusCode.BadRequest,
                       ""
                   );
                }
                //need to check if the descriptor is deleted
                var exists = _documentDescriptorReader
                    .AllUnsorted
                    .Where(d => d.Id == documentId)
                    .Any();
                if (!exists)
                {
                    Logger.ErrorFormat("Trying to add a format for Job Id {0} queue {1} - DocumentDescriptor does not exists or was deleted!", jobId, queueName);
                    return Request.CreateErrorResponse(
                       HttpStatusCode.BadRequest,
                       ""
                   );
                }
                Logger.DebugFormat("Add format {0} to job id {1} and document id {2}", format, job.Id, documentId);
            }

            if (format == "null")
            {
                var formatFromFileName = _documentFormatTranslator.GetFormatFromFileName(_fileName);
                if (formatFromFileName == null)
                {
                    String error = "Format not specified and no known format for file: " + _fileName;
                    Logger.Error(error);
                    return Request.CreateErrorResponse(
                        HttpStatusCode.BadRequest,
                        error
                    );
                }
                format = new DocumentFormat(formatFromFileName);
            }

            var createdById = new PipelineId(_customData[AddFormatToDocumentParameters.CreatedBy] as String);
            Logger.DebugFormat("Incoming new format for documentId {0}", documentId);

            var command = new AddFormatToDocumentDescriptor(documentId, format, _blobId, createdById);
            CommandBus.Send(command, "api");

            return Request.CreateResponse(
                HttpStatusCode.OK,
                new AddFormatToDocumentResponse
                {
                    Result = true,
                }
            );
        }
コード例 #33
0
 private UserId(Guid guid, TenantId tenantId = null) : base(guid, tenantId)
 {
 }
コード例 #34
0
 internal static partial void ResettingStreamProcessorForTenant(ILogger logger, ScopeId scope, ProjectionId projection, TenantId tenant);
コード例 #35
0
 public ProductOwnerId(TenantId tenantId, string id)
     : base(tenantId + ":" + id)
 {
 }
コード例 #36
0
 internal static partial void ResettingProjection(ILogger logger, ScopeId scope, ProjectionId projection, TenantId tenant, FailedProjectionDefinitionComparisonReason reason);
コード例 #37
0
        public HttpResponseMessage GetCustomData(TenantId tenantId, DocumentHandle handle)
        {
            var data = _handleWriter.FindOneById(handle);
            if (data == null)
                return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Document not found");

            return Request.CreateResponse(HttpStatusCode.OK, data.CustomData);
        }
コード例 #38
0
 public StreamSubscriptionActor(ScopeId scope, TenantId tenantId, ILogger <StreamSubscriptionActor> logger)
 {
     _scope    = scope;
     _tenantId = tenantId;
     _logger   = logger;
 }
コード例 #39
0
        public async Task<HttpResponseMessage> GetFormatList(
            TenantId tenantId,
            DocumentHandle handle
        )
        {
            var documentDescriptor = GetDocumentDescriptorByHandle(handle);

            if (documentDescriptor == null)
            {
                return DocumentNotFound(handle);
            }

            var formats = documentDescriptor.Formats.ToDictionary(x =>
                (string)x.Key,
                x => Url.Content("/" + tenantId + "/documents/" + handle + "/" + x.Key)
            );
            return Request.CreateResponse(HttpStatusCode.OK, formats);
        }
コード例 #40
0
        public async Task<HttpResponseMessage> GetAttachmentFat(
            TenantId tenantId,
            DocumentHandle handle
        )
        {
            var documentDescriptor = _documentDescriptorReader.AllUnsorted.SingleOrDefault(d =>
                  d.Documents.Contains(handle));

            if (documentDescriptor == null)
            {
                return DocumentNotFound(handle);
            }

            List<DocumentAttachmentsFat.AttachmentInfo> fat = new List<DocumentAttachmentsFat.AttachmentInfo>();
            if (documentDescriptor.Attachments != null && documentDescriptor.Attachments.Count > 0)
            {
                ScanAttachments(
                    tenantId,
                    documentDescriptor.Attachments,
                    fat,
                    "",
                    0,
                    5);
            }

            return Request.CreateResponse(HttpStatusCode.OK, fat);
        }
コード例 #41
0
ファイル: Product.cs プロジェクト: guruvn/SaasOvation
 public void RequestFeature(TenantId Tenant, ProductId Product, IssueId Id, string Name, string Description, IssueAssignerId Assigner)
 {
     MustBeActive(Tenant, Product);
     MustBeActive(Tenant, assigner: Assigner);
     Changes.IssueRegistered(Tenant, Product, Id, Name, Description, IssueType.Feature, Assigner);
 }
コード例 #42
0
 public TenantProjections(TenantId tenantId, IProjection[] allProjections)
 {
     _tenantId       = tenantId;
     _allProjections = allProjections;
 }
コード例 #43
0
        public async Task<HttpResponseMessage> UploadAttachFromJob(
            TenantId tenantId,
            String queueName,
            String jobId,
            String attachSource)
        {
            var job = _queueDispatcher.GetJob(queueName, jobId);
            if (job == null)
            {
                return Request.CreateErrorResponse(
                    HttpStatusCode.BadRequest,
                    String.Format("Job id {0} not valid for queue {1}", jobId, queueName)
                );
            }
            var realAttacHandle = GetAttachHandleFromAttachSource(attachSource);

            var fatherDescriptor = _documentDescriptorReader.AllUnsorted.SingleOrDefault(dd =>
                  dd.Documents.Contains(job.Handle));
            if (fatherDescriptor == null)
            {
                return Request.CreateErrorResponse(
                    HttpStatusCode.NotFound,
                    string.Format("Handle {0} referenced from job {1} has no descriptor", job.Handle, job.Id)
                );
            }
            return await InnerUploadDocument(tenantId, realAttacHandle, job.Handle, fatherDescriptor.Id);
        }
コード例 #44
0
ファイル: Product.cs プロジェクト: guruvn/SaasOvation
 public void ReportDefect(TenantId Tenant, ProductId Product, IssueId Id, string Name, string Description, IssueAssignerId Assigner)
 {
     MustBeActive(Tenant, Product);
     Changes.IssueRegistered(Tenant, Product, Id, Name, Description, IssueType.Defect, Assigner);
 }
コード例 #45
0
        public async Task<HttpResponseMessage> CopyDocument(
            TenantId tenantId, DocumentHandle originalHandle, DocumentHandle copiedHandle)
        {
            var documentDescriptor = GetDocumentDescriptorByHandle(originalHandle);
            if (documentDescriptor == null)
                return DocumentNotFound(originalHandle);

            documentDescriptor = GetDocumentDescriptorByHandle(copiedHandle);
            if (documentDescriptor != null)
                return Request.CreateErrorResponse(
                   HttpStatusCode.InternalServerError,
                   string.Format("Handle {0} already existing", copiedHandle)
               );

            CommandBus.Send(new CopyDocument(originalHandle, copiedHandle), "api");

            return Request.CreateResponse(
                HttpStatusCode.OK,
                string.Format("Handle {0} copied into handle {1}", originalHandle, copiedHandle)
            );
        }
コード例 #46
0
ファイル: Product.cs プロジェクト: guruvn/SaasOvation
 public void CloseIssue(TenantId Tenant, ProductId Product, IssueId Id)
 {
     MustBeActive(Tenant, Product, Id);
     Changes.IssueClosed(Tenant, Product, Id);
 }
コード例 #47
0
        public async Task<HttpResponseMessage> DeleteFormatFromDocument(
            TenantId tenantId,
            DocumentHandle handle,
            DocumentFormat format)
        {
            var documentDescriptor = GetDocumentDescriptorByHandle(handle);
            if (documentDescriptor == null)
                return DocumentNotFound(handle);

            CommandBus.Send(new DeleteFormatFromDocumentDescriptor(documentDescriptor.Id, format), "api");

            return Request.CreateResponse(
                HttpStatusCode.Accepted,
                string.Format("Format {0} marked for deletion for handle {0}", format, handle)
            );
        }
コード例 #48
0
 /// <summary>
 /// Initializes a new instance of the <see cref="TenantOffset"/> class.
 /// </summary>
 /// <param name="tenant">The tenant.</param>
 /// <param name="offset">The offset.</param>
 public TenantOffset(TenantId tenant, ulong offset)
 {
     Tenant = tenant;
     Offset = offset;
 }
コード例 #49
0
 public HttpResponseMessage GetFileName(TenantId tenantId, DocumentHandle handle)
 {
     var data = _handleWriter.FindOneById(handle);
     if (data == null)
         return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Document not found");
     var name = data.FileName != null ? data.FileName.FileName : "";
     return Request.CreateResponse(HttpStatusCode.OK, new { FileName = name });
 }
コード例 #50
0
    IEnumerable <TenantScopedStreamProcessorStatus> CreateScopedStreamProcessorStatus(EventHandlerInfo info, TenantId tenant = null)
    {
        var state = _eventHandlers.CurrentStateFor(info.Id);

        if (!state.Success)
        {
            throw state.Exception;
        }

        return(tenant == null
            ? _streamProcessorStatusConverter.Convert(state.Result)
            : _streamProcessorStatusConverter.ConvertForTenant(state.Result, tenant));
    }
コード例 #51
0
        public async Task<HttpResponseMessage> GetAttachmentList(
            TenantId tenantId,
            DocumentHandle handle
        )
        {
            var documentDescriptor = _documentDescriptorReader.AllUnsorted.SingleOrDefault(d =>
                  d.Documents.Contains(handle));

            if (documentDescriptor == null)
            {
                return DocumentNotFound(handle);
            }

            if (documentDescriptor.Attachments == null || documentDescriptor.Attachments.Count == 0)
                return Request.CreateResponse(HttpStatusCode.OK, new List<ClientAttachmentInfo>());

            var attachments = documentDescriptor.Attachments
                .Select(a =>
                {
                    var attachment = new ClientAttachmentInfo()
                    {
                        Handle = Url.Content("/" + tenantId + "/documents/" + a.Handle),
                        RelativePath = a.RelativePath
                    };
                    var hasAttachment = _documentDescriptorReader.AllUnsorted.Any(d =>
                        d.Documents.Contains(a.Handle) &&
                        d.Attachments.Count > 0);
                    attachment.HasAttachments = hasAttachment;
                    return attachment;
                })
                .ToList();

            return Request.CreateResponse(HttpStatusCode.OK, attachments);
        }
コード例 #52
0
 public UserDescriptor(TenantId tenantId, string username, string emailAddress)
 {
     this.EmailAddress = emailAddress;
     this.TenantId     = tenantId;
     this.Username     = username;
 }
コード例 #53
0
        private void ScanAttachments(
            TenantId tenantId,
            IEnumerable<DocumentAttachmentReadModel> attachments,
            List<DocumentAttachmentsFat.AttachmentInfo> fat,
            String rootAttachmentPath,
            Int32 actualDeepLevel,
            Int32 maxLevel)
        {
            //grab in a single query all documents and descriptors for this data
            foreach (var attach in attachments)
            {
                //grab all data for this attachment
                var descriptor = _documentDescriptorReader.AllUnsorted
                    .Single(d => d.Documents.Contains(attach.Handle));
                var document = _handleWriter.FindOneById(attach.Handle);

                fat.Add(new DocumentAttachmentsFat.AttachmentInfo(
                        Url.Content("/" + tenantId + "/documents/" + attach.Handle),
                        document.FileName,
                        attach.RelativePath,
                        rootAttachmentPath
                    ));
                var newRootAttachmentPath = rootAttachmentPath + "/" + document.FileName;

                //we need to further scan attachment.
                if (actualDeepLevel < maxLevel &&
                    descriptor.Attachments != null &&
                    descriptor.Attachments.Count > 0)
                {
                    ScanAttachments(tenantId, descriptor.Attachments, fat, newRootAttachmentPath, actualDeepLevel + 1, maxLevel);
                }
            }
        }
コード例 #54
0
 public TenantClosed(TenantId tenantId, DateTimeOffset closedAt)
 {
     TenantId = tenantId;
     ClosedAt = closedAt;
 }
コード例 #55
0
        public async Task<HttpResponseMessage> GetBlobForJob(
            TenantId tenantId,
            String queueName,
            String jobId
        )
        {
            var job = _queueDispatcher.GetJob(queueName, jobId);
            if (job == null)
                return Request.CreateErrorResponse(
                    HttpStatusCode.NotFound,
                    string.Format("Job {0} not found", jobId)
                    ); ;

            return StreamFile(job.BlobId);
        }
コード例 #56
0
        public ListFeedstockQueryHandlerTest()
        {
            var repository = new Mock <IFeedstockRepository>();

            repository.Setup(x => x.ListAsync(It.IsAny <Expression <Func <Domain.Entities.Feedstock, bool> > >(),
                                              It.IsAny <string>(), It.IsAny <int>(), It.IsAny <int>()))
            .ReturnsAsync((Expression <Func <Domain.Entities.Feedstock, bool> > filter,
                           string orderBy, int page, int qtyPerPage) =>
            {
                var func  = filter.Compile();
                var value = func.Invoke(Domain.Entities.Feedstock.New("test", StatusEnum.Disable, MeasureId.New(), 1, ColorId.New(), TenantId.New()));

                if (value)
                {
                    return(Pagination <Domain.Entities.Feedstock> .Empty);
                }
                else
                {
                    return(Pagination <Domain.Entities.Feedstock> .New(new Domain.Entities.Feedstock[]
                    {
                        Domain.Entities.Feedstock.New("test 1", StatusEnum.Disable, MeasureId.New(), 1, ColorId.New(), TenantId.New())
                    }, 1, 1, 1));
                }
            });

            _feedstockRepository = repository.Object;
        }
コード例 #57
0
        public async Task<HttpResponseMessage> GetHandleInfo(
            TenantId tenantId, 
            DocumentHandle handle)
        {
            var handleString = handle.ToString();
            var regex = "/" + handleString.Replace("/", "//") + "/";
            var descriptors = _documentDescriptorReader.Collection
                .Find(Builders<DocumentDescriptorReadModel>.Filter.Regex("Documents", new MongoDB.Bson.BsonRegularExpression(regex)))
                .Limit(20);

            var retValue = new List<DocumentInfo>();
            foreach (var d in descriptors.ToEnumerable())
            {
                var documentHandle = d.Documents.FirstOrDefault(dd => dd.ToString().Contains(handleString));
                var di = new DocumentInfo()
                {
                    DocumentHandle = documentHandle,
                    Formats = d.Formats.Select(f => new DocumentFormatInfo()
                    {
                        FormatType = f.Key,
                        FormatUrl = Url.Content("/" + tenantId + "/documents/" + documentHandle + "/" + f.Key)
                    }).ToList()
                };
                retValue.Add(di);
            }

            return Request.CreateResponse(HttpStatusCode.OK, retValue);
        }
コード例 #58
0
ファイル: MailBox.cs プロジェクト: yulifengwx/CommunityServer
 public override int GetHashCode()
 {
     return((TenantId.GetHashCode() + UserId.GetHashCode()) ^ EMail.Address.ToLowerInvariant().GetHashCode());
 }
コード例 #59
0
 public void verify_job_filter_by_tenant_id()
 {
     var none = new TenantId("tenant_none");
     var foo = new TenantId("tenant_foo");
     var bar = new TenantId("tenant_bar");
     QueueHandler sut = CreateAGenericJob(new QueueInfo("test", "tika", ""), tenant: foo);
     HandleStreamToCreateJob(sut, bar);
     var nextJob = sut.GetNextJob("identity", "handle",none , null);
     Assert.That(nextJob, Is.Null);
     nextJob = sut.GetNextJob("identity", "handle", bar, null);
     Assert.That(nextJob.TenantId, Is.EqualTo(bar));
     nextJob = sut.GetNextJob("identity", "handle", foo, null);
     Assert.That(nextJob.TenantId, Is.EqualTo(foo));
 }
 /// <summary>
 /// Instantiates an instance of <see cref="MissingResourceConfigurationForResourceTypeForTenant"/>
 /// </summary>
 /// <param name="tenantId">The <see cref="TenantId"/> the configuration is missing for</param>
 /// <param name="resourceType">The <see cref="ResourceType"/> that's missing</param>
 public MissingResourceConfigurationForResourceTypeForTenant(TenantId tenantId, ResourceType resourceType)
     : base($"Missing resource configuration for resource typeof {resourceType} for tenant with Id '{tenantId}'")
 {
 }