Source

main-vinayFork / Source / Excel / Excel.BizLogic / Managers / ServiceManager.cs

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Net;
using System.Runtime.Serialization;
using System.Text;
using System.Linq;
using System.Xml.Linq;
using DataUp.Excel.Common;
using DataUp.Web.Service.Model;
using Ionic.Zip;
using Microsoft.Office.Interop.Excel;
using System.Security.Cryptography.X509Certificates;
using Tools = Microsoft.Office.Tools.Excel;
using System.Net.Security;

namespace DataUp.Excel.BizLogic
{
    public class RepositoryManager : IRepositoryManager
    {
        private Tools.ApplicationFactory Factory { get; set; }

        DataUpService.RepositoryDataContext service;

        /// <summary>
        /// Gets or sets the workbook instance.
        /// </summary>
        public _Workbook Workbook { get; set; }

        /// <summary>
        /// Creates instance of RepositoryManager class.
        /// 
        /// </summary>
        /// <param name="workbook">Workbook instance.</param>
        /// <param name="factory">ApplicationFactory Instance.</param>
        public RepositoryManager(_Workbook workbook, Tools.ApplicationFactory factory)
        {
            this.Workbook = workbook;
            this.Factory = factory;
            ServicePointManager.ServerCertificateValidationCallback = delegate(object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return true; };
            this.service = new DataUpService.RepositoryDataContext(new Uri(Common.Constants.DcxlWebServiceLink));
        }

        /// <summary>
        /// Gets the identifier from repository.
        /// </summary>
        /// <param name="data">Query data.</param>
        /// <param name="repositoryBase">Repository base instance.</param>
        /// <returns>Identifier for the given document.</returns>
        public ServiceResponse GetIdentifier(DQueryData queryData, DRepositoryBase repositoryBase)
        {
            ServiceResponse status = new ServiceResponse();

            try
            {
                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(Common.Constants.DcxlWebServiceLink + "/GetIdentifier"), "POST", values);

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

                    if (!string.IsNullOrWhiteSpace(responseString))
                    {
                        var getIdentifierElement = XElement.Parse(responseString);
                        status = ServiceResponse.CreateStatus(getIdentifierElement.Value);
                    }
                }
            }
            catch (Exception ex)
            {
                // TODO: Error handling
                status = ServiceResponse.CreateFailureStatus(ex);
            }

            return status;
        }

        /// <summary>
        /// Post file as CSV.
        /// </summary>
        /// <param name="data">Metadata List.</param>
        /// <param name="rep">Repository base instance.</param>
        /// <param name="filename">Name of the file.</param>
        /// <param name="filecontent">Content of the file.</param>
        /// <param name="extension">Extension of the file.</param>
        /// <param name="iscompressed">Whether the file is compressed or not.</param>
        /// <returns>Successfully posted file or not.</returns>
        public ServiceResponse PostAsCSV(DQueryData data, DRepositoryBase rep, string filename, byte[] filecontent, string extension, bool iscompressed)
        {
            ServiceResponse status = new ServiceResponse();

            try
            {
                status = PublishFile(data, rep, Path.GetFileName(filename), filecontent, extension, iscompressed);
            }
            catch (Exception ex)
            {
                // TODO: Error handling
                status = ServiceResponse.CreateFailureStatus(ex);
            }

            return status;
        }

        /// <summary>
        /// Post file as XLS.
        /// </summary>
        /// <param name="data">Metadata List.</param>
        /// <param name="rep">Repository base instance.</param>
        /// <param name="filename">Name of the file.</param>
        /// <param name="filecontent">Content of the file.</param>
        /// <param name="extension">Extension of the file.</param>
        /// <param name="iscompressed">Whether the file is compressed or not.</param>
        /// <returns>Successfully posted file or not.</returns>
        public ServiceResponse PostAsXSL(DQueryData data, DRepositoryBase rep, string filename, byte[] filecontent, string extension, bool iscompressed)
        {
            ServiceResponse status = new ServiceResponse();

            try
            {
                status = PublishFile(data, rep, Path.GetFileName(filename), filecontent, extension, iscompressed);
            }
            catch (Exception ex)
            {
                // TODO: Error handling
                status = ServiceResponse.CreateFailureStatus(ex);
            }

            return status;
        }

        /// <summary>
        /// Gets the temp path of the xls file.
        /// </summary>
        /// <returns>Path of the xls file.</returns>
        public string GetXslFilePath()
        {
            string FileName = string.Empty;
            FileName = Path.GetTempPath();
            return FileName;
        }

        /// <summary>
        /// This method is used to convert the given workbook to csv files and then compress.
        /// </summary>
        /// <param name="zipFileName">Name of the compressed file.</param>
        /// <returns>Path of the compressed file.</returns>
        public string GetCsvZipFile(string zipFileName)
        {
            string strVal = string.Empty;
            string tempDirectory = string.Empty;
            string filepath = string.Empty;
            string tempCompressedFile = string.Empty;
            _Workbook workbook = this.Workbook;

            if (workbook != null)
            {
                tempDirectory = Path.Combine(Path.GetTempPath(), Path.GetFileNameWithoutExtension(Path.GetRandomFileName()));

                DirectoryInfo tempDirectoryInfo = Directory.CreateDirectory(tempDirectory);

                tempCompressedFile = Path.Combine(tempDirectoryInfo.FullName, zipFileName + ".zip");

                foreach (var item in workbook.Worksheets)
                {
                    Worksheet sheet = (Worksheet)item;
                    if (workbook.IsValid(sheet))
                    {
                        string filename = Path.Combine(tempDirectoryInfo.FullName, string.Format("{0}-{1}.csv", zipFileName, sheet.Name));
                        using (StreamWriter file = new StreamWriter(filename))
                        {
                            // Range range = sheet.UsedRange;
                            var data = sheet.UsedRange.GetDataArray(false);

                            int rows = data.GetLength(0);
                            int cols = data.GetLength(1);

                            if (data != null)
                            {
                                for (int rCnt = 1; rCnt <= rows; rCnt++)
                                {
                                    // if (!workbook.IsEmpty((range.Cells[rCnt, 1] as Range).EntireRow))
                                    System.Text.StringBuilder sb = new System.Text.StringBuilder();
                                    for (int cCnt = 1; cCnt <= cols; cCnt++)
                                    {
                                        var val = data[rCnt, cCnt];
                                        if (val != null)
                                        {
                                            if (val.ToString().Contains("\""))
                                            {
                                                sb.AppendFormat("\"\"{0}\"\",", val.ToString());
                                            }
                                            else
                                            {
                                                sb.AppendFormat("\"{0}\",", val.ToString());
                                            }
                                        }
                                        else
                                        {
                                            sb.Append(",");
                                        }
                                    }
                                    // sb.Append(Environment.NewLine);
                                    file.WriteLine(sb.ToString());
                                }
                            }
                        }
                    }
                }

                var files = Directory.GetFiles(tempDirectoryInfo.FullName);
                if (files == null || files.Length <= 0)
                {
                    // Create an empty File.
                    string filename = Path.Combine(tempDirectoryInfo.FullName, "empty.csv");
                    using (StreamWriter file = new StreamWriter(filename))
                    {
                        file.WriteLine(string.Empty);
                    }
                }

                files = Directory.GetFiles(tempDirectoryInfo.FullName);
                if (files != null && files.Length > 0)
                {
                    filepath = ZipFiles(tempDirectoryInfo.FullName, tempCompressedFile);
                }
            }
            return filepath;
        }

        /// <summary>
        /// This method if used to get the list of repositories.
        /// </summary>
        /// <returns>list of repositories</returns>
        public List<RepositoryModel> GetRespositories()
        {
            List<RepositoryModel> repositories = new List<RepositoryModel>();

            try
            {
                // Get details from OData Service.
                foreach (var item in service.Repositories)
                {
                    repositories.Add(new RepositoryModel()
                    {
                        RepositoryName = item.RepositoryName,
                        RepositoryType = item.Type,
                        IsPasswordRequired = item.IsPasswordRequired
                    });
                }
            }
            catch (Exception ex)
            {
                // TODO: Error handling
                throw new Exception("Error while getting repositories: " + ex.Message, ex);
            }

            return repositories;
        }

        /// <summary>
        /// Gets the identifier from repository.
        /// </summary>
        /// <param name="details">Identifier details.</param>
        /// <returns>Service response instance.</returns>
        public ServiceResponse GetIdentifier(IdentifierDetail details)
        {
            ServiceResponse status = new ServiceResponse();

            try
            {
                DQueryData queryData = GetIdentifierQueryData(details);

                // Convert.ToBase64String(System.Text.UTF8Encoding.UTF8.GetBytes("dcxl" + ":" + "dcxl"))
                DRepositoryBase repositoryBase = new DRepositoryBase()
                {
                    RepositoryName = details.RepositoryName,
                    Authorization = details.Authorization
                };

                status = GetIdentifier(queryData, repositoryBase);
            }
            catch (Exception ex)
            {
                // TODO: Error handling
                status = ServiceResponse.CreateFailureStatus(ex);
            }

            return status;
        }

        /// <summary>
        /// Gets the user agreement for the given repository.
        /// </summary>
        /// <param name="repositoryName">Name of the repository.</param>
        /// <returns>User agreement string.</returns>
        public string GetUserAgreement(string repositoryName)
        {
            string userAgreement = string.Empty;

            using (WebClient client = new WebClient())
            {
                NameValueCollection values = new NameValueCollection();
                values.Add("RepositoryName", repositoryName);

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

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

                if (!string.IsNullOrWhiteSpace(responseString))
                {
                    var element = XElement.Parse(responseString);
                    userAgreement = element.Value;
                }
            }

            return userAgreement;
        }

        /// <summary>
        /// Publish file to repository.
        /// </summary>
        /// <param name="details">Post file detail.</param>
        /// <param name="metadataList">Metadata list.</param>
        /// <param name="parameterMetadata">Parameter metadata list.</param>
        /// <returns>Service response instance.</returns>
        public ServiceResponse PublishFile(PostFileDetail details, List<MetadataDetail> metadataList, List<ParameterDetail> parameterMetadata)
        {
            ServiceResponse status = new ServiceResponse();

            try
            {
                var queryData = GetPostQueryData(details, metadataList, parameterMetadata);

                // Convert.ToBase64String(System.Text.UTF8Encoding.UTF8.GetBytes("dcxl" + ":" + "dcxl"))
                DRepositoryBase repositoryBase = new DRepositoryBase()
                {
                    RepositoryName = details.RepositoryName,
                    Authorization = details.Authorization
                };

                DFile file = new DFile();
                file.isCompressed = details.IsCompressed;
                file.FileName = Path.GetFileName(details.Filename);
                file.FileExtentsion = Path.GetExtension(details.Filename);
                file.FileContent = details.Content;
                status = PublishFile(queryData, repositoryBase, file);

            }
            catch (Exception)
            {
                // TODO: Error handling
                throw;
            }

            return status;
        }

        private static string ZipFiles(string inputFolderPath, string outputPathAndFile)
        {
            ArrayList arrOfFiles = GenerateFileList(inputFolderPath); // generate file list
            //Stream ostream;
            //byte[] obuffer;
            string outPath = outputPathAndFile;
            using (ZipFile zip = new ZipFile(outPath))
            {
                foreach (string file in arrOfFiles)
                {
                    zip.AddFile(file, "");
                }
                zip.Save();
                return outPath;
            }
        }

        private static ArrayList GenerateFileList(string Dir)
        {
            ArrayList files = new ArrayList();
            bool Empty = true;
            foreach (string file in Directory.GetFiles(Dir)) // add each file in directory
            {
                files.Add(file);
                Empty = false;
            }

            if (Empty)
            {
                // if directory is completely empty, add it
                if (Directory.GetDirectories(Dir).Length == 0)
                {
                    files.Add(Dir + @"/");
                }
            }

            foreach (string dirs in Directory.GetDirectories(Dir))
            {
                foreach (object obj in GenerateFileList(dirs))
                {
                    files.Add(obj);
                }
            }
            return files;
        }

        private static string SerializeObject(object obj, string rootName)
        {
            DataContractSerializer se;
            if (string.IsNullOrEmpty(rootName))
                se = new DataContractSerializer(obj.GetType());
            else
                se = new DataContractSerializer(obj.GetType(), rootName, "");

            byte[] bArr;
            using (MemoryStream ms = new MemoryStream())
            {
                se.WriteObject(ms, obj);
                ms.Position = 0;
                bArr = new byte[ms.Length];
                ms.Read(bArr, 0, Convert.ToInt32(ms.Length));
            }

            return new UTF8Encoding().GetString(bArr);
        }

        private static ServiceResponse PublishFile(DQueryData queryData, DRepositoryBase repositoryBase, DFile file)
        {
            ServiceResponse status = new ServiceResponse();

            string returnString = string.Empty;
            string queryDataString = queryData.SerializeObject<DQueryData>("queryData");
            string repositoryDataString = repositoryBase.SerializeObject<DRepositoryBase>("repositoryModel");
            string queryFIle = file.SerializeObject<DFile>("file");

            using (CustomWebClient client = new CustomWebClient())
            {
                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(Common.Constants.DcxlWebServiceLink + "/UploadFile"), "POST", values);

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

                if (!string.IsNullOrWhiteSpace(responseString))
                {
                    var element = XElement.Parse(responseString);
                    status = ServiceResponse.CreateStatus(element.Value);
                }
            }

            return status;
        }

        private ServiceResponse PublishFile(DQueryData queryData, DRepositoryBase repositoryBase, string filename, byte[] filecontent, string extension, bool iscompressed)
        {
            DFile file = new DFile();
            file.isCompressed = iscompressed;

            file.FileName = Path.GetFileName(filename);
            file.FileExtentsion = extension;
            file.FileContent = filecontent;

            return PublishFile(queryData, repositoryBase, file);
        }

        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", Common.Constants.GetIdentifierProfile),
                new DKeyValuePair<string, string>("Who", details.Who),
                new DKeyValuePair<string, string>("What", details.What),
                new DKeyValuePair<string, string>("When", details.When.ToString(Common.Constants.DefaultDateFormat))
            };

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

        private static DQueryData GetPostQueryData(PostFileDetail details, List<MetadataDetail> metadataList, List<ParameterDetail> parameterMetadataList)
        {
            DQueryData queryData = new DQueryData();
            List<DKeyValuePair<string, string>> content = new List<DKeyValuePair<string, string>>();
            foreach (var item in metadataList)
            {
                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 = Common.Constants.GetPostProfile });
            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(Common.Constants.DefaultDateFormat) });
            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();

            // Update Parameters metadata values

            List<ParameterMetadataDetail> parameters = new List<ParameterMetadataDetail>();

            var paramData = from val in parameterMetadataList
                            group val by val.EntityName into param
                            select new
                            {
                                EntityName = param.Key,
                                Description = param.Select(q => (String.IsNullOrEmpty(q.EntityDescription) ? "" : q.EntityDescription)).FirstOrDefault(q => !String.IsNullOrEmpty(q)),
                                Values = param.ToList()
                            };

            foreach (var data in paramData)
            {
                parameters.Add(new ParameterMetadataDetail
                {
                    EntityName = data.EntityName,
                    EntityDescription = data.Description,
                    AttributeList = data.Values.Select(q => new ParameterAttribute { Name = q.Name, Description = q.Description, Type = q.Type, Units = q.Units }).ToList()

                });
            }

            queryData.ParameterMetadata = parameters.ToArray();

            return queryData;
        }
    }
}
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.