Exemple #1
0
        public async Task <ActionResult> DeleteBlob(string blobName)
        {
            var blobRepository = new BlobStorageRepository(GetStorageSettings());
            await blobRepository.DeleteAsync(blobName);

            return(RedirectToAction("Index"));
        }
Exemple #2
0
        public MainPage()
        {
            try
            {
                ComputerVisionRepository computerVisionRepository = new ComputerVisionRepository();
                BlobStorageRepository    blobStorageRepository    = new BlobStorageRepository();
                IAnalysisService         analysisService          = new AnalysisService(computerVisionRepository);
                IFileService             fileService = new FileService();
                _logger = new ConsoleLogger();
                IComputerVisionService computerVisionService = new ComputerVisionService(
                    fileService,
                    analysisService,
                    computerVisionRepository,
                    blobStorageRepository);

                this.InitializeComponent();
                this.MainPageViewModel = new MainPageViewModel(Dispatcher, _logger, fileService, computerVisionService);

                Task.Run(() => MainPageViewModel.Init());

                //MainPageViewModel.Init();
            }
            catch (Exception ex)
            {
                _logger.LogEx(ex);
            }
        }
        public JsonResult DownloadDocument(int?id, int?ver)
        {
            if (Session["username"] != null)
            {
                if (id != null || ver != null)
                {
                    BlobStorageRepository br = new BlobStorageRepository();
                    string[] fileName        = getFileNameAndExtention(Convert.ToInt32(id));
                    string   handle          = Guid.NewGuid().ToString();
                    using (MemoryStream ms = br.GetBlobAsStream(fileName[0] + "_v" + ver, fileName[1]))
                    {
                        ms.Position      = 0;
                        TempData[handle] = ms.ToArray();
                    }


                    return(new JsonResult()
                    {
                        Data = new { fileGuid = handle, fileName = fileName[0] + fileName[1] }
                    });
                }
                return(null);
            }
            return(null);
        }
Exemple #4
0
        public async Task <ActionResult> ZipBlob(string blobName)
        {
            var blobRepository = new BlobStorageRepository(GetStorageSettings());

            var zipFileStream = new MemoryStream();


            using (ZipFile theZipFile = new ZipFile())
            {
                List <BlobItem> blobList = await blobRepository.ListFilesAsync(blobName);

                foreach (BlobItem myCloudBlob in blobList)
                {
                    BlobClient myBlobClient = blobRepository.CreateClient(myCloudBlob.Name);
                    var        myStream     = myBlobClient.OpenRead();

                    // Remove first part of the path
                    if (myCloudBlob.Name.StartsWith("Images"))
                    {
                        string newName = myCloudBlob.Name.Substring(7);
                        theZipFile.AddEntry(newName, myStream);
                    }
                    else
                    {
                        theZipFile.AddEntry(myCloudBlob.Name, myStream);
                    }
                }

                return(new ZipResult(theZipFile, "Report.zip"));
            }
        }
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation("HTTP trigger function processed a request.");

            string command = req.Query["command"];

            string  requestBody = await new StreamReader(req.Body).ReadToEndAsync();
            dynamic data        = JsonConvert.DeserializeObject(requestBody);

            command = command ?? data?.command;

            //Azure Blob Storage integration to keep your kubeconf file in Azure.

            var blobstorage = new BlobStorageRepository();

            var kubeconfigFile = await blobstorage.GetKubeConfigFile();

            var config = KubernetesClientConfiguration.BuildConfigFromConfigFile(kubeconfigFile);

            // var config = KubernetesClientConfiguration.BuildConfigFromConfigFile(@"C:\config.txt");
            IKubernetes client = new Kubernetes(config);

            log.LogInformation("Kubernetes Client Configured successfully...");

            if (command == "listpods")
            {
                var list = client.ListNamespacedPod("dev");
                foreach (var item in list.Items)
                {
                    log.LogInformation(item.Metadata.Name);
                }
                if (list.Items.Count == 0)
                {
                    log.LogInformation("Empty!");
                }
            }
            else if (command == "scale")
            {
                var deployment = client.ListNamespacedDeployment("dev").Items.First();

                var deploymentName = deployment.Metadata.Name;

                var newreplicavalue = deployment.Spec.Replicas.Value + 1;

                var patch = new JsonPatchDocument <V1ReplicaSet>();
                patch.Replace(e => e.Spec.Replicas, newreplicavalue);

                client.PatchNamespacedDeploymentScale(new V1Patch(patch), deploymentName, "dev");


                log.LogInformation("ReplicateSet of ---" + deploymentName + " --- scaled successfully....");
            }

            return(command != null
                ? (ActionResult) new OkObjectResult($"Azure Function executed successfully, command executed: {command}")
                : new BadRequestObjectResult("ERROR: I am only accept the commands (scale, delete, listpods)"));
        }
        private static async Task UploadAudio(StorageItem item, string mp3Location, ILogger log, CancellationToken cancellationToken)
        {
            log.LogInformation("Uploading to Blob Storage...");
            item.Message        = string.Empty;
            item.ConversionDate = DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm");
            item.StorageUrl     = await BlobStorageRepository.Upload(item.Id, mp3Location, cancellationToken);

            await BlobStorageRepository.Upload(item.Id, item, cancellationToken);
        }
Exemple #7
0
        public async Task UploadImage(string containerName, int order, string image)
        {
            //request bytes or base64 or whatever + iduser (hashid) +order
            BlobStorageRepository blobs = new BlobStorageRepository(context.Value.ConnectionString, containerName.ToLower());

            byte [] newimage = Convert.FromBase64String(image);
            await blobs.UploadimageBlob(order, newimage);

            await repository.UpdatePhoto(containerName.ToLower(), order);
        }
Exemple #8
0
        public void GetBlobsAsync_WhenBlobStorageHasItemsAndPrefixIsNotFound_ShouldNotReturnAnyItems()
        {
            var sut = new BlobStorageRepository(_blobConnectionString);

            // --- Act
            var resultBlockBlob = sut.GetBlobs("NonExistingPrefix");

            // --- Assert
            Assert.IsNotNull(resultBlockBlob);
            Assert.IsTrue(resultBlockBlob.ToArray().Length == 0);
        }
Exemple #9
0
        public async Task UploadCollectionAsync_WhenBlobNameIsEmpty_ShouldThrow()
        {
            // --- Arrange
            TrackContainer trackContainer = GetMock.TrackContainer();
            var            resultJson     = Serializer.WriteFromObject(typeof(TrackContainer), trackContainer);

            var sut = new BlobStorageRepository(_blobConnectionString);

            // --- Act
            string blobName = "";
            await sut.UploadCollectionAsync(resultJson, blobName);
        }
Exemple #10
0
        public void DownloadBlob_WhenBlobnameDoesNotExist_ShouldReturnEmptyString()
        {
            // --- Arrange
            var sut = new BlobStorageRepository(_blobConnectionString);

            // --- Act
            var blobName     = "non existing blob";
            var objectString = sut.DownloadBlob(blobName);

            // --- Assert
            Assert.IsTrue(objectString == string.Empty);
        }
Exemple #11
0
        public void GetBlobs_WhenAzureBlobStorageHasItems_ShouldReturnItems()
        {
            var connStr = AppSettings.AzureDevConnectionString;
            var sut     = new BlobStorageRepository(_blobConnectionString);

            // --- Act
            var blobItems = sut.GetBlobs();

            // --- Assert
            Assert.IsNotNull(blobItems);
            Assert.IsTrue(blobItems.ToArray().Length > 0);
        }
Exemple #12
0
 public static async Task <HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequestMessage req, ILogger log)
 {
     log.LogInformation("List triggered");
     try
     {
         return(req.CreateResponse(HttpStatusCode.OK, await BlobStorageRepository.List()));
     }
     catch (Exception ex)
     {
         log.LogError(ex, ex.Message.EscapeCurlyBraces());
         return(req.CreateResponse(HttpStatusCode.BadRequest, ex));
     }
 }
Exemple #13
0
        public void GetBlobs_WhenBlobStorageHasItemsAndPrefixIsFound_ShouldReturnItems()
        {
            var            sut            = new BlobStorageRepository(_blobConnectionString);
            TrackContainer trackContainer = GetMock.TrackContainer();
            var            resultJson     = Serializer.WriteFromObject(typeof(TrackContainer), trackContainer);
            var            blobItem       = sut.UploadCollection(resultJson, trackContainer.Id);

            // --- Act
            var blobItems = sut.GetBlobs(blobItem.BlobId);

            // --- Assert
            Assert.IsNotNull(blobItems);
            Assert.IsTrue(blobItems.ToArray().Length > 0);
        }
Exemple #14
0
        public static async Task Run(
            [ServiceBusTrigger("process", Connection = "ServiceBusConnectionListen")] string queueMessage,
            ILogger log)
        {
            var connectionString      = Environment.GetEnvironmentVariable("StorageConnectionString", EnvironmentVariableTarget.Process);
            var blobStorageRepository = new BlobStorageRepository(connectionString);

            var memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(queueMessage));

            var rnd = new Random();
            await Task.Delay(rnd.Next(12000, 36000));

            await blobStorageRepository.AddFileAsync("scaled", queueMessage, memoryStream);
        }
Exemple #15
0
        public async Task <ActionResult> Index()
        {
            var fileList = new List <string>();

            var blobRepository = new BlobStorageRepository(GetStorageSettings());

            var result = await blobRepository.ListFilesAsync();

            foreach (var blobItem in result)
            {
                fileList.Add(blobItem.Name);
            }

            return(View(fileList));
        }
Exemple #16
0
        public async Task UploadCollectionAsync_WhenCollectionValidUploadToAzure_ShouldUpload()
        {
            // --- Arrange
            TrackContainer trackContainer = GetMock.TrackContainer();
            var            resultJson     = Serializer.WriteFromObject(typeof(TrackContainer), trackContainer);

            var sut = new BlobStorageRepository(_blobConnectionString);

            // --- Act
            var blobName = trackContainer.Id;
            var blobItem = await sut.UploadCollectionAsync(resultJson, blobName);

            // --- Assert
            Assert.IsNotNull(blobItem);
            Assert.AreEqual(blobName, blobItem.BlobId);
            Assert.IsTrue(blobItem.BlobUri.AbsoluteUri.LastIndexOf(blobName) > 0);
        }
Exemple #17
0
        public void DownloadBlob_WhenValidCollectionUploadedAzure_ShouldDownloadToCollectionObject()
        {
            // --- Arrange
            TrackContainer trackContainer = GetMock.TrackContainer();
            var            containerJson  = Serializer.WriteFromObject(typeof(TrackContainer), trackContainer);

            var sut = new BlobStorageRepository(_blobConnectionString);

            // --- Act
            var blobName = trackContainer.Id;

            sut.UploadCollection(containerJson, blobName);
            var objectString = sut.DownloadBlob(blobName);
            var container    = Serializer.ReadToTrackObject <TrackContainer>(objectString);

            // --- Assert
            Assert.IsNotNull(container);
        }
Exemple #18
0
        private async Task <FileResult> DownloadAzureBlob(string blobName)
        {
            var blobRepository = new BlobStorageRepository(GetStorageSettings());

            var dataStream = await blobRepository.DownloadAsync(blobName);

            if (dataStream == null)
            {
                throw new FileNotFoundException($"Could not find the blob named: {blobName}");
            }

            // Determine the Mime Type
            string mimeType = MimeMapping.GetMimeMapping(blobName) ?? "application/octet-stream";

            // The stream will be destoyed by FileSreamResult.WriteFile deep within HttpResponseBase according to this post
            // https://stackoverflow.com/questions/3084366/how-do-i-dispose-my-filestream-when-implementing-a-file-download-in-asp-net
            return(File(dataStream, mimeType, blobName));
        }
Exemple #19
0
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "files")] HttpRequest req, ILogger log)
        {
            var connectionString      = Environment.GetEnvironmentVariable("StorageConnectionString", EnvironmentVariableTarget.Process);
            var blobStorageRepository = new BlobStorageRepository(connectionString);

            if (req.Form.Files.Count != 1)
            {
                return(new BadRequestResult());
            }

            using (var ms = new MemoryStream())
            {
                var file = req.Form.Files[0];
                await file.CopyToAsync(ms);

                ms.Seek(0, SeekOrigin.Begin);
                await blobStorageRepository.AddFileAsync("upload", file.FileName, ms);
            }

            return(new OkResult());
        }
Exemple #20
0
        public async Task <ActionResult> UploadFile()
        {
            var httpRequest = HttpContext.Request;

            if (httpRequest.Files.Count > 0)
            {
                const int fileIndex      = 0;
                var       blobRepository = new BlobStorageRepository(GetStorageSettings());

                var directory = FileUploadHelper.GetFormValue <string>(httpRequest, "directory", string.Empty);
                var fileName  = string.IsNullOrWhiteSpace(directory) ?
                                FileUploadHelper.GetFileName(httpRequest, fileIndex) :
                                Path.Combine(directory, FileUploadHelper.GetFileName(httpRequest, fileIndex));

                using (Stream fileStream = FileUploadHelper.GetInputStream(httpRequest, fileIndex))
                    await blobRepository.UploadAsync(fileName, fileStream);

                return(RedirectToAction("Index"));
            }

            throw new ArgumentException("File count is zero.");
        }
Exemple #21
0
 private static Task <string> GetTempFileStorageUrl(string id, ILogger log)
 {
     log.LogInformation($"[{id}] Checking blob storage");
     return(BlobStorageRepository.GetTempFileStorageUrl(id));
 }
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext <GetOnBoardDbContext>(
                option => option.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"), b => b.MigrationsAssembly("GetOnBoard")));

            // Azure configuration
            services.AddOptions();
            services.Configure <AzureStorageConfig>(Configuration.GetSection("AzureStorageConfig"));

            // Initialize sigleton
            services.AddSingleton <IBlobStorageRepository>(serviceProvider =>
            {
                var blobStorage = new BlobStorageRepository(serviceProvider.GetService <IOptions <AzureStorageConfig> >());
                blobStorage.Initialize().GetAwaiter().GetResult();
                return(blobStorage);
            });

            //AddTransient?
            //services.AddScoped<IGameSessionsRepository, GameSessionsRepository>();
            services.AddTransient <IGameSessionsRepository, GameSessionsRepository>();
            services.AddTransient <IProfileRepository, ProfileRepository>();
            services.AddTransient <IChatRepository, ChatRepository>();
            //services.AddSingleton<IGameSessionsRepository>(serviceProvider =>
            //{
            //	return new GameSessionsRepository(GetOnBoardDbContext dbContext);
            //});


            //TODO: CORS POLICY poprawić
            services.AddCors(o => o.AddPolicy("CorsPolicy", builder =>
            {
                builder.WithOrigins(new[] { "http://localhost:81", "http://localhost:80", "http://localhost", "http://getonboard.pl/", "https://getonboard.pl/" })
                .AllowAnyMethod()
                .AllowAnyHeader()
                .AllowCredentials();
            }
                                              ));
            //TODO: zmienić wymaganie na takie co są w backendzie // Marek - chyba frontendzie ? i moim zdanie to należy wyłączyć i na frroncie będzie to sprawdzane
            services.AddIdentity <ApplicationUser, IdentityRole>(
                option =>
            {
                option.Password.RequireDigit           = false;
                option.Password.RequiredLength         = 6;
                option.Password.RequireNonAlphanumeric = false;
                option.Password.RequireUppercase       = false;
                option.Password.RequireLowercase       = false;
            }
                ).AddEntityFrameworkStores <GetOnBoardDbContext>()
            .AddDefaultTokenProviders();

            services.AddAuthentication(option =>
            {
                option.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                option.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
                option.DefaultScheme             = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(options =>
            {
                options.SaveToken                 = true;
                options.RequireHttpsMetadata      = true;
                options.TokenValidationParameters = new TokenValidationParameters()
                {
                    ValidateIssuer   = true,
                    ValidateAudience = true,
                    ValidAudience    = Configuration["Jwt:Audience"],
                    ValidIssuer      = Configuration["Jwt:Issuer"],
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:SigningKey"]))
                };
                options.Events = new JwtBearerEvents
                {
                    OnMessageReceived = context =>
                    {
                        var accessToken = context.Request.Query["access_token"];

                        // If the request is for our hub...
                        var path = context.HttpContext.Request.Path;
                        if (!string.IsNullOrEmpty(accessToken) &&
                            (path.StartsWithSegments("/chat")))
                        {
                            // Read the token out of the query string
                            context.Token = accessToken;
                        }
                        return(Task.CompletedTask);
                    },
                    //add token expired header
                    OnAuthenticationFailed = context =>
                    {
                        if (context.Exception.GetType() == typeof(SecurityTokenExpiredException))
                        {
                            context.Response.Headers.Add("Token-Expired", "true");
                        }
                        return(Task.CompletedTask);
                    }
                };
            });
            services.AddMvc()
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
            .AddJsonOptions(x => x.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore);
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("GetOnBoardAPI", new Info {
                    Title = "GetOnBoardAPI", Version = "0.0.1"
                });
                c.AddSecurityDefinition("Bearer", new ApiKeyScheme
                {
                    Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"",
                    Name        = "Authorization",
                    In          = "header",
                    Type        = "apiKey"
                });
                c.OperationFilter <SecurityRequirementsOperationFilter>();

                var filePath = Path.Combine(System.AppContext.BaseDirectory, "GetOnBoard.xml");
                c.IncludeXmlComments(filePath);
            });
            services.AddSignalR();
        }
        public string ReviewDocument(int id, int ver1, int ver2)
        {
            BlobStorageRepository blobStorage = new BlobStorageRepository();
            DatabaseHelper        dbh         = new DatabaseHelper();

            DataRow[]   dr            = dbh.RunQuery($"Select fileName, fileExtension from Document where documentId={id}");
            DataRow[]   dr2           = dbh.RunQuery($"Select timeStamp, modifiedBy from documentVersion where documentId={id} and version={ver1}");
            DataRow[]   dr3           = dbh.RunQuery($"Select timeStamp, modifiedBy from documentVersion where documentId={id} and version={ver2}");;
            string      fileName      = dr[0]["fileName"].ToString();
            string      fileExtention = dr[0]["fileExtension"].ToString();
            string      fileName1     = fileName + "_v" + ver1;
            string      fileName2     = fileName + "_v" + ver2;
            ReviewModel rm            = new ReviewModel();

            rm.modifiedBy1 = dr2[0]["modifiedBy"].ToString();
            rm.modifiedBy2 = dr3[0]["modifiedBy"].ToString();
            rm.timeStamp1  = dr2[0]["timeStamp"].ToString();
            rm.timeStamp2  = dr3[0]["timeStamp"].ToString();
            MemoryStream doc1 = blobStorage.GetBlobAsStream(fileName1, fileExtention);
            MemoryStream doc2 = blobStorage.GetBlobAsStream(fileName2, fileExtention);

            rm.fileSize1 = blobStorage.GetFileSize(fileName1, fileExtention);
            rm.fileSize2 = blobStorage.GetFileSize(fileName2, fileExtention);
            DocumentJSON.Document docJSON1;
            DocumentJSON.Document docJSON2;
            DocumentCore          docCore1 = DocumentCore.Load(doc1, new DocxLoadOptions());
            DocumentCore          docCore2 = DocumentCore.Load(doc2, new DocxLoadOptions());

            docJSON1 = Document.CreateJSON(docCore1, ver1);
            docJSON2 = Document.CreateJSON(docCore2, ver2);
            docJSON2 = Document.CompareParagraphs(docJSON1, docJSON2);
            docJSON2 = Document.CompareTables(docJSON1, docJSON2);
            docJSON2 = Document.CompareDocumentImages(docJSON1, docJSON2);
            int order = 0;
            List <ElementJSON> doc2Elements = new List <ElementJSON>();

            foreach (Section sec in docCore2.GetChildElements(false, ElementType.Section))
            {
                foreach (Element el in sec.GetChildElements(false))
                {
                    if (el.ElementType.Equals(ElementType.Paragraph))
                    {
                        if (el.GetChildElements(false, ElementType.Picture).Count() != 0)
                        {
                            Picture     pic     = (Picture)el.GetChildElements(false, ElementType.Picture).First();
                            String      hash    = Document.CalculateHash(pic.ImageData.GetStream().ToArray());
                            string      status  = docJSON2.images.Where(x => x.hash == hash).First().status;
                            ElementJSON picture = new ElementJSON();
                            picture.order   = order++;
                            picture.type    = PICTURE_TYPE;
                            picture.content = Convert.ToBase64String(pic.ImageData.GetStream().ToArray());
                            picture.status  = status;
                            picture.format  = pic.ImageData.Format.ToString();
                            doc2Elements.Add(picture);
                        }
                        else
                        {
                            Paragraph par = (Paragraph)el;
                            if (!par.Content.ToString().Equals("\r\n") && !par.Content.ToString().Equals(""))
                            {
                                string parContent = par.Content.ToString().Replace("trial", "");
                                if (parContent.Contains("Created by the  version of Document .Net 3.3.3.27"))
                                {
                                    int index = parContent.IndexOf("Created by the  version of Document .Net 3.3.3.27");
                                    parContent = par.Content.ToString().Remove(index, par.Content.ToString().Length - index);
                                }
                                if (!parContent.Equals(""))
                                {
                                    String hash = Document.CalculateHash(Encoding.UTF8.GetBytes(parContent));
                                    DocumentJSON.Paragraph parJSON   = docJSON2.paragraphs.Where(x => x.hash.Equals(hash)).First();
                                    ElementJSON            paragraph = new ElementJSON();
                                    paragraph.id      = parJSON.id;
                                    paragraph.order   = order++;
                                    paragraph.content = parContent;
                                    paragraph.type    = PARAGRAPH_TYPE;
                                    paragraph.status  = parJSON.status;
                                    if (paragraph.status.Equals("m"))
                                    {
                                        List <ElementJSON>           sentencesList = new List <ElementJSON>();
                                        string[]                     sentences     = par.Content.ToString().Split('.');
                                        List <DocumentJSON.Sentence> sJSON         = parJSON.sentence.ToList();
                                        int sentenceOrder = 0;
                                        foreach (string s in sentences)
                                        {
                                            ElementJSON sent = new ElementJSON();
                                            sent.type    = SENTENCE_TYPE;
                                            sent.order   = sentenceOrder++;
                                            sent.content = s;
                                            if (sJSON.Where(x => x.content.Equals(s)).Count() > 0)
                                            {
                                                sent.status = sJSON.Where(x => x.content.Equals(s)).First().status;
                                            }

                                            else
                                            {
                                                sent.status = "o";
                                            }
                                            if (!sent.status.Equals("d"))
                                            {
                                                sentencesList.Add(sent);
                                            }
                                        }
                                        paragraph.elements = sentencesList.ToArray();
                                    }
                                    doc2Elements.Add(paragraph);
                                }
                            }
                        }
                    }
                    else if (el.ElementType.Equals(ElementType.Table))
                    {
                        ElementJSON table = new ElementJSON();
                        table.order = order++;
                        table.type  = TABLE_TYPE;
                        List <ElementJSON> rows = new List <ElementJSON>();
                        int rowOrder            = 0;
                        foreach (TableRow tr in el.GetChildElements(false, ElementType.TableRow))
                        {
                            ElementJSON row = new ElementJSON();
                            row.order = rowOrder++;
                            List <ElementJSON> cells = new List <ElementJSON>();
                            int cellOrder            = 0;
                            foreach (TableCell tc in tr.GetChildElements(false, ElementType.TableCell))
                            {
                                ElementJSON cell = new ElementJSON();
                                string      hash = Document.CalculateHash(Encoding.UTF8.GetBytes(tc.Content.ToString()));
                                cell.order   = cellOrder++;
                                cell.content = tc.Content.ToString();
                                cell.status  = docJSON2.cells.ToList().Where(x => x.hash.Equals(hash)).First().status;
                                cells.Add(cell);
                            }
                            row.elements = cells.ToArray();
                            rows.Add(row);
                        }
                        table.elements = rows.ToArray();
                        doc2Elements.Add(table);
                    }
                }
            }
            rm.Doc2 = doc2Elements.ToArray();
            order   = 0;
            List <ElementJSON> doc1Elements = new List <ElementJSON>();

            foreach (Section sec in docCore1.GetChildElements(false, ElementType.Section))
            {
                foreach (Element el in sec.GetChildElements(false))
                {
                    if (el.ElementType.Equals(ElementType.Paragraph))
                    {
                        if (el.GetChildElements(false, ElementType.Picture).Count() != 0)
                        {
                            Picture     pic     = (Picture)el.GetChildElements(false, ElementType.Picture).First();
                            String      hash    = Document.CalculateHash(pic.ImageData.GetStream().ToArray());
                            string      status  = docJSON1.images.Where(x => x.hash == hash).First().status;
                            ElementJSON picture = new ElementJSON();
                            picture.order   = order++;
                            picture.type    = PICTURE_TYPE;
                            picture.content = Convert.ToBase64String(pic.ImageData.GetStream().ToArray());
                            picture.status  = status;
                            if (!picture.status.Equals("d"))
                            {
                                picture.status = "o";
                            }
                            picture.format = pic.ImageData.Format.ToString();
                            doc1Elements.Add(picture);
                        }
                        else
                        {
                            Paragraph par = (Paragraph)el;
                            if (!par.Content.ToString().Equals("\r\n") && !par.Content.ToString().Equals(""))
                            {
                                string parContent = par.Content.ToString().Replace("trial", "");
                                if (parContent.Contains("Created by the  version of Document .Net 3.3.3.27"))
                                {
                                    int index = parContent.IndexOf("Created by the  version of Document .Net 3.3.3.27");
                                    parContent = par.Content.ToString().Remove(index, par.Content.ToString().Length - index);
                                }
                                if (!parContent.Equals(""))
                                {
                                    String hash = Document.CalculateHash(Encoding.UTF8.GetBytes(parContent));
                                    DocumentJSON.Paragraph parJSON   = docJSON1.paragraphs.Where(x => x.hash.Equals(hash)).First();
                                    ElementJSON            paragraph = new ElementJSON();
                                    paragraph.id      = parJSON.id;
                                    paragraph.order   = order++;
                                    paragraph.content = parContent;
                                    paragraph.type    = PARAGRAPH_TYPE;
                                    paragraph.status  = parJSON.status;
                                    if (paragraph.status.Equals("n"))
                                    {
                                        paragraph.status = "o";
                                    }
                                    if (docJSON2.paragraphs.Where(x => x.id == parJSON.id).First().status.Equals("m"))
                                    {
                                        paragraph.status = "m";
                                        List <ElementJSON>           sentencesList = new List <ElementJSON>();
                                        string[]                     sentences     = par.Content.ToString().Split('.');
                                        List <DocumentJSON.Sentence> sJSON         = docJSON2.paragraphs.Where(x => x.id == parJSON.id).First().sentence.Where(y => y.status.Equals("d")).ToList();
                                        int sentenceOrder = 0;
                                        foreach (string s in sentences)
                                        {
                                            ElementJSON sent = new ElementJSON();
                                            sent.type    = SENTENCE_TYPE;
                                            sent.order   = sentenceOrder++;
                                            sent.content = s;
                                            if (sJSON.Where(x => x.content.Equals(s)).Count() > 0)
                                            {
                                                sent.status = "m";
                                            }
                                            else
                                            {
                                                sent.status = "o";
                                            }
                                            sentencesList.Add(sent);
                                        }
                                        paragraph.elements = sentencesList.ToArray();
                                    }
                                    doc1Elements.Add(paragraph);
                                }
                            }
                        }
                    }
                    else if (el.ElementType.Equals(ElementType.Table))
                    {
                        ElementJSON table = new ElementJSON();
                        table.order = order++;
                        table.type  = TABLE_TYPE;
                        List <ElementJSON> rows = new List <ElementJSON>();
                        int rowOrder            = 0;
                        foreach (TableRow tr in el.GetChildElements(false, ElementType.TableRow))
                        {
                            ElementJSON row = new ElementJSON();
                            row.order = rowOrder++;
                            List <ElementJSON> cells = new List <ElementJSON>();
                            int cellOrder            = 0;
                            foreach (TableCell tc in tr.GetChildElements(false, ElementType.TableCell))
                            {
                                ElementJSON cell = new ElementJSON();
                                string      hash = Document.CalculateHash(Encoding.UTF8.GetBytes(tc.Content.ToString()));
                                cell.order   = cellOrder++;
                                cell.content = tc.Content.ToString();
                                cell.status  = docJSON1.cells.ToList().Where(x => x.hash.Equals(hash)).First().status;
                                if (!cell.status.Equals("d"))
                                {
                                    cell.status = "o";
                                }
                                cells.Add(cell);
                            }
                            row.elements = cells.ToArray();
                            rows.Add(row);
                        }
                        table.elements = rows.ToArray();
                        doc1Elements.Add(table);
                    }
                }
            }
            rm.Doc1 = doc1Elements.ToArray();
            return(JsonConvert.SerializeObject(rm));
        }
Exemple #24
0
        public long GetUsedStorage()
        {
            BlobStorageRepository bs = new BlobStorageRepository();

            return(bs.BlobStorage());
        }