Source

main / Source / WebService / Web.Admin / Repositories / MerritRepository.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
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using DataUp.Web.Service.Model;
using System.Diagnostics;

namespace DataUp.Web.Admin
{
    public class MerritRepository : IRepository
    {
        private static string CurrentFileName = String.Empty;
        enum FileCreationType
        {
            ERC,
            EML,
            ManiFest
        }

        public string GetIdentifier(DQueryData queryData, DRepositoryBase repositoryModel)
        {
            DQueryData request = queryData;

            string requestBody = GetIdentifierRequestBody(request);

            HttpWebRequest httpRequest = (HttpWebRequest)HttpWebRequest.Create(repositoryModel.RepositoryUrl);
            httpRequest.ContentType = "multipart/form-data; boundary=" + Constants.Boundary;
            httpRequest.Method = "POST";
            byte[] buffer = Encoding.UTF8.GetBytes(requestBody);
            httpRequest.ContentLength = buffer.Length;
            httpRequest.Headers.Add("Authorization", "Basic " + repositoryModel.Authorization);

            HttpWebResponse httpResponse;
            Stream dataStream = null;
            StreamReader reader = null;
            string restResponse;

            try
            {
                dataStream = httpRequest.GetRequestStream();
                dataStream.Write(buffer, 0, buffer.Length);
                dataStream.Close();

                Trace.TraceInformation("Getting Response");

                httpResponse = (HttpWebResponse)httpRequest.GetResponse();

                Trace.TraceInformation("Received Response");
            }
            catch (WebException webException)
            {
                httpResponse = (HttpWebResponse)webException.Response;

                Trace.TraceInformation("Received WebException with Status Code :" + httpResponse.StatusCode);

                if (httpResponse.StatusCode == HttpStatusCode.Unauthorized)
                {
                    return "false|" + "The username or password you entered is incorrect.";
                }
                return "false|" + webException.Message;
            }

            if (httpResponse.StatusCode != HttpStatusCode.OK
                && httpResponse.StatusCode != HttpStatusCode.Unauthorized
                && httpResponse.StatusCode != HttpStatusCode.NotFound)
            {
                Trace.TraceInformation("Network exception occurred with Status Code : ." + httpResponse.StatusCode);

                return "false|Network Exception";
                //throw new FaultException<MerritResponseFault>(new MerritResponseFault() { Message = "Network Exception" });
            }

            Trace.TraceInformation("Getting response stream.");

            dataStream = httpResponse.GetResponseStream();
            reader = new StreamReader(dataStream);

            restResponse = reader.ReadToEnd();

            reader.Close();
            dataStream.Close();
            httpResponse.Close();

            // Get Identifier from the response.
            return "true|" + restResponse.Substring(restResponse.IndexOf("ark:")).Trim();
        }

        private string GetIdentifierRequestBody(DQueryData request)
        {
            StringBuilder body = new StringBuilder();

            // Update Profile.
            string m_szProfile = request["Profile"].Value;

            body.AppendLine("--" + Constants.Boundary);
            body.AppendLine("Content-disposition: form-data; name=\"profile\"");
            //body.AppendLine("Content-type: text/plain");

            body.AppendLine();
            body.AppendLine(m_szProfile);
            body.AppendLine("--" + Constants.Boundary);

            // Update ERC

            string _who = string.Format(CultureInfo.InvariantCulture, "{0}: {1}", request["Who"].Key, request["Who"].Value);
            string _what = string.Format(CultureInfo.InvariantCulture, "{0}: {1}", request["What"].Key, request["What"].Value);
            string _when = string.Format(CultureInfo.InvariantCulture, "{0}: {1}", request["When"].Key, request["When"].Value);

            string m_szErc = string.Format(CultureInfo.InvariantCulture, "{0}%0A{1}%0A{2}", _who, _what, _when);

            body.AppendLine("Content-disposition: form-data; name=\"erc\"");
            //body.AppendLine("Content-type: text/plain");
            body.AppendLine();
            body.AppendLine("erc: " + m_szErc);
            body.AppendLine("--" + Constants.Boundary + "--");

            return body.ToString();
        }

        public string PostFile(DQueryData queryData, DRepositoryBase repositoryModel, DFile file)
        {
            DQueryData request = queryData;
            Encoding encoding = Encoding.UTF8;

            string fileName = file.FileName.Trim();
            if (string.IsNullOrEmpty(fileName))
            {
                return "false|A non-empty file name is needed.";
                // throw new ArgumentOutOfRangeException("fileName", "A non-empty file name is needed.");
            }

            //Ensure there's no directory path in the file name
            fileName = Path.GetFileName(fileName);

            if (file.FileContent == null || file.FileContent.Length == 0)
            {
                return "false|File is empty.";
                // throw new FaultException<DocumentLengthFault>(DocumentLengthFault.FileEmpty(fileName));
            }
            //Set name of Current File
            CurrentFileName = Path.GetFileNameWithoutExtension(fileName);
            //create temporary directory to unzip the files and zip the files again
            string tempFolder = Constants.TempDownloadPath;
            Directory.CreateDirectory(tempFolder);

            DownloadFile(fileName, file.FileContent, file.FileExtentsion, file.isCompressed, tempFolder);

            try
            {
                // Create erc, eml and data-mainfest files
                CreateFile(FileCreationType.ManiFest, Path.Combine(tempFolder, Constants.MrtManifestFile), queryData, encoding);
                CreateFile(FileCreationType.ERC, Path.Combine(tempFolder, Constants.MrtErcFile), queryData, encoding);
                CreateFile(FileCreationType.EML, Path.Combine(tempFolder, Constants.MrtEmlFile), queryData, encoding);
            }
            catch (Exception)
            {
                // TODO: Need to Add exception handling logic. 
            }

            //actual zipping functionality will start here
            MemoryStream memoryStream = ZipUtilities.ZipFiles(tempFolder, "");
            memoryStream.Seek(0, SeekOrigin.Begin);

            byte[] byteArray = memoryStream.ToArray();

            string m_szProfile = request["Profile"].Value;
            string m_szArkIdentity = request["ARK"].Value;
            string m_szEmail = request["Creator: Email"].Value;

            Stream formDataStream = new System.IO.MemoryStream();

            string CRLF = "\r\n";
            string boundary = "--" + Constants.Boundary;

            StringBuilder body = new StringBuilder();
            body.AppendLine(boundary);
            body.AppendLine("Content-disposition: form-data; name=\"file\"; filename=\"" + Path.GetFileNameWithoutExtension(fileName) + ".zip\"");
            body.AppendLine("Content-type: application/zip");
            body.AppendLine();

            formDataStream.Write(encoding.GetBytes(body.ToString()), 0, encoding.GetByteCount(body.ToString()));
            formDataStream.Write(byteArray, 0, byteArray.Length);
            formDataStream.Write(encoding.GetBytes(CRLF), 0, encoding.GetByteCount(CRLF));

            body = new StringBuilder();
            body.AppendLine(boundary);
            body.AppendLine("Content-disposition: form-data; name=\"type\"");
            body.AppendLine();
            body.AppendLine("container");
            body.AppendLine(boundary);
            body.AppendLine("Content-disposition: form-data; name=\"profile\"");
            body.AppendLine();
            body.AppendLine(m_szProfile);

            body.AppendLine(boundary);
            body.AppendLine("Content-disposition: form-data; name=\"primary-identifier\"");
            body.AppendLine();
            body.AppendLine(m_szArkIdentity);
            body.AppendLine(boundary);
            body.AppendLine("Content-disposition: form-data; name=\"notification\"");
            body.AppendLine();
            if (string.IsNullOrWhiteSpace(m_szEmail))
            {
                body.AppendLine(Constants.AdminEmail);
            }
            else
            {
                body.AppendLine(m_szEmail);
            }
            body.AppendLine(boundary);

            body.AppendLine("Content-disposition: form-data; name=\"digestType\"");
            body.AppendLine();
            body.AppendLine("md5");
            body.AppendLine(boundary);

            body.AppendLine("Content-disposition: form-data; name=\"digestValue\"");
            body.AppendLine();
            body.AppendLine(GenerateCheckSum(byteArray));
            body.AppendLine(boundary);

            body.AppendLine("Content-disposition: form-data; name=\"responseForm\"");
            body.AppendLine();
            body.AppendLine("anvl"); //Not sure is this right value or not. stress test required
            body.AppendLine(boundary + "--");

            formDataStream.Write(encoding.GetBytes(body.ToString()), 0, encoding.GetByteCount(body.ToString()));
            formDataStream.Position = 0;

            HttpWebRequest httpRequest = (HttpWebRequest)HttpWebRequest.Create(repositoryModel.RepositoryUrl);

            httpRequest.ContentType = "multipart/form-data; boundary=" + Constants.Boundary;
            httpRequest.Method = "POST";
            httpRequest.Timeout = DataUp.Web.Common.Constants.PostFileTimeOutMinutes * 60 * 1000;
            byte[] buffer = new byte[formDataStream.Length];
            formDataStream.Read(buffer, 0, buffer.Length);
            formDataStream.Close();

            httpRequest.ContentLength = buffer.Length;
            httpRequest.Headers.Add("Authorization", "Basic " + repositoryModel.Authorization);

            HttpWebResponse httpResponse;
            Stream dataStream = null;
            StreamReader reader = null;
            string restResponse;

            dataStream = httpRequest.GetRequestStream();
            dataStream.Write(buffer, 0, buffer.Length);
            dataStream.Close();

            try
            {
                httpResponse = (HttpWebResponse)httpRequest.GetResponse();
            }
            catch (WebException webException)
            {
                httpResponse = (HttpWebResponse)webException.Response;

                if (httpResponse.StatusCode == HttpStatusCode.Unauthorized)
                {
                    return "false|" + "The username or password you entered is incorrect.";
                }
                return "false|" + webException.Message;
            }
            if (httpResponse.StatusCode != HttpStatusCode.OK
                && httpResponse.StatusCode != HttpStatusCode.Unauthorized
                && httpResponse.StatusCode != HttpStatusCode.NotFound)
            {
                return "false|Network Exception";
            }

            dataStream = httpResponse.GetResponseStream();
            reader = new StreamReader(dataStream);

            restResponse = reader.ReadToEnd();

            reader.Close();
            dataStream.Close();
            httpResponse.Close();

            return restResponse;
        }

        private static string GenerateCheckSum(byte[] byteArray)
        {
            StringBuilder checkSum = new StringBuilder();

            using (MD5 md5Hash = MD5.Create())
            {
                byte[] data = md5Hash.ComputeHash(byteArray);

                for (int i = 0; i < data.Length; i++)
                {
                    checkSum.Append(data[i].ToString("x2"));
                }
            }
            return checkSum.ToString();
        }

        private static void DownloadFile(string fileName, byte[] fileContents, string fileExtentsion, bool isCompressed, string tempFolder)
        {

            string tempFileName = fileName;

            bool isMultiCSVPassed = false;
            if (isCompressed)
            {
                switch (fileExtentsion.ToLower())
                {
                    case Constants.ZIP:
                        tempFileName = string.Format(CultureInfo.InvariantCulture, Constants.TempFileName, Constants.ZIP);
                        isMultiCSVPassed = true;
                        break;
                    case Constants.TAR:
                        tempFileName = string.Format(CultureInfo.InvariantCulture, Constants.TempFileName, Constants.TAR);
                        isMultiCSVPassed = true;
                        break;
                    case Constants.GZIP:
                        tempFileName = string.Format(CultureInfo.InvariantCulture, Constants.TempFileName, Constants.GZIP);
                        isMultiCSVPassed = true;
                        break;
                }
            }

            string filePath = Path.Combine(tempFolder, tempFileName);
            FileStream fs = File.Create(filePath);
            fs.Close();

            File.WriteAllBytes(filePath, fileContents);

            if (isMultiCSVPassed)
            {
                ZipUtilities.UnZipFiles(filePath, tempFolder, "", true);
                File.Delete(filePath);
            }
        }

        private static void CreateFile(FileCreationType file, string filePath, DQueryData request, Encoding encoding)
        {
            StringBuilder arguments = new StringBuilder();

            switch (file)
            {
                case FileCreationType.ManiFest:
                    arguments.AppendLine("#%dataonem_0.1");
                    arguments.AppendLine("#%profile | http://uc3.cdlib.org/registry/ingest/manifest/mrt-dataone- manifest");
                    arguments.AppendLine("#%prefix | dom: | http://uc3.cdlib.org/ontology/dataonem#");
                    arguments.AppendLine("#%prefix | mrt: | http://uc3.cdlib.org/ontology/mom#");
                    arguments.AppendLine("#%fields | dom:scienceMetadataFile | dom:scienceMetadataFormat | dom:scienceDataFile | mrt:mimeType");
                    ArrayList files = ZipUtilities.GenerateFileList(Path.GetDirectoryName(filePath));
                    foreach (string fileName in files)
                    {
                        var tempName = System.IO.Path.GetFileName(fileName);
                        arguments.AppendLine(Constants.MrtErcFile + " | ERC | " + tempName + " | text/plain");
                        arguments.AppendLine(Constants.MrtEmlFile + " | eml://ecoinformatics.org/eml-2.1.1 | " + tempName + " | text/xml");
                    }
                    arguments.AppendLine("#%eof");
                    break;
                case FileCreationType.ERC:
                    string _who = string.Format(CultureInfo.InvariantCulture, "{0}: {1}", request["who"].Key, request["who"].Value);
                    string _what = string.Format(CultureInfo.InvariantCulture, "{0}: {1}", request["what"].Key, request["what"].Value);
                    string _when = string.Format(CultureInfo.InvariantCulture, "{0}: {1}", request["when"].Key, request["when"].Value);
                    string _where = string.Format(CultureInfo.InvariantCulture, "{0}: {1}", request["where"].Key, request["where"].Value);

                    arguments.AppendLine("erc:");

                    arguments.AppendLine(_who);
                    arguments.AppendLine(_what);
                    arguments.AppendLine(_when);
                    arguments.AppendLine(_where);
                    break;
                case FileCreationType.EML:
                    WriteEML(request, filePath);
                    break;
            }

            using (FileStream fileStream = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite))
            {
                if (encoding != null)
                {
                    fileStream.Write(encoding.GetBytes(arguments.ToString()), 0, encoding.GetByteCount(arguments.ToString()));
                }
            }
        }

        private static void WriteEML(DQueryData request, string filePath)
        {
            string Newscientific = Constants.NewscientificMetadata;
            string DataUpmetada = Constants.DataUpMetadata;
            string DataUpmetadatadestpath = string.Empty;
            XmlDocument metadataDocument = new XmlDocument();
            XmlDocument emlDocument = new XmlDocument();
            if (File.Exists(Newscientific))
            {
                XmlTextReader reader = new XmlTextReader(Newscientific);
                metadataDocument.Load(reader);
                reader.Close();
            }
            else
            {
                string filepath = Constants.GetAppInstallationLocation();
                string newscientificpath = Path.Combine(filepath, "NewScientificMetadata.xml");
                XmlTextReader reader = new XmlTextReader(newscientificpath);
                metadataDocument.Load(reader);
                reader.Close();
            }

            if (File.Exists(DataUpmetada))
            {
                XmlTextReader reader1 = new XmlTextReader(DataUpmetada);
                emlDocument.Load(reader1);
                reader1.Close();
            }
            else
            {
                string filepath = Constants.GetAppInstallationLocation();
                DataUpmetadatadestpath = Path.Combine(filepath, "DataUpMetadata.xml");
                XmlTextReader reader1 = new XmlTextReader(DataUpmetadatadestpath);
                emlDocument.Load(reader1);
                reader1.Close();
            }

            XmlNamespaceManager nsmgr = new XmlNamespaceManager(emlDocument.NameTable);
            nsmgr.AddNamespace("eml", Constants.EmlNamespace);

            //XmlNodeList oldCd;
            XmlElement root = metadataDocument.DocumentElement;
            XmlNodeList oldCd = root.SelectNodes(Constants.Mapping);
            foreach (XmlNode node in oldCd)
            {
                string nodeField = node.SelectSingleNode("field").InnerText.Trim();
                string value = string.Empty;
                if (request.KeyValuePair.Where(kv => kv.Key == nodeField).Any())
                {
                    value = System.Security.SecurityElement.Escape(request.KeyValuePair.Where(kv => kv.Key == nodeField).Single().Value);
                }

                string serachNode = node.SelectSingleNode("mapping").InnerText.Trim();
                serachNode = serachNode.Replace('.', '/').Replace("eml", "");
                serachNode = "./" + serachNode;

                XmlElement root1 = emlDocument.DocumentElement;
                XmlNode oldNode = root1.SelectSingleNode(serachNode, nsmgr);
                if (oldNode != null)
                {
                    if (string.Compare(nodeField, "keyword(s)", true) == 0)
                    {
                        if (!string.IsNullOrWhiteSpace(value))
                        {
                            var keywords = value.Split(',');

                            var keywordSet = oldNode.ParentNode;
                            keywordSet.RemoveChild(oldNode);

                            foreach (var keyword in keywords)
                            {
                                var keywordNode = oldNode.Clone();
                                keywordNode.InnerText = keyword;

                                keywordSet.InsertBefore(keywordNode, keywordSet.LastChild);
                            }
                        }
                    }
                    else if (string.Compare(nodeField, "keyword thesaurus used", true) == 0 && string.IsNullOrWhiteSpace(value))
                    {
                        var keywordset = oldNode.ParentNode;
                        keywordset.RemoveChild(oldNode);
                    }
                    else
                    {
                        if (!string.IsNullOrWhiteSpace(value))
                        {
                            oldNode.InnerText = value;
                        }
                    }
                }
            }

            // Write Parameter Metadata properties.
            if (request.ParameterMetadata != null && request.ParameterMetadata.Length > 0)
            {
                WriteParamMetadata(request, emlDocument);
            }

            //Added this following conditions outside the above for loop to avoid the following conditions not to repeat every time
  
            //If contact element is not there, then insert the value from creator/surname
            ManageContactElement(emlDocument);

            //If no project title element ,then add the project title element value
            ManageProjectTitleElement(emlDocument);

            //If datatable has no entityname ,then add the entity name
            ManageEntityNameElement(emlDocument);

            //If datatable has no attributeList, then add attributeList node
            ManageAttributeListElement(emlDocument);

            //set the coordinate value for geographical location 
            ManageGeographicLocationCoordinates(emlDocument);
            
            //check the temporal coverage conidtions
            ManageTemporalCoverage(emlDocument);

            emlDocument.Save(filePath);
        }

        private static void ManageGeographicLocationCoordinates(XmlDocument emlDocument)
        {
            var rootElement = emlDocument.DocumentElement;
            var geographicDescElement = rootElement.SelectSingleNode(Constants.XPathDataSetGeoDesc);
            var boundingCoordinatesElement = rootElement.SelectSingleNode(Constants.XPathDataSetGeoCoordinates);

            if (geographicDescElement != null && boundingCoordinatesElement != null)
            {
                var westBoundingCoordinateElement = boundingCoordinatesElement.SelectSingleNode("westBoundingCoordinate");
                var eastBoundingCoordinateElement = boundingCoordinatesElement.SelectSingleNode("eastBoundingCoordinate");
                var northBoundingCoordinateElement = boundingCoordinatesElement.SelectSingleNode("northBoundingCoordinate");
                var southBoundingCoordinateElement = boundingCoordinatesElement.SelectSingleNode("southBoundingCoordinate");
                if (westBoundingCoordinateElement != null && string.IsNullOrWhiteSpace(westBoundingCoordinateElement.InnerText))
                {   
                    westBoundingCoordinateElement.InnerText = Constants.DefaultCoordinateValue;
                }
                if (eastBoundingCoordinateElement != null && string.IsNullOrWhiteSpace(eastBoundingCoordinateElement.InnerText))
                {
                    eastBoundingCoordinateElement.InnerText = Constants.DefaultCoordinateValue;
                }
                if (northBoundingCoordinateElement != null && string.IsNullOrWhiteSpace(northBoundingCoordinateElement.InnerText))
                {
                    northBoundingCoordinateElement.InnerText = Constants.DefaultCoordinateValue;
                }
                if (southBoundingCoordinateElement != null && string.IsNullOrWhiteSpace(southBoundingCoordinateElement.InnerText))
                {
                    southBoundingCoordinateElement.InnerText = Constants.DefaultCoordinateValue;
                }
            }
        }

        private static void ManageAttributeListElement(XmlDocument emlDocument)
        {
            var rootElement = emlDocument.DocumentElement;
            var dataTableElement = rootElement.SelectSingleNode(Constants.XPathDatasetDataTable);

            if (dataTableElement != null)
            {
                var attributeListElement = dataTableElement.SelectSingleNode("attributeList");
                if (attributeListElement == null)
                {
                    //create elements
                    attributeListElement = emlDocument.CreateElement("attributeList");

                    //set the attribute name node
                    var attributeNameElement = emlDocument.CreateElement("attributeName");
                    attributeNameElement.InnerText = Constants.MissingRequiredElement;

                    //set the attribute definition node
                    var attributeDefinitionElement = emlDocument.CreateElement("attributeDefinition");
                    attributeDefinitionElement.InnerText = Constants.MissingRequiredElement;

                    //set the measurement scale node
                    var measurementScaleElement = emlDocument.CreateElement("measurementScale");
                    var nominalElement = emlDocument.CreateElement("nominal");
                    var nonNumericDomainElement = emlDocument.CreateElement("nonNumericDomain");
                    var textDomainElement = emlDocument.CreateElement("textDomain");
                    var definitionElement = emlDocument.CreateElement("definition");
                    definitionElement.InnerText = Constants.MissingRequiredElement;

                    //add the measurement scale nodes
                    textDomainElement.AppendChild(definitionElement);
                    nonNumericDomainElement.AppendChild(textDomainElement);
                    nominalElement.AppendChild(nonNumericDomainElement);
                    measurementScaleElement.AppendChild(nominalElement);

                    //append the nodes to attribute list node
                    attributeListElement.AppendChild(attributeNameElement);
                    attributeListElement.AppendChild(attributeDefinitionElement);
                    attributeListElement.AppendChild(measurementScaleElement);

                    //add to the datatable node
                    dataTableElement.AppendChild(attributeListElement);
                }
            }
        }

        private static void ManageEntityNameElement(XmlDocument emlDocument)
        {
            var rootElement = emlDocument.DocumentElement;
            var dataTableElement = rootElement.SelectSingleNode(Constants.XPathDatasetDataTable);

            if (dataTableElement != null)
            {
                var entityNameElement = dataTableElement.SelectSingleNode("entityName");
                if (entityNameElement == null)
                {
                    entityNameElement = emlDocument.CreateElement("entityName");
                    entityNameElement.InnerText = Constants.MissingRequiredElement;
                    dataTableElement.AppendChild(entityNameElement);
                }
                else if (string.IsNullOrWhiteSpace(entityNameElement.InnerText))
                {
                    entityNameElement.InnerText = Constants.MissingRequiredElement;
                }
            }
        }

        private static void ManageProjectTitleElement(XmlDocument emlDocument)
        {
            var rootElement = emlDocument.DocumentElement;
            var projectElement = rootElement.SelectSingleNode(Constants.XPathDatasetProject);

            if (projectElement != null)
            {
                var titleElement = projectElement.SelectSingleNode("title");
                if (titleElement == null)
                {
                    titleElement = emlDocument.CreateElement("title");
                    titleElement.InnerText = Constants.MissingRequiredElement;
                    projectElement.AppendChild(titleElement);
                }
                else if (string.IsNullOrWhiteSpace(titleElement.InnerText))
                {
                    titleElement.InnerText = Constants.MissingRequiredElement;
                }
            }
        }

        private static void ManageContactElement(XmlDocument emlDocument)
        {
            var rootElement = emlDocument.DocumentElement;
            var datasetContactElement = rootElement.SelectSingleNode(Constants.XPathDatasetContact);

            if (datasetContactElement == null)//If contact element is not there as part of the dataset/contact add the dataset/contact/surname
            {
                var surNameValue = rootElement.SelectSingleNode(Constants.XPathDataSetSurName).InnerText;
                if (string.IsNullOrWhiteSpace(surNameValue))
                    surNameValue = "Create surname";

                var datasetElement = rootElement.SelectSingleNode("dataset");
                //create new xml elements
                var contactElement = emlDocument.CreateElement("contact");
                var individualElement = emlDocument.CreateElement("individualName");
                var surNameElement = emlDocument.CreateElement("surName");

                surNameElement.InnerText = surNameValue;

                individualElement.AppendChild(surNameElement);
                contactElement.AppendChild(individualElement);
                datasetElement.AppendChild(contactElement);
            }
        }

        private static void ManageTemporalCoverage(XmlDocument emlDocument)
        {
            var rootElement = emlDocument.DocumentElement;
            var temporalCoverageElement = rootElement.SelectSingleNode(Constants.XPathDataSetTemporalCoverage);
            var additionalMetadataElement = rootElement.SelectSingleNode("additionalMetadata");

            //If temp coverage element is not there and Additional meta data elemenet exists ,delete the describes node from AdditionalMetaData element
            if (temporalCoverageElement == null && additionalMetadataElement != null)
            {
                var describesElement = additionalMetadataElement.SelectSingleNode("describes");
                if (describesElement != null)
                {
                    additionalMetadataElement.RemoveChild(describesElement);
                }
            }
        }

        private static void RemoveEmptyElements(XmlDocument emlDocument)
        {
            var rootElement = emlDocument.DocumentElement;
            //rootElement.
        }

        private static void WriteParamMetadata(DQueryData request, XmlDocument emlDocument)
        {
            XmlNamespaceManager emlNamespaceMgr = new XmlNamespaceManager(emlDocument.NameTable);
            emlNamespaceMgr.AddNamespace("eml", Constants.EmlNamespace);

            XmlElement emlRoot = emlDocument.DocumentElement;

            XmlNode dataTableRef = emlRoot.SelectSingleNode(Constants.SheetTableXPath, emlNamespaceMgr);
            XmlNode parentDataTable = dataTableRef.ParentNode;
            List<string> standardUnits = GetStandardUnits();
            StringBuilder attibuteListBuilder;
            XElement scaleNode;
            foreach (var param in request.ParameterMetadata)
            {
                var sheetTable = dataTableRef.Clone();
                attibuteListBuilder = new StringBuilder();
                foreach (var attr in param.AttributeList)
                {
                    scaleNode = new XElement("measurementScale");
                    string units = string.IsNullOrWhiteSpace(attr.Units) ? string.Empty : attr.Units.Trim();
                    if (!string.IsNullOrWhiteSpace(attr.Type))
                    {
                        switch (attr.Type.ToLower())
                        {
                            case "text":
                                scaleNode = new XElement("measurementScale"
                                    , new XElement("nominal"
                                        , new XElement("nonNumericDomain"
                                            , new XElement("textDomain"
                                                , new XElement("definition", System.Security.SecurityElement.Escape(attr.Description))))));
                                break;
                            case "datetime":
                                scaleNode = new XElement("measurementScale"
                                    , new XElement("dateTime"
                                        , new XElement("formatString", "The user has designated this column as some form of date and/or time. No standard is specified due to DataUp coding constraints.")));
                                break;
                            case "numeric":
                                XElement unitsElement = new XElement("unit", new XElement("standardUnit", System.Security.SecurityElement.Escape(units)));
                                if (!string.IsNullOrWhiteSpace(units) && !standardUnits.Contains(units))
                                {
                                    unitsElement = new XElement("unit", new XElement("customUnit", System.Security.SecurityElement.Escape(units)));
                                }

                                scaleNode = new XElement("measurementScale"
                                    , new XElement("interval"
                                        , unitsElement
                                        , new XElement("numericDomain", new XElement("numberType", "real"))));
                                break;
                        }
                    }

                    var attibuteNode = new XElement("attribute"
                            , new XElement("attributeName", System.Security.SecurityElement.Escape(attr.Name))
                            , new XElement("attributeDefinition", System.Security.SecurityElement.Escape(attr.Description))
                            , scaleNode);

                    attibuteListBuilder.AppendLine(attibuteNode.ToString().Trim());
                }

                sheetTable.SelectSingleNode("entityName").InnerText = String.Format("{0} - {1}",System.Security.SecurityElement.Escape(CurrentFileName),System.Security.SecurityElement.Escape(param.EntityName));
                 sheetTable.SelectSingleNode("entityDescription").InnerText = System.Security.SecurityElement.Escape(param.EntityDescription);
                 sheetTable.SelectSingleNode("attributeList").InnerXml = attibuteListBuilder.ToString();

                 parentDataTable.InsertBefore(sheetTable, dataTableRef);
            }

            parentDataTable.RemoveChild(dataTableRef);
        }

        private static List<string> GetStandardUnits()
        {
            List<string> units = new List<string>() { };

            try
            {
                string standardUnitsPath = Constants.StandardUnitsPath;
                string[] metadataValue;

                if (File.Exists(standardUnitsPath))
                {
                    metadataValue = File.ReadAllLines(standardUnitsPath);
                }
                else
                {
                    string filepath = Constants.GetAppInstallationLocation();
                    string newscientificpath = Path.Combine(filepath, "StandardUnits.txt");

                    metadataValue = File.ReadAllLines(Path.Combine(filepath, "StandardUnits.txt"));
                }

                units = metadataValue.Select(p => p.Trim()).ToList();
            }
            catch
            {
                // Ignore.
            }

            return units;
        }
    }
}