Example #1
0
        public void Resource_Extraction()
        {
            ResourceDetail ri = ExtractResource(Subjects.One, "BitDiffer.Tests.Subject.ResourceA.txt");

            Assert.AreEqual(Status.Present, ri.Status);
            Assert.AreEqual("5A555A09783EBF2C664B570A8367C151CD05C010", ri.ToString());
        }
Example #2
0
        public void Resource_Changed()
        {
            ResourceDetail ri1 = ExtractResource(Subjects.One, "BitDiffer.Tests.Subject.ResourceB.txt");
            ResourceDetail ri2 = ExtractResource(Subjects.Two, "BitDiffer.Tests.Subject.ResourceB.txt");

            Assert.AreEqual(ChangeType.ContentChanged, ri1.PerformCompare(ri2));
        }
Example #3
0
        public ResponseBase Init(IList <string> urls, IList <AuthenticatedUrl> urlsWithAuthentification = null)
        {
            Log.Information("Starting the download process");
            if (urlsWithAuthentification == null)
            {
                urlsWithAuthentification = new List <AuthenticatedUrl>();
            }
            Log.Information("List of URLs passed down : " + string.Join(";", urls));
            Log.Information("List of URLs requiring authentication passed down : " + string.Join(";", urlsWithAuthentification));

            var responseInit = _initializeDonwload.InitConfigData();

            if (responseInit.Denied)
            {
                Log.Fatal("Could not retrieve config");
                var failResponse = new ResponseBase()
                {
                    Denied = true
                };
                failResponse.AddListMessage(responseInit.Messages);
            }
            _configurationSetting = responseInit.ReturnedValue;
            //Prepare the file to be downloaded extract the protocol Type
            _resourceDetails = ResourceDetail.FromListUrl(urls, urlsWithAuthentification).ToList();
            return(new ResponseBase()
            {
                Denied = false
            });
        }
Example #4
0
        public ResponseBase <Stream> CreateStream(ResourceDetail rl, long initialPosition, long endPosition)
        {
            try {
                FtpWebRequest request = (FtpWebRequest)GetRequest(rl);
                FillCredentials(request, rl);

                request.UsePassive = true;
                //request.Timeout = -1;
                request.Method        = WebRequestMethods.Ftp.DownloadFile;
                request.ContentOffset = initialPosition;

                WebResponse response       = request.GetResponse();
                var         responseStream = response.GetResponseStream();
                return(new ResponseBase <Stream>()
                {
                    ReturnedValue = responseStream, Denied = false
                });
            }
            catch (Exception ex)
            {
                Serilog.Log.Error(ex, "An exception was raised in Createstream.cs ");

                while (ex.InnerException != null)
                {
                    ex = ex.InnerException;
                }
                var responseFailed = new ResponseBase <Stream>()
                {
                    Denied = true
                };
                responseFailed.Messages.Add(ex.Message);
                return(responseFailed);
            }
        }
Example #5
0
        public RemoteFileDetail GetFileInfo(ResourceDetail rl)
        {
            FtpWebRequest    request;
            RemoteFileDetail result = new RemoteFileDetail();

            result.AcceptRanges = true;



            request = (FtpWebRequest)GetRequest(rl);

            request.UsePassive = true;
            request.Timeout    = 500000;
            request.Method     = WebRequestMethods.Ftp.GetFileSize;
            FillCredentials(request, rl);

            using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
            {
                result.FileSize = response.ContentLength;
            }

            request        = (FtpWebRequest)GetRequest(rl);
            request.Method = WebRequestMethods.Ftp.GetDateTimestamp;
            FillCredentials(request, rl);

            using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
            {
                result.LastModified = response.LastModified;
            }

            return(result);
        }
Example #6
0
        private void PostUpdates()
        {
            // Getting values from preferences
            string deviceInfo = Android.OS.Build.Model;

            // Log
            Log.Debug(TAG, "Foreground updating");
            Log.Debug(TAG, "Device info: " + deviceInfo);
            Log.Debug(TAG, "Post url: " + AppConfig.PostUrl);

            // Getting lat/lon
            Location location = LocationServices.FusedLocationApi.GetLastLocation(apiClient);
            double   lat      = location.Latitude;
            double   lon      = location.Longitude;

            // Getting the resource detail
            ResourceDetail det = HTTPSender.createResourceDetail(AppConfig.UserID, AppConfig.Agency);

            List <EventDetails> detailsList = new List <EventDetails>();

            detailsList.Add(det);

            if (sensorDetailMap.Count > 0)
            {
                Log.Debug(TAG, "Adding Sensor Details");
                detailsList.AddRange(sensorDetailMap.Values.ToList());
            }

            HTTPSender.sendUpdate(lat, lon, AppConfig.UserID, AppConfig.Agency, AppConfig.PostUrl, AppConfig.SelectedResource, detailsList);
        }
Example #7
0
 public void MergeFrom(EntryPointResponse other)
 {
     if (other == null)
     {
         return;
     }
     if (other.LighthouseId.Length != 0)
     {
         LighthouseId = other.LighthouseId;
     }
     if (other.ForceUpdate != false)
     {
         ForceUpdate = other.ForceUpdate;
     }
     if (other.resourceDetail_ != null)
     {
         if (resourceDetail_ == null)
         {
             ResourceDetail = new global::gen.msg.VersionDetail();
         }
         ResourceDetail.MergeFrom(other.ResourceDetail);
     }
     if (other.Maintenance != false)
     {
         Maintenance = other.Maintenance;
     }
     if (other.RedirectURL.Length != 0)
     {
         RedirectURL = other.RedirectURL;
     }
     _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
 }
Example #8
0
        public void Change_DifferentTypes()
        {
            ResourceDetail r1 = new ResourceDetail(null, "test", new byte[0]);
            StubDetail     s1 = new StubDetail("x1", null, Visibility.Public);

            r1.PerformCompare(s1);
        }
Example #9
0
        protected WebRequest GetRequest(ResourceDetail location)
        {
            WebRequest request = WebRequest.Create(location.Url);

            request.Timeout = 90000;
            return(request);
        }
        public ResponseBase <RemoteFileDetail> GetFileInfo(ResourceDetail rl)
        {
            try
            {
                HttpWebRequest request = (HttpWebRequest)GetRequest(rl);
                //request.Timeout = 100000;

                HttpWebResponse  response = (HttpWebResponse)request.GetResponse();
                RemoteFileDetail result   = new RemoteFileDetail
                {
                    MimeType     = response.ContentType,
                    LastModified = response.LastModified,
                    FileSize     = response.ContentLength,
                    AcceptRanges = Compare(response.Headers["Accept-Ranges"], "bytes", StringComparison.OrdinalIgnoreCase) == 0
                };
                return(new ResponseBase <RemoteFileDetail>()
                {
                    Denied = false, ReturnedValue = result
                });
            }
            catch (Exception ex)
            {
                while (ex.InnerException != null)
                {
                    ex = ex.InnerException;
                }
                Serilog.Log.Error(ex, "---Could not get remote file information trial number");
                var responseFailed = new ResponseBase <RemoteFileDetail>()
                {
                    Denied = true
                };
                responseFailed.AddMessage(ex.Message);
                return(responseFailed);
            }
        }
Example #11
0
        public override int GetHashCode()
        {
            int hash = 1;

            if (LighthouseId.Length != 0)
            {
                hash ^= LighthouseId.GetHashCode();
            }
            if (ForceUpdate != false)
            {
                hash ^= ForceUpdate.GetHashCode();
            }
            if (resourceDetail_ != null)
            {
                hash ^= ResourceDetail.GetHashCode();
            }
            if (Maintenance != false)
            {
                hash ^= Maintenance.GetHashCode();
            }
            if (RedirectURL.Length != 0)
            {
                hash ^= RedirectURL.GetHashCode();
            }
            if (_unknownFields != null)
            {
                hash ^= _unknownFields.GetHashCode();
            }
            return(hash);
        }
Example #12
0
 /// <summary>
 /// Refresh database context, open time and close time of resources.
 /// </summary>
 public static void RefreshContext()
 {
     EssResources      = Resource.LoadList();
     EssResourceDetail = ResourceDetail.LoadList();
     OpenTime          = Convert.ToDateTime((from c in EssResources select c.BookingOpenFrom).Min()).TimeOfDay;
     CloseTime         = Convert.ToDateTime((from c in EssResources select c.BookingOpenTo).Max()).TimeOfDay;
 }
Example #13
0
        /// <summary>
        /// Return a description from this Event
        /// </summary>
        /// <returns>Description</returns>
        public string Description()
        {
            string retVal = "Emergency Management Event";

            if (myEvent != null)
            {
                List <AltStatus> secondaryStatus = null;

                if (myEvent.Details != null && // we have details
                    myEvent.Details.Count == 1 && // there is only one details object
                    myEvent.Details[0].GetType() == typeof(ResourceDetail)) // and it is a Resource Detail
                {
                    ResourceDetail resourceDetail = (ResourceDetail)myEvent.Details[0];

                    if (resourceDetail.Status.SecondaryStatus != null && // secondary status isn't null
                        resourceDetail.Status.SecondaryStatus.Count > 0) // and secondary status acually has content
                    {
                        secondaryStatus = resourceDetail.Status.SecondaryStatus;
                    }
                }

                if (secondaryStatus != null) /* the only case this is not null is if
                                              * a) There is a single ResourceDetail object present in the Event's Details list, and
                                              * b) That ResourceDetail object has a non-null SecondaryStatus with at least one object.
                                              *
                                              * If those conditions are met, we want to use the secondary status for the description.
                                              * Otherwise, just use EventTypeDescriptor as before.*/
                {
                    StringBuilder sb = new StringBuilder();

                    secondaryStatus.ForEach(ss => sb.Append(ss.GetSecondaryStatusText() + ", "));

                    if (sb.Length > 0)
                    {
                        // remove last ", "
                        sb.Length -= 2;
                    }

                    retVal = sb.ToString();
                }
                else if (myEvent.EventTypeDescriptor != null)
                {
                    if (myEvent.EventTypeDescriptor.EventTypeDescriptorExtension != null && myEvent.EventTypeDescriptor.EventTypeDescriptorExtension.Count > 0)
                    {
                        retVal = "";
                        foreach (string ext in myEvent.EventTypeDescriptor.EventTypeDescriptorExtension)
                        {
                            retVal = retVal + ext + " ";
                        }
                    }
                    else
                    {
                        retVal = myEvent.EventTypeDescriptor.EventTypeCode;
                    }
                }
            }

            return(retVal);
        }
Example #14
0
        /// <summary>
        /// Creates the resource detail with the given name
        /// </summary>
        /// <returns>The resource detail.</returns>
        /// <param name="name">Name.</param>
        /// <param name="agency">Agency</param>
        public static ResourceDetail createResourceDetail(string name, string agency)
        {
            ResourceDetail resource = new ResourceDetail();

            resource.Status = new ResourceStatus();
            resource.setPrimaryStatus(ResourcePrimaryStatusCodeList.Available);

            resource.OwningOrg            = new ResourceOrganization();
            resource.OwningOrg.ResourceID = name;
            resource.OwningOrg.OrgID      = agency;

            return(resource);
        }
Example #15
0
        /// <summary>
        /// Sends the location.
        /// </summary>
        /// <returns>The location.</returns>
        /// <param name="lat">Lat.</param>
        /// <param name="lon">Lon.</param>
        /// <param name="url">URL.</param>
        /// <param name="name">Name.</param>
        /// <param name="agency">Agency.</param>
        /// <param name="resourceType">Resource type.</param>
        /// <param name="eventDetails">Event details.</param>
        public static async Task SendLocation(double lat, double lon, string url, string name, string agency, string resourceType, List <EventDetails> eventDetails)
        {
            DEv1_0         de       = new DEv1_0();
            Event          newEvent = new Event();
            ResourceDetail resource = new ResourceDetail();

            resource.Status = new ResourceStatus();
            //resource.Status.SecondaryStatus = new List<AltStatus>();
            resource.setPrimaryStatus(ResourcePrimaryStatusCodeList.Available);
            resource.OwningOrg            = new ResourceOrganization();
            resource.OwningOrg.ResourceID = name;
            // resource.AddSecondaryStatusText("Test", "001");
            newEvent.EventTypeDescriptor = new EventTypeDescriptor();
            newEvent.EventTypeDescriptor.EventTypeCode = resourceType;
            //EventTypeCodeList.ATOM_GRDTRK_EQT_GRDVEH_CVLVEH_EM_EMS_AMBULANCE.ToString();
            de.SenderID                = name + "." + agency + "@watchtower";
            de.DistributionID          = name;
            de.DateTimeSent            = DateTime.Now;
            de.DistributionStatus      = StatusValue.Test;
            de.DistributionType        = TypeValue.Update;
            de.CombinedConfidentiality = "Unclassified";

            // add resource details at beginning
            eventDetails.Insert(0, resource);
            newEvent.Details = eventDetails;
            newEvent.EventID = de.DistributionID;
            newEvent.EventMessageDateTime = DateTime.Now;
            newEvent.EventValidityDateTimeRange.StartDate = DateTime.Now;
            newEvent.EventValidityDateTimeRange.EndDate   = DateTime.Now.AddMinutes(30);

            newEvent.EventLocation = new EventLocation();
            newEvent.EventLocation.LocationCylinder = new LocationCylinder();
            newEvent.EventLocation.LocationCylinder.LocationPoint           = new LocationPoint();
            newEvent.EventLocation.LocationCylinder.LocationPoint.Point     = new Point();
            newEvent.EventLocation.LocationCylinder.LocationPoint.Point.Lat = lat;
            newEvent.EventLocation.LocationCylinder.LocationPoint.Point.Lon = lon;


            de.ContentObjects = new List <EMS.EDXL.DE.ContentObject>();

            //Debug.WriteLine(newEvent.ToString());

            XElement xml = XElement.Parse(newEvent.ToString());

            EMS.EDXL.DE.ContentObject co = new EMS.EDXL.DE.ContentObject();
            co.XMLContent = new XMLContentType();
            co.XMLContent.AddEmbeddedXML(xml);
            de.ContentObjects.Add(co);

            await sendMessage(de, url);
        }
Example #16
0
        public ResponseBase <RemoteFileDetail> GetFileInfo(ResourceDetail rl)
        {
            try {
                FtpWebRequest    request;
                RemoteFileDetail result = new RemoteFileDetail();
                result.AcceptRanges = true;



                request = (FtpWebRequest)GetRequest(rl);

                request.UsePassive = true;
                //request.Timeout = 500000;
                request.Method = WebRequestMethods.Ftp.GetFileSize;
                FillCredentials(request, rl);

                using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
                {
                    result.FileSize = response.ContentLength;
                }

                request        = (FtpWebRequest)GetRequest(rl);
                request.Method = WebRequestMethods.Ftp.GetDateTimestamp;
                FillCredentials(request, rl);

                using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
                {
                    result.LastModified = response.LastModified;
                }

                return(new ResponseBase <RemoteFileDetail>()
                {
                    Denied = false, ReturnedValue = result
                });
            }
            catch (Exception ex)
            {
                while (ex.InnerException != null)
                {
                    ex = ex.InnerException;
                }
                var responseFailed = new ResponseBase <RemoteFileDetail>()
                {
                    Denied = true
                };
                responseFailed.Messages.Add(ex.Message);
                return(responseFailed);
            }
        }
Example #17
0
 public async Task <IdReply> AddResourceDetail(ResourceDetailDto resourceDetailDto)
 {
     using (var authContext = GetContext())
     {
         var ns = new ResourceDetail
         {
             Description = resourceDetailDto.Description,
             Key         = resourceDetailDto.Key,
             ResourceId  = resourceDetailDto.ResourceId
         };
         authContext.ResourceDetails.Add(ns);
         authContext.SaveChanges();
         return(IdReply.Success(ns.Id));
     }
 }
Example #18
0
        public Stream CreateStream(ResourceDetail rl, long initialPosition, long endPosition)
        {
            FtpWebRequest request = (FtpWebRequest)GetRequest(rl);

            FillCredentials(request, rl);

            request.UsePassive    = true;
            request.Timeout       = -1;
            request.Method        = WebRequestMethods.Ftp.DownloadFile;
            request.ContentOffset = initialPosition;

            WebResponse response = request.GetResponse();

            return(response.GetResponseStream());
        }
        public void Init()
        {
            //these 2 urls are well knwon resource for testing
            _resourceDetailFtp = new ResourceDetail()
            {
                Url = "ftp://speedtest.tele2.net/1MB.zip"
            };

            _resourceDetailhttp = new ResourceDetail()
            {
                Url = "http://httpbin.org/robots.txt"
            };

            _ftpProtocolDownlaoder  = new FtpProtocolDownloader();
            _httpProtocolDownlaoder = new HttpProtocolDownloader();
        }
Example #20
0
        protected WebRequest GetRequest(ResourceDetail location)
        {
            WebRequest request = WebRequest.Create(location.Url);

            int timeout;
            var conversion = int.TryParse(ConfigurationManager.AppSettings["Timeout"], out timeout);

            if (!conversion)
            {
                Serilog.Log.Error("Could not Fetch timeout from config");
                var response = new ResponseBase()
                {
                    Denied = true,
                };
                response.Messages.Add("Could not Fetch timeout from config");
            }
            request.Timeout = timeout;
            return(request);
        }
Example #21
0
        public virtual RemoteFileDetail GetFileInfo(ResourceDetail rl)
        {
            HttpWebRequest request = (HttpWebRequest)GetRequest(rl);

            request.Timeout = 100000;
            FillCredentials(request, rl);

            HttpWebResponse  response = (HttpWebResponse)request.GetResponse();
            RemoteFileDetail result   = new RemoteFileDetail
            {
                MimeType     = response.ContentType,
                LastModified = response.LastModified,
                FileSize     = response.ContentLength,
                AcceptRanges =
                    Compare(response.Headers["Accept-Ranges"], "bytes", StringComparison.OrdinalIgnoreCase) == 0
            };


            return(result);
        }
        public ResponseBase <Stream> CreateStream(ResourceDetail rl, long initialPosition, long endPosition)
        {
            try
            {
                HttpWebRequest request = (HttpWebRequest)GetRequest(rl);
                //request.Timeout = 100000;

                if (initialPosition != 0)
                {
                    if (endPosition == 0)
                    {
                        request.AddRange((int)initialPosition);
                    }
                    else
                    {
                        request.AddRange((int)initialPosition, (int)endPosition);
                    }
                }

                var response       = request.GetResponse();
                var responseStream = response.GetResponseStream();
                return(new ResponseBase <Stream>()
                {
                    Denied = false, ReturnedValue = responseStream
                });
            }
            catch (Exception ex)
            {
                Serilog.Log.Error(ex, "An exception was raised in Createstream.cs ");
                while (ex.InnerException != null)
                {
                    ex = ex.InnerException;
                }
                var responseFailed = new ResponseBase <Stream>()
                {
                    Denied = true
                };
                responseFailed.Messages.Add(ex.Message);
                return(responseFailed);
            }
        }
Example #23
0
    public void ButtonClick(int index)
    {
        //reset position of event
        GameObject.FindGameObjectWithTag("Event").GetComponent <RectTransform>().position = new Vector3(512f, -20, 0);
        choice1.gameObject.SetActive(true);
        choice2.gameObject.SetActive(true);

        //quick and dirty resource updating from event
        ResourceDetail resourceUpdate = activeEvent.getOption(index).ResourceEffects;

        this.resources = this.resources + resourceUpdate;

        //unpause
        timer.Start();

        // hack to get by update calling multiple events per hour
        hour++;

        // restart loop
        eventActive = false;
    }
Example #24
0
        private void FillCredentials(FtpWebRequest request, ResourceDetail rl)
        {
            if (rl.Authenticate)
            {
                string login  = rl.Login;
                string domain = string.Empty;

                int slashIndex = login.IndexOf('\\');

                if (slashIndex >= 0)
                {
                    domain = login.Substring(0, slashIndex);
                    login  = login.Substring(slashIndex + 1);
                }

                NetworkCredential myCred = new NetworkCredential(login, rl.Password);
                myCred.Domain = domain;

                request.Credentials = myCred;
            }
        }
Example #25
0
        /// <summary>
        /// find all declared resources and add them to the db.
        /// </summary>
        private void SeedResources()
        {
            var assembly = Assembly.GetEntryAssembly();
            var attribs  = assembly.GetTypes()
                           .SelectMany(type => type.GetMembers())
                           .Union(assembly.GetTypes())
                           .Where(type => Attribute.IsDefined(type, typeof(ResourcePermissionAttribute)));

            foreach (var memberInfo in attribs)
            {
                var permResource = memberInfo.GetCustomAttribute <ResourcePermissionAttribute>();

                var resource = _authDbContext.Resources.FirstOrDefault(c => c.Key == permResource.ResourceKey);
                if (resource == null)
                {
                    resource = new Resource
                    {
                        Key         = permResource.ResourceKey,
                        Description = permResource.ResourceKey
                    };
                    _authDbContext.Resources.Add(resource);
                }

                var resourceDetail = _authDbContext.ResourceDetails.FirstOrDefault(c =>
                                                                                   c.ResourceId == resource.Id && c.Key == permResource.ResourceDetailKey);

                if (resourceDetail == null)
                {
                    resourceDetail = new ResourceDetail()
                    {
                        Key         = permResource.ResourceDetailKey,
                        Description = permResource.ResourceDetailKey,
                        ResourceId  = resource.Id
                    };
                    _authDbContext.ResourceDetails.Add(resourceDetail);
                }

                _authDbContext.SaveChanges();
            }
        }
Example #26
0
        public void IsDownloadFailsAfterMaxRetries()
        {
            var configSetting = new ConfigurationSetting()
            {
                NumberOfTrial    = 10,
                LocalFilePath    = "C:\\temp",
                MinSizeSegment   = 200000,
                RetrialDelay     = 10,
                NumberOfSegments = 5,
                Timeout          = -1,
                LogFilePath      = "C:\\temp\\log.txt"
            };
            var rd = new ResourceDetail()
            {
                Url = "http://testutl.example/file.txt"
            };
            FileDownloader fileDownloader = new FileDownloader(_mockSegementProcessorDownloadSegmentRetries.Object, _mockProtcolDownloadSegmentRetries.Object, new InitializeDownload());
            ResponseBase   response       = fileDownloader.StartDownload(rd, configSetting);

            Assert.IsTrue(response.Denied);
            _mockSegementProcessorDownloadSegmentRetries.Verify(m => m.ProcessSegment(It.IsAny <ResourceDetail>(), It.IsAny <IProtocolDownloader>(), It.IsAny <Segment>()));
        }
        public ActionResult ResourceDetailAdd(AdminResourceDetailViewModel model)
        {
            if (!IsLoggedIn)
            {
                return(RedirectToAction("Index"));
            }

            var rd = new ResourceDetail
            {
                Title            = model.Title,
                Description      = model.Description,
                ShortDescription = model.ShortDescription,
                OpeningHours     = model.OpeningHours,
                Address          = model.Address,
                Language         = Db.Languages.Single(l => l.ID == model.LanguageID),
                Resource         = Db.Resources.Single(c => c.ID == model.ResourceID)
            };

            Db.ResourceDetails.Add(rd);
            Db.SaveChanges();
            return(RedirectToAction("ResourceDetail", new { id = model.ResourceID }));
        }
Example #28
0
        public virtual Stream CreateStream(ResourceDetail rl, long initialPosition, long endPosition)
        {
            HttpWebRequest request = (HttpWebRequest)GetRequest(rl);

            request.Timeout = 100000;
            FillCredentials(request, rl);

            if (initialPosition != 0)
            {
                if (endPosition == 0)
                {
                    request.AddRange((int)initialPosition);
                }
                else
                {
                    request.AddRange((int)initialPosition, (int)endPosition);
                }
            }

            WebResponse response = request.GetResponse();

            return(response.GetResponseStream());
        }
Example #29
0
        private EventDetails CreateResourceDetail(XmlNode node, ResourceDetail resource)
        {
            resource.Status = new ResourceStatus();
            resource.Status.SecondaryStatus = new List <AltStatus>(0);
            resource.ControllingOrg         = new ResourceOrganization();
            XmlNodeList resourceDetailNodes = node.ChildNodes;

            foreach (XmlNode childNode in resourceDetailNodes)
            {
                XmlNodeList statusNodes = childNode.ChildNodes;
                if (string.IsNullOrEmpty(childNode.InnerText))
                {
                    continue;
                }
                switch (childNode.LocalName)
                {
                case "ResourceStatus":
                    foreach (XmlNode statusNode in statusNodes)
                    {
                        if (string.IsNullOrEmpty(statusNode.InnerText))
                        {
                            continue;
                        }
                        switch (statusNode.LocalName)
                        {
                        case "ResourcePrimaryStatus":
                            ResourcePrimaryStatusCodeList outputPrim = GetCode <ResourcePrimaryStatusCodeList>(statusNode.InnerText);
                            resource.Status.PrimaryStatus = outputPrim;
                            break;

                        case "ResouceEIDDStatus":
                            ResourceEIDDStatusCodeList outputEEID = GetCode <ResourceEIDDStatusCodeList>(statusNode.InnerText);
                            resource.AddEIDDStatus(outputEEID);
                            break;

                        case "ResourceUCADStatus":
                            ResourceUCADStatusCodeList outputUCAD = GetCode <ResourceUCADStatusCodeList>(statusNode.InnerText);
                            resource.AddUCADStatus(outputUCAD);
                            break;

                        case "ResourceSecondaryTextStatus":
                            resource.AddSecondaryStatusText(statusNode.InnerText, "Freetext");
                            break;

                        default:
                            throw new ArgumentException("Unexpected Node Name: " + statusNode.Name + " in NIEM Resource Status");
                        }
                    }
                    break;


                case "ResourceOwningOrganization":
                    resource.OwningOrg = new ResourceOrganization();
                    foreach (XmlNode orgNode in childNode.ChildNodes)
                    {
                        switch (orgNode.LocalName)
                        {
                        case "OrganizationIdentification":
                            resource.OwningOrg.OrgID = orgNode.InnerText;
                            break;

                        case "ResourceIdentifier":
                            resource.OwningOrg.ResourceID = orgNode.InnerText;
                            break;

                        default:
                            throw new ArgumentException("Unexpected Node Name: " + childNode.Name + " in NIEM Owning Organization");
                        }
                    }
                    break;

                case "ResourceControllingOrganization":
                    foreach (XmlNode orgNode in childNode.ChildNodes)
                    {
                        switch (orgNode.LocalName)
                        {
                        case "OrganizationIdentification":
                            resource.OwningOrg.OrgID = orgNode.InnerText;
                            break;

                        case "ResourceIdentifier":
                            resource.OwningOrg.ResourceID = orgNode.InnerText;
                            break;

                        default:
                            throw new ArgumentException("Unexpected Node Name: " + childNode.Name + " in NIEM Owning Organization");
                        }
                    }
                    break;

                default:
                    throw new ArgumentException("Unexpected Node Name: " + childNode.Name + " in NIEM Event");
                }
            }
            return(resource);
        }
Example #30
0
        /// <summary>
        /// Reads in the xml
        /// </summary>
        /// <param name="xmlData">Xml as string</param>
        public void ReadXML(string xmlData)
        {
            if (string.IsNullOrEmpty(xmlData))
            {
                throw new ArgumentNullException("XMLData Can't Be Null!");
            }

            XmlDocument doc = new XmlDocument();

            try
            {
                doc.LoadXml(xmlData);
            }
            catch (XmlException)
            {
                throw new ArgumentException("Invalid XML String");
            }

            XmlNodeList denodelist = doc.GetElementsByTagName("Event", Constants.EmlcNamespace);

            if (denodelist.Count == 0)
            {
                throw new FormatException("No Event Element found!");
            }
            else if (denodelist.Count > 1)
            {
                throw new FormatException("Multiple Event Elements found!");
            }

            XmlNode deroot = denodelist[0];

            foreach (XmlNode node in deroot.ChildNodes)
            {
                if (string.IsNullOrEmpty(node.InnerText))
                {
                    continue;
                }

                switch (node.LocalName)
                {
                case "EventID":
                    this.EventID = node.InnerText;
                    break;

                case "EventTypeDescriptor":
                    EventTypeDescriptor.EventTypeCode = new ValueList(doc.GetElementsByTagName("EventTypeCode", Constants.EmeventNamespace)[0]);
                    //this.EventTypeDescriptor.SerialEventTypeCode = doc.GetElementsByTagName("EventTypeCode", Constants.EmeventNamespace)[0];//.InnerText; // 1/11/2017 changed property to "SerialEventTypeCode"
                    // to be consistent with LinkedEventCategory....should it be "EventTypeCode",
                    // or will XML be updated to be "SerialEventTypeCode"?
                    this.EventTypeDescriptor.EventTypeDescriptorExtension = new List <string>(0);
                    XmlNodeList extensions = doc.GetElementsByTagName("EventTypeDescriptorExtension", Constants.EmeventNamespace);
                    foreach (XmlNode extension in extensions)
                    {
                        this.EventTypeDescriptor.EventTypeDescriptorExtension.Add(extension.InnerText);
                    }
                    break;

                case "EventLocation":
                    this.EventLocation.LocationCylinder = new LocationCylinder();
                    this.EventLocation.LocationCylinder.LocationPoint               = new LocationPoint();
                    this.EventLocation.LocationCylinder.LocationPoint.Point         = new Point();
                    this.EventLocation.LocationCylinder.LocationPoint.Point.pos     = doc.GetElementsByTagName("Point", Constants.GmlNamespace)[0].InnerText;
                    this.EventLocation.LocationCylinder.LocationCylinderRadiusValue = decimal.Parse(doc.GetElementsByTagName("LocationCylinderRadiusValue", Constants.MofNamespace)[0].InnerText);
                    this.EventLocation.LocationCylinder.LocationCreationCode        = doc.GetElementsByTagName("LocationCreationCode", Constants.MofNamespace)[0].InnerText;
                    break;

                case "EventValidityDateTimeRange":
                    this.EventValidityDateTimeRange           = new EventValidityDateTimeRange();
                    this.EventValidityDateTimeRange.StartDate = Convert.ToDateTime(doc.GetElementsByTagName("StartDate", Constants.NiemcoreNamespace)[0].InnerText);
                    this.EventValidityDateTimeRange.EndDate   = Convert.ToDateTime(doc.GetElementsByTagName("EndDate", Constants.NiemcoreNamespace)[0].InnerText);
                    break;

                case "EventComment":
                    EventComment newComment     = new EventComment();
                    XmlNodeList  commentContent = node.ChildNodes;
                    foreach (XmlNode childNode in commentContent)
                    {
                        if (string.IsNullOrEmpty(childNode.InnerText))
                        {
                            continue;
                        }
                        switch (childNode.LocalName)
                        {
                        case "DateTime":
                            newComment.DateTime = Convert.ToDateTime(childNode.InnerText);
                            break;

                        case "CommentText":
                            newComment.CommentText = childNode.InnerText;
                            break;

                        case "OrganizationIdentification":
                            newComment.OrganizationIdentification = childNode.InnerText;
                            break;

                        case "PersonHumanResourceIdentification":
                            newComment.PersonHumanResourceIdentification = childNode.InnerText;
                            break;

                        default:
                            throw new ArgumentException("Unexpected Node Name: " + childNode.Name + " in NIEM Event Comment");
                        }
                    }
                    this.EventComment.Add(newComment);
                    break;

                case "EventMessageDateTime":
                    this.EventMessageDateTime = Convert.ToDateTime(node.FirstChild.InnerXml);
                    break;

                case "ResourceDetail":
                    ResourceDetail resource = new ResourceDetail();
                    this.Details = CreateResourceDetail(node, resource);
                    break;

                case "IncidentDetail":
                    IncidentDetail incident = new IncidentDetail();
                    this.Details = CreateIncidentDetail(node, incident);
                    break;

                case "InfrastructureDetail":
                    throw new NotImplementedException("ReadXML for " + node.Name + " not implemented yet");

                default:
                    throw new ArgumentException("Unexpected Node Name: " + node.Name + " in NIEM Event");
                }
            }
        }