public async Task <MappingContent> GetMapping(string templateName, string templateVersion, string mappingName, string mappingVersion)
        {
            if (string.IsNullOrEmpty(templateName))
            {
                throw new ArgumentNullException(nameof(templateName));
            }
            if (string.IsNullOrEmpty(mappingName))
            {
                throw new ArgumentNullException(nameof(mappingName));
            }

            if (string.IsNullOrEmpty(mappingVersion))
            {
                return(GetLatestMapping(templateName, templateVersion, mappingName));
            }
            else
            {
                if (string.IsNullOrEmpty(templateVersion))
                {
                    templateVersion = await GetLatestTemplateVersion(templateName);
                }
                var prefix          = $"{templateName}_{templateVersion}_{mappingName}";
                var containerClient = GetMappingsContainer();
                var blobItem        = containerClient
                                      .GetBlobs(BlobTraits.Metadata, BlobStates.Snapshots, prefix)
                                      .FirstOrDefault(o => o.Metadata[MAPPING_VERSION_KEY] == mappingVersion);
                if (blobItem == null)
                {
                    return(null);
                }
                var blobClient = containerClient.GetBlobClient(blobItem.Name);
                var contents   = DownloadContentItem(blobClient, blobItem);
                return(ContentItemFactory.BuildMapping(blobClient.Uri, blobItem, contents));
            }
        }
        public IEnumerable <MappingContentSummary> GetMappings(string templateName, string templateVersion, string mappingName = null)
        {
            if (string.IsNullOrEmpty(templateName))
            {
                throw new ArgumentNullException(nameof(templateName));
            }

            var prefix = templateName;

            if (!string.IsNullOrEmpty(templateVersion))
            {
                prefix += "_" + templateVersion;
                if (!string.IsNullOrEmpty(mappingName))
                {
                    prefix += "_" + mappingName;
                }
            }
            var containerClient = GetMappingsContainer();
            var blobs           = containerClient.GetBlobs(BlobTraits.Metadata, BlobStates.None, prefix);
            var items           = blobs
                                  .Select(o => ContentItemFactory.BuildMappingSummary($"{containerClient.Uri}/{o.Name}", o));

            if (string.IsNullOrEmpty(templateVersion) && !string.IsNullOrEmpty(mappingName))
            {
                items = items.Where(o => o.Name.EndsWith(mappingName));
            }
            return(items);
        }
        /// <summary>
        /// The <see cref="CreateTemplate(string, Stream)"/> operation creates a new template.
        /// If the template with the same name already exists, the operation creates a new version.
        /// </summary>
        /// <param name="templateName">The name of template to create.</param>
        /// <param name="contents">The <see cref="Stream"/> that contains a valid Word document.</param>
        /// <returns>A <see cref="ContentItem"/> describing the state of the created template.</returns>
        /// <remarks>
        /// An <see cref="ArgumentNullException"/> will be thrown if templateName or contents are null or empty.
        /// A <see cref="RequestFailedException"/> will be thrown if a failure occurs.
        /// </remarks>
        public async Task <TemplateContent> CreateTemplate(string templateName, Stream contents)
        {
            if (string.IsNullOrEmpty(templateName))
            {
                throw new ArgumentNullException(nameof(templateName));
            }
            if (contents == null || contents.Length == 0)
            {
                throw new ArgumentNullException(nameof(contents));
            }

            var containerClient = GetTemplatesContainer();
            var blobFileName    = $"{templateName}.docx";
            var blobClient      = containerClient.GetBlobClient(blobFileName);

            var templateVersion = await TryCreateSnapshot(blobClient, TEMPLATE_VERSION_KEY);

            var metadata = new Dictionary <string, string>
            {
                [TEMPLATE_NAME_KEY]    = templateName,
                [TEMPLATE_VERSION_KEY] = templateVersion
            };

            var response = await blobClient.UploadAsync(contents, metadata : metadata);

            var blobContentInfo = response.Value;

            return(ContentItemFactory.BuildTemplate(blobClient.Uri, blobContentInfo, metadata, contents));
        }
 public TemplateContent GetTemplate(string templateName, string templateVersion = null)
 {
     if (string.IsNullOrEmpty(templateName))
     {
         throw new ArgumentNullException(nameof(templateName));
     }
     if (string.IsNullOrEmpty(templateVersion))
     {
         return(GetLatestTemplate(templateName));
     }
     else
     {
         var containerClient = GetTemplatesContainer();
         var blobItem        = containerClient
                               .GetBlobs(BlobTraits.Metadata, BlobStates.Snapshots, templateName)
                               .FirstOrDefault(o => o.Metadata[TEMPLATE_VERSION_KEY] == templateVersion);
         if (blobItem == null)
         {
             return(null);
         }
         var blobClient = containerClient.GetBlobClient(blobItem.Name);
         var contents   = DownloadContentItem(blobClient, blobItem);
         return(ContentItemFactory.BuildTemplate(blobClient.Uri, blobItem, contents));
     }
 }
        public IEnumerable <TemplateContentSummary> GetTemplateVersions(string templateName)
        {
            var containerClient = GetTemplatesContainer();

            return(containerClient.GetBlobs(BlobTraits.Metadata, BlobStates.Snapshots, templateName)
                   .Select(o => ContentItemFactory.BuildTemplateSummary($"{containerClient.Uri}/{o.Name}", o))
                   .ToList());
        }
        public IEnumerable <TemplateContentSummary> GetTemplates()
        {
            var containerClient = GetTemplatesContainer();
            var blobs           = containerClient.GetBlobs(BlobTraits.Metadata);

            return(blobs
                   .Select(o => ContentItemFactory.BuildTemplateSummary($"{containerClient.Uri}/{o.Name}", o))
                   .ToList());
        }
        /// <summary>
        /// The <see cref="CreateDocument(string, string, Stream)"/> operation creates a new document.
        /// The new document gets a unique name.
        /// </summary>
        /// <param name="templateName">The name of the template used for this document.</param>
        /// <param name="mappingName">The name of the mapping used to transform input.</param>
        /// <param name="contents">The <see cref="Stream"/> that contains a valid Word document.</param>
        /// <returns>A <see cref="ContentItem"/> describing the state of the created document.</returns>
        /// <remarks>
        /// An <see cref="ArgumentNullException"/> will be thrown if any of the parameters are null or empty.
        /// A <see cref="RequestFailedException"/> will be thrown if a failure occurs.
        /// </remarks>
        public async Task <DocumentContent> CreateDocument(string templateName, string mappingName, Stream contents)
        {
            // Check
            if (string.IsNullOrEmpty(templateName))
            {
                throw new ArgumentNullException(nameof(templateName));
            }
            if (string.IsNullOrEmpty(mappingName))
            {
                throw new ArgumentNullException(nameof(mappingName));
            }
            if (contents == null || contents.Length <= 0)
            {
                throw new ArgumentNullException(nameof(contents));
            }

            var templateVersion = await GetLatestTemplateVersion(templateName);

            if (templateVersion == null)
            {
                throw new ArgumentException($"Template {templateName} not found.");
            }
            var mappingVersion = await GetLatestMappingVersion($"{templateName}_{templateVersion}_{mappingName}");

            if (mappingVersion == null)
            {
                throw new ArgumentException($"Mapping {mappingName} not found.");
            }

            var documentId      = DateTime.Now.Ticks.ToString();
            var containerClient = GetDocumentsContainer();
            //var name = $"{templateName}_{templateVersion}_{mappingName}_{mappingVersion}_{documentId}";
            var blobFileName = $"{documentId}.docx";
            var blobClient   = containerClient.GetBlobClient(blobFileName);

            var metadata = new Dictionary <string, string>
            {
                [TEMPLATE_NAME_KEY]    = templateName,
                [TEMPLATE_VERSION_KEY] = templateVersion,
                [MAPPING_NAME_KEY]     = mappingName,
                [MAPPING_VERSION_KEY]  = mappingVersion,
                [DOCUMENT_ID]          = documentId
            };

            var response = await blobClient.UploadAsync(contents, metadata : metadata);

            var blobContentInfo = response.Value;

            return(ContentItemFactory.BuildDocument(blobClient.Uri, blobContentInfo, metadata, contents));
        }
        /// <summary>
        /// The <see cref="CreateMapping(string, string, Stream)"/> operation creates a new mapping.
        /// If the mapping with the same name already exists, the operation creates a new version.
        /// </summary>
        /// <param name="templateName">The name of the parent template.</param>
        /// <param name="mappingName">The name of mapping to create.</param>
        /// <param name="contents">The <see cref="Stream"/> that contains a valid Excel document.</param>
        /// <returns>A <see cref="ContentItem"/> describing the state of the created mapping.</returns>
        /// <remarks>
        /// An <see cref="ArgumentNullException"/> will be thrown if any of the parameters are null or empty.
        /// A <see cref="RequestFailedException"/> will be thrown if a failure occurs.
        /// </remarks>
        public async Task <MappingContent> CreateMapping(string templateName, string mappingName, Stream contents)
        {
            if (string.IsNullOrEmpty(templateName))
            {
                throw new ArgumentNullException(nameof(templateName));
            }
            if (string.IsNullOrEmpty(mappingName))
            {
                throw new ArgumentNullException(nameof(mappingName));
            }
            if (contents == null || contents.Length == 0)
            {
                throw new ArgumentNullException(nameof(contents));
            }

            var templateVersion = await GetLatestTemplateVersion(templateName);

            if (templateVersion == null)
            {
                throw new ArgumentException(nameof(templateName));
            }

            var containerClient = GetMappingsContainer();
            var blobFileName    = $"{templateName}_{templateVersion}_{mappingName}.xlsm";
            var blobClient      = containerClient.GetBlobClient(blobFileName);

            var mappingVersion = await TryCreateSnapshot(blobClient, MAPPING_VERSION_KEY);

            var metadata = new Dictionary <string, string>
            {
                [TEMPLATE_NAME_KEY]    = templateName,
                [TEMPLATE_VERSION_KEY] = templateVersion,
                [MAPPING_NAME_KEY]     = mappingName,
                [MAPPING_VERSION_KEY]  = mappingVersion
            };

            var response = await blobClient.UploadAsync(contents, metadata : metadata);

            var blobContentInfo = response.Value;

            return(ContentItemFactory.BuildMapping(blobClient.Uri, blobContentInfo, metadata, contents));
        }
        public MappingContent GetLatestMapping(string templateName, string templateVersion, string mappingName)
        {
            if (string.IsNullOrEmpty(templateName))
            {
                throw new ArgumentNullException(nameof(templateName));
            }

            if (string.IsNullOrEmpty(templateVersion))
            {
                templateVersion = GetLatestTemplateVersion(templateName).GetAwaiter().GetResult();
            }
            if (string.IsNullOrEmpty(templateVersion))
            {
                throw new ArgumentNullException(nameof(templateVersion));
            }

            if (string.IsNullOrEmpty(mappingName))
            {
                throw new ArgumentNullException(nameof(mappingName));
            }
            var mappingVersionName = $"{templateName}_{templateVersion}_{mappingName}";

            try
            {
                var containerClient  = GetMappingsContainer();
                var blobFileName     = $"{mappingVersionName}.xlsm";
                var blobClient       = containerClient.GetBlobClient(blobFileName);
                var blobDownloadInfo = DownloadContentItem(blobClient);
                return(ContentItemFactory.BuildMapping(blobClient.Uri, blobDownloadInfo));
            }
            catch (RequestFailedException ex)
            {
                if (ex.Status != 404)
                {
                    throw ex;
                }
            }
            return(null);
        }
        public IEnumerable <ContentItemStats> GetMappingStats(string mappingName = null)
        {
            var documentsContainerClient = GetDocumentsContainer();
            var allDocuments             = documentsContainerClient
                                           .GetBlobs(BlobTraits.Metadata, BlobStates.None, null)
                                           .Select(o => ContentItemFactory.BuildDocumentSummary($"{documentsContainerClient.Uri}/{o.Name}", o));

            var mappingContainerClient = GetMappingsContainer();
            var allMappings            = mappingContainerClient
                                         .GetBlobs(BlobTraits.Metadata, BlobStates.None, null)
                                         .Select(o => ContentItemFactory.BuildMappingSummary($"{mappingContainerClient.Uri}/{o.Name}", o));

            if (string.IsNullOrEmpty(mappingName))
            {
                return(allMappings
                       .GroupBy(o => o.MappingName)
                       .Select(g => new ContentItemStats()
                {
                    MappingName = g.Key,
                    TemplateName = null,
                    Templates = g.Select(o => o.TemplateName).Distinct().Count(),
                    Documents = allDocuments.Count(d => d.MappingName == g.Key)
                }));
            }
            else
            {
                return(allMappings
                       .Where(o => string.Equals(mappingName, o.MappingName, StringComparison.CurrentCultureIgnoreCase))
                       .GroupBy(o => o.TemplateName)
                       .Select(g => new ContentItemStats()
                {
                    MappingName = mappingName,
                    TemplateName = g.Key,
                    Templates = 1,
                    Documents = allDocuments.Count(d => d.MappingName == mappingName && d.TemplateName == g.Key)
                }));
            }
        }
 public TemplateContent GetLatestTemplate(string templateName)
 {
     if (string.IsNullOrEmpty(templateName))
     {
         throw new ArgumentNullException(nameof(templateName));
     }
     try
     {
         var containerClient  = GetTemplatesContainer();
         var blobFileName     = $"{templateName}.docx";
         var blobClient       = containerClient.GetBlobClient(blobFileName);
         var blobDownloadInfo = DownloadContentItem(blobClient);
         return(ContentItemFactory.BuildTemplate(blobClient.Uri, blobDownloadInfo));
     }
     catch (RequestFailedException ex)
     {
         if (ex.Status != 404)
         {
             throw ex;
         }
     }
     return(null);
 }