Source

main / Source / WebClient / Web.BizLogic / Services / RepositoryService.cs

Full commit
Naethra D 3ee1b94 

































































































































































































































































































using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using System.Text;
using DataUp.Web.DataLayer;
using System.IO;
using DocumentFormat.OpenXml.Packaging;
using System.Net;
using DataUp.Web.Common;
using DataUp.Web.Service.Model;
using System.Collections.Specialized;
using System.Security.Cryptography.X509Certificates;
using System.Net.Security;

namespace DataUp.Web.BizLogic
{
    public class RepositoryService : IRepositoryService
    {
        DataUpClient.RepositoryDataContext service;
        private IDocumentStoreRepository documentStoreRepository;
        private IBlobDataRepository blobDataRepository;

        public RepositoryService(IDocumentStoreRepository documentStoreRepository, IBlobDataRepository blobDataRepository)
        {
            ServicePointManager.ServerCertificateValidationCallback = delegate(object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return true; };

            service = new DataUpClient.RepositoryDataContext(new Uri(Constants.DataUpWebServiceLink));
            this.documentStoreRepository = documentStoreRepository;
            this.blobDataRepository = blobDataRepository;
        }

        public IEnumerable<RepositoryDetail> RetrieveRespositories()
        {
            IEnumerable<RepositoryDetail> repositories;
            try
            {
                // Get details from OData Service.
                repositories = (from val in service.Repositories
                                select new RepositoryDetail
                                {
                                    RepositoryId = val.RepositoryId,
                                    RepositoryName = val.RepositoryName,
                                    PostFileLink = val.PostFileLink,
                                    IdentifierLink = val.IdentifierLink,
                                    IsPasswordRequired = val.IsPasswordRequired,
                                    Type = val.Type
                                });
            }
            catch (Exception ex)
            {
                throw new Exception("Error while getting repositories: " + ex.Message, ex);
            }

            return repositories;
        }

        public string GetIdentifier(IdentifierDetail details)
        {
            string identifier = string.Empty;
            try
            {
                DQueryData queryData = GetIdentifierQueryData(details);

                DRepositoryBase repositoryBase = new DRepositoryBase()
                {
                    RepositoryName = details.RepositoryName,
                    Authorization = details.Authorization
                };

                string queryDataString = queryData.SerializeObject<DQueryData>("queryData");
                string repositoryDataString = repositoryBase.SerializeObject<DRepositoryBase>("repositoryModel");

                using (WebClient client = new WebClient())
                {
                    NameValueCollection values = new NameValueCollection();
                    values.Add("QueryData", queryDataString.EncodeTo64());
                    values.Add("RepositoryModel", repositoryDataString.EncodeTo64());
                    byte[] response = client.UploadValues(new Uri(Constants.DataUpWebServiceLink + "/GetIdentifier"), "POST", values);

                    string responseString = Encoding.UTF8.GetString(response);

                    if (!string.IsNullOrWhiteSpace(responseString))
                    {
                        var getIdentifierElement = XElement.Parse(responseString);
                        identifier = getIdentifierElement.Value;
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception("An error while getting identifier from repository.", ex);
            }

            return identifier;
        }

        public string GetUserAgreement(string repositoryName)
        {
            string agreement = string.Empty;
            try
            {
                using (WebClient client = new WebClient())
                {
                    NameValueCollection values = new NameValueCollection();
                    values.Add("RepositoryName", repositoryName);

                    byte[] response = client.UploadValues(new Uri(Constants.DataUpWebServiceLink + "/GetUserAgreement"), "POST", values);

                    string responseString = Encoding.UTF8.GetString(response);

                    if (!string.IsNullOrWhiteSpace(responseString))
                    {
                        var getResponse = XElement.Parse(responseString);
                        agreement = getResponse.Value;
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception("An error while getting User agreement from repository.", ex);
            }

            return agreement;
        }

        public string PublishFile(PostFileDetail details, MetadataDetailList metadataList, DataDetail updatedDocument)
        {
            string returnString = string.Empty;
            MemoryStream fileStream = null;
            try
            {
                var queryData = GetPostQueryData(details, metadataList);

                DRepositoryBase repositoryBase = new DRepositoryBase()
                {
                    RepositoryName = details.RepositoryName,
                    Authorization = details.Authorization
                };

                DFile file = new DFile();
                file.isCompressed = details.IsCompressed;

                fileStream = new MemoryStream();
                updatedDocument.DataStream.CopyToStream(fileStream);
                if (!details.IsCompressed)
                {
                    file.FileName = Path.GetFileName(details.FileName);
                    file.FileExtentsion = Path.GetExtension(details.FileName);
                    file.FileContent = fileStream.GetBytes();
                }
                else
                {
                    file.FileName = Path.GetFileNameWithoutExtension(details.FileName) + ".zip";
                    file.FileExtentsion = ".zip";

                    // TODO: Integrated code for converting to csv
                    using (SpreadsheetDocument excelDocument = SpreadsheetDocument.Open(fileStream, true))
                    {
                        var zipFileStream = excelDocument.GetZipFileStream(Path.GetFileNameWithoutExtension(details.FileName));
                        if (zipFileStream != null)
                        {
                            file.FileContent = zipFileStream.GetBytes();
                        }
                    }
                }
                string queryDataString = queryData.SerializeObject<DQueryData>("queryData");
                string repositoryDataString = repositoryBase.SerializeObject<DRepositoryBase>("repositoryModel");
                string queryFIle = file.SerializeObject<DFile>("file");

                using (WebClient client = new WebClient())
                {
                    NameValueCollection values = new NameValueCollection();
                    values.Add("QueryData", queryDataString.EncodeTo64());
                    values.Add("RepositoryModel", repositoryDataString.EncodeTo64());
                    values.Add("File", queryFIle.EncodeTo64());

                    byte[] response = client.UploadValues(new Uri(Constants.DataUpWebServiceLink + "/UploadFile"), "POST", values);

                    string responseString = Encoding.UTF8.GetString(response);

                    if (!string.IsNullOrWhiteSpace(responseString))
                    {
                        var element = XElement.Parse(responseString);
                        if (!element.Value.Contains("false|"))
                        {
                            returnString = "Your data file was submitted successfully. You will receive an email shortly with your unique identifier and submission information.";
                        }
                        else
                        {
                            return element.Value;
                        }
                    }

                }
            }
            catch (Exception ex)
            {
                throw new Exception("An error while publishing file to repository. <br /> Exception : " + ex.Message, ex);
            }
            finally
            {
                if (fileStream != null)
                {
                    fileStream.Dispose();
                }
            }

            return returnString;
        }

        private static DQueryData GetIdentifierQueryData(IdentifierDetail details)
        {
            DQueryData queryData = new DQueryData();
            List<DKeyValuePair<string, string>> kayValue = new List<DKeyValuePair<string, string>>()
            {
                new DKeyValuePair<string, string>("Profile", ConfigReader<string>.GetSetting("Profile_Identifier")),
                new DKeyValuePair<string, string>("Who", details.Who),
                new DKeyValuePair<string, string>("What", details.What),
                new DKeyValuePair<string, string>("When", details.When.ToString("yyyy-MM-dd"))
            };

            queryData.KeyValuePair = kayValue.ToArray();
            return queryData;
        }

        private static DQueryData GetPostQueryData(PostFileDetail details, MetadataDetailList metadataList)
        {
            DQueryData queryData = new DQueryData();
            List<DKeyValuePair<string, string>> content = new List<DKeyValuePair<string, string>>();
            foreach (var item in metadataList.Metadata)
            {
                DKeyValuePair<string, string> metadata = new DKeyValuePair<string, string>();
                metadata.Key = item.Name;
                metadata.Value = item.Value;
                content.Add(metadata);
            }

            content.Add(new DKeyValuePair<string, string>() { Key = "Profile", Value = ConfigReader<string>.GetSetting("Profile_Post") });
            content.Add(new DKeyValuePair<string, string>() { Key = "who", Value = details.Who });
            content.Add(new DKeyValuePair<string, string>() { Key = "what", Value = details.What });
            content.Add(new DKeyValuePair<string, string>() { Key = "when", Value = details.When.ToString("yyyy-MM-dd") });
            content.Add(new DKeyValuePair<string, string>() { Key = "where", Value = details.Identifier });
            content.Add(new DKeyValuePair<string, string>() { Key = "ARK", Value = details.Identifier });

            queryData.KeyValuePair = content.ToArray();

            List<DataUp.Web.Service.Model.ParameterMetadataDetail> parameters = new List<DataUp.Web.Service.Model.ParameterMetadataDetail>();
            foreach (var item in metadataList.ParamterMetadata)
            {
                parameters.Add(new DataUp.Web.Service.Model.ParameterMetadataDetail()
                {
                    EntityName = item.EntityName,
                     EntityDescription = item.EntityDescription,
                      AttributeList = item.AttributeList.Select(q => new DataUp.Web.Service.Model.ParameterAttribute{
                                             Name = q.Name,
                                              Description = q.Description,
                                               Type = q.Type,
                                                Units = q.Units
                                      }).ToList()
                });
            }
            queryData.ParameterMetadata = parameters.ToArray();

            return queryData;
        }

        private Stream GetFileStream(int documentId, int userId)
        {
            Stream dataStream = null;

            var document = this.documentStoreRepository.GetItem(item => item.UserId == userId && item.Id == documentId);

            if (document != null)
            {
                if (!string.IsNullOrWhiteSpace(document.FileId))
                {
                    var blobDetails = this.blobDataRepository.GetBlobContent(document.FileId);
                    dataStream = blobDetails.Data;
                }
                else
                {
                    // TODO : Get the Stream of data from the 
                    // documents.FileData
                }
            }

            return dataStream;
        }
    }
}