/// <summary> /// Computes the lookup value for a Content Object /// </summary> /// <param name="de">DE Object</param> /// <param name="co">Content Object</param> /// <returns>Lookup Value</returns> public static int ComputeContentLookupID(DEv1_0 de, ContentObject co) { return(ComputeHash(new List <string>() { de.DistributionID, de.SenderID, co.ContentDescription })); }
public HttpResponseMessage Get(int lookupID) { try { DEv1_0 de1 = dbDal.ReadDE(lookupID); if (de1 != null) { return(Request.CreateResponse(HttpStatusCode.OK, de1)); } else { return(Request.CreateErrorResponse(HttpStatusCode.NotFound, "DE: " + lookupID.ToString() + " not found.")); } } catch (NpgsqlException e) { return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Database Error Occurred")); } catch (ArgumentException e) { return(Request.CreateErrorResponse(HttpStatusCode.NotFound, "DE: " + lookupID.ToString() + " not found.")); } catch (Exception e) { return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Error occurred when getting the DE with id: " + lookupID.ToString())); } }
/// <summary> /// Computes the hash value for a DE Object /// </summary> /// <param name="de">DE Object</param> /// <returns>Hash Value</returns> public static int ComputeDELookupID(DEv1_0 de) { return(ComputeHash(new List <string>() { de.DistributionID, de.SenderID })); }
/// <summary> /// Returns the Feed Content information for a content object /// </summary> /// <param name="de">Parent DE</param> /// <param name="co">Content Object</param> /// <returns>Feed Content Interface</returns> public static IFeedContent FeedContent(DEv1_0 de, ContentObject co) { IFeedContent myContent = null; XElement xmlContent = co.XMLContent.EmbeddedXMLContent[0]; //TODO: Fix this hack caused by fix to gml pos element name string contentString = xmlContent.ToString(); contentString = contentString.Replace("gml:Pos", "gml:pos"); var document = XDocument.Parse(contentString); xmlContent = document.Root; string deHash = DEUtilities.ComputeDELookupID(de).ToString(); //TODO: Update FeedContent method to support all supported standards //content is a SensorThings Observation //if (xmlContent.Name.LocalName.Equals("Observation", StringComparison.InvariantCultureIgnoreCase) && // xmlContent.Name.NamespaceName.Equals(EDXLSharp.MQTTSensorThingsLib.Constants.STApiNamespace, StringComparison.InvariantCultureIgnoreCase) ) //{ // XmlSerializer serializer = new XmlSerializer(typeof(Observation)); // Observation observation = (Observation)serializer.Deserialize(xmlContent.CreateReader()); // myContent = new STContent(observation, deHash); //} //content could be CoT or NIEM EMLC, need to check the namespace to know for sure if (xmlContent.Name.LocalName.Equals("event", StringComparison.InvariantCultureIgnoreCase)) { //content could be CoT or NIEM EMLC, need to check the namespace to know for sure //if (xmlContent.Name.NamespaceName.Equals(@"urn:cot:mitre:org", StringComparison.InvariantCultureIgnoreCase)) //{ // string cotString = xmlContent.ToString(); // //remove namespace or CoTLibrary blows up // //brute force method // int index, end, len; // index = cotString.IndexOf("xmlns="); // while (index != -1) // { // end = cotString.IndexOf('"', index); // end++; // end = cotString.IndexOf('"', end); // end++; // len = end - index; // cotString = cotString.Remove(index, len); // index = cotString.IndexOf("xmlns="); // } // CoT_Library.CotEvent anEvent = new CoT_Library.CotEvent(cotString); // CoTContent mCC = new CoTContent(anEvent, deHash); // myContent = mCC; //} if (xmlContent.Name.NamespaceName.Equals(@"http://release.niem.gov/niem/domains/emergencyManagement/3.1/emevent/0.1/emlc/", StringComparison.InvariantCultureIgnoreCase)) { XmlSerializer serializer = new XmlSerializer(typeof(Event)); Event emlc = (Event)serializer.Deserialize(xmlContent.CreateReader()); myContent = new EMLCContent(emlc, deHash); } } return(myContent); }
/// <summary> /// Determines the overall expiration time of a DE. This looks at the ContentObjects' ExpiresTimes. /// If none of them are set, 1 day from the DE time sent is used. /// </summary> /// <param name="de">The DE</param> /// <returns>The expiration time.</returns> public static DateTime GetDEExpiresTime(DEv1_0 de) { if (de.ExpiresDateTime.HasValue) { return(de.ExpiresDateTime.Value.ToUniversalTime()); } else { return(de.DateTimeSent.AddDays(1).ToUniversalTime()); } }
private void FederateDE(DEv1_0 de, List <string> fedUris) { //TODO:figure out how to federate all DE foreach (string uri in fedUris) { // Federating the URL only if its valid if (IsValid(uri)) { Task.Run(() => DoPost(new Uri(uri), de)); } } }
/// <summary> /// Vaidates the DE message. /// </summary> /// <remarks> /// A DE is invalid if it is null or does not include a senderID, distID, and DateTime sent. /// </remarks> /// <param name="de"></param> /// <returns>True if the DE is valid, False otherwise</returns> public static bool ValidateDE(DEv1_0 de, out string validationError) { validationError = null; bool isSuccess = false; try { if (de == null) { throw new ArgumentNullException("The DE object was null"); } if (string.IsNullOrWhiteSpace(de.DistributionID)) { validationError = "DistributionID must be included and have a valid value"; return(isSuccess); } if (string.IsNullOrWhiteSpace(de.SenderID)) { validationError = "SenderID must be included and have a valid value"; return(isSuccess); } try { if (de.DateTimeSent == null) { validationError = "DateTimeSent must be included and have a valid value"; return(isSuccess); } } catch (Exception e) { validationError = "DateTimeSent must be included and have a valid value"; return(isSuccess); } isSuccess = true; } catch (ArgumentNullException e) { validationError = "The DE could not be read."; return(isSuccess); } catch (Exception e) { validationError = "The DE was invalid."; return(isSuccess); } return(isSuccess); }
/// <summary> /// Creates the De object /// </summary> /// <returns>Status code for the post. Returns -1 if there was an exception</returns> /// <param name="lat">Lat.</param> /// <param name="lon">Lon.</param> /// <param name="name">Name.</param> /// <param name="agency">Agency.</param> /// <param name="postURL">Post URL.</param> /// <param name="resourceType">Resource type.</param> /// <param name="eventDetails">Event details.</param> public static async Task sendUpdate(double lat, double lon, string name, string agency, string postURL, string resourceType, List <EventDetails> eventDetails) { try { // Creating DE DEv1_0 de = new DEv1_0(); de.ContentObjects = new List <EMS.EDXL.DE.ContentObject>(); de.DistributionID = name; de.DateTimeSent = DateTime.Now; de.DistributionStatus = StatusValue.Test; de.DistributionType = TypeValue.Update; de.CombinedConfidentiality = "Unclassified"; // Creating Event Event newEvent = new Event(); newEvent.EventTypeDescriptor = new EventTypeDescriptor(); newEvent.EventLocation = new EventLocation(); newEvent.EventLocation.LocationCylinder = new LocationCylinder(); newEvent.EventLocation.LocationCylinder.LocationPoint = new LocationPoint(); newEvent.EventLocation.LocationCylinder.LocationPoint.Point = new Point(); newEvent.EventID = de.DistributionID; de.SenderID = name + "." + agency + "@watchtower"; newEvent.EventTypeDescriptor.EventTypeCode = resourceType; newEvent.Details = eventDetails; newEvent.EventMessageDateTime = DateTime.Now; newEvent.EventValidityDateTimeRange.StartDate = DateTime.Now; newEvent.EventValidityDateTimeRange.EndDate = DateTime.Now.AddMinutes(30); newEvent.EventLocation.LocationCylinder.LocationPoint.Point.Lat = lat; newEvent.EventLocation.LocationCylinder.LocationPoint.Point.Lon = lon; Debug.WriteLine(newEvent.ToString()); // Serializing Event to XML XElement xml = XElement.Parse(newEvent.ToString()); // Adding the Event to DE as a content object 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, postURL); } catch (Exception e) { // log } }
/// <summary> /// Archives a DE Message /// </summary> /// <param name="de">DE message to archive</param> /// <param name="sourceip">Source IP Address of the message</param> public bool ArchiveDE(DEv1_0 de, string sourceip) { bool wasSuccessful = false; NpgsqlCommand command = null; NpgsqlTransaction sqlTrans = null; NpgsqlConnection currentConnection = null; try { currentConnection = GetDatabaseConnection(); if (OpenConnection(currentConnection) == false) { return(wasSuccessful); } sqlTrans = currentConnection.BeginTransaction(); command = currentConnection.CreateCommand(); command.Transaction = sqlTrans; //add DE first //assumes calling function will wrap this in a try catch block //allows the error to be thrown to the calling function int iHash = DEUtilities.ComputeDELookupID(de); string sTable = QualifiedTableName(TableNames.MessageArchive); string sColumns = MessageArchiveColumns.DELookupID + "," + MessageArchiveColumns.DistributionID + "," + MessageArchiveColumns.SenderID + "," + MessageArchiveColumns.DateTimeSent + "," + MessageArchiveColumns.SenderIP + "," + MessageArchiveColumns.DateTimeLogged + "," + MessageArchiveColumns.DE; command.CommandText = "INSERT INTO " + sTable + " (" + sColumns + ") VALUES (@DEHash, @DistributionID, @SenderID, @DateTimeSent, @SourceIP, @DateTimeLogged, @DEv1_0)"; command.Parameters.Clear(); AddParameter(command, NpgsqlDbType.Integer, "DEHash", iHash); AddParameter(command, NpgsqlDbType.Text, "DistributionID", de.DistributionID); AddParameter(command, NpgsqlDbType.Text, "SenderID", de.SenderID); AddParameter(command, NpgsqlDbType.TimestampTZ, "DateTimeSent", de.DateTimeSent); AddParameter(command, NpgsqlDbType.Text, "SourceIP", sourceip); AddParameter(command, NpgsqlDbType.TimestampTZ, "DateTimeLogged", DateTime.UtcNow); AddParameter(command, NpgsqlDbType.Xml, "DEv1_0", de.ToString()); Log.Debug(command.CommandText); command.ExecuteNonQuery(); sqlTrans.Commit(); wasSuccessful = true; } catch (Exception Ex) { Log.Error("General Error in AddedDEToCache()", Ex); this.WasRolledBackTransaction(sqlTrans); } finally { CloseConnection(currentConnection); } return(wasSuccessful); }
/// <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); }
public ActionResult GetEnhancedDetails(int id) { DEv1_0 de = dbDal.ReadDE(id); ContentObject co = de.ContentObjects[0]; EMLCContent evtHelper = (EMLCContent)DEUtilities.FeedContent(de, co); string addr = DEUtilities.ReverseGeocodeLookup(evtHelper.Location().Latitude.ToString(), evtHelper.Location().Longitude.ToString()); DE_Details_ViewModel vm = new DE_Details_ViewModel(evtHelper, addr, de.DateTimeSent); // return partial view, not full view return(PartialView("DE_View_partial", vm)); }
/// <summary> /// Determines the overall expiration time of a DE. This looks at the ContentObjects' ExpiresTimes. /// If none of them are set, 1 day from the DE time sent is used. /// </summary> /// <param name="de">The DE</param> /// <param name="co">Content Object</param> /// <returns>The expiration time.</returns> public static DateTime GetContentObjectExpiresTime(DEv1_0 de, ContentObject co) { DateTime coexpires; if (co.ExpiresTime.HasValue) { coexpires = co.ExpiresTime.Value; } else { coexpires = de.DateTimeSent.AddDays(1.0); } return(coexpires.ToUniversalTime()); }
public IHttpActionResult FederationRequest([FromBody] FederationRequestDTO federationRequest) { // If the request is null if (federationRequest == null) { logger.Warn("Empty federation request"); return(Content(HttpStatusCode.BadRequest, "Empty federation request")); } logger.Debug(string.Format("Received Federation Request: {0}", federationRequest.ToXMLString())); DEv1_0 de = DEUtilities.DeserializeDE(federationRequest.DEXMLElement.ToString()); FederateDE(de, federationRequest.FedURIs); return(this.StatusCode(HttpStatusCode.Accepted)); }
/// <summary> /// Returns the expiration time of a content object /// </summary> /// <param name="de">Parent DE</param> /// <param name="co">Content Object</param> /// <returns>Expiration time</returns> public static DateTime?GetExpirationTime(DEv1_0 de, ContentObject co) { IFeedContent myContent = FeedContent(de, co); DateTime? expires = null; if (myContent != null) { expires = myContent.Expires(); } if (!expires.HasValue) { expires = de.DateTimeSent.AddDays(1.0); } return(expires); }
public HttpResponseMessage Validate([FromBody] DEv1_0 value) { List <string> errorList = null; try { Log.Debug("Checking if DE Message is valid"); string xml = value.ToString(); // Validates DE portion of message and writes to xml bool isValid = Fresh.Global.DEUtilities.ValidateNiemSchema(xml, out errorList); if (isValid) { DEUtilities.LogMessage("The message is valid", DEUtilities.LogLevel.Info); return(Request.CreateResponse(HttpStatusCode.OK, "Message is valid")); } else { DEUtilities.LogMessage("The message was not valid", DEUtilities.LogLevel.Info); string schemaErrorString = ""; foreach (string er in errorList) { schemaErrorString = schemaErrorString + er + "\n"; } return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, "The DE was invalid: " + schemaErrorString)); } } catch (IOException Ex) { return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "The schema files could not be read")); } catch (FormatException Ex) { return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "The schema files could not be parsed")); } catch (Exception Ex) { return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "The message could not be validated")); } }
/// <summary> /// Sends the given de message /// </summary> /// <param name="de">De.</param> /// <param name="url">URL.</param> public static async Task sendMessage(DEv1_0 de, string url) { try { XmlSerializer x = new XmlSerializer(de.GetType()); XmlWriterSettings xsettings = new XmlWriterSettings(); xsettings.Indent = true; xsettings.OmitXmlDeclaration = true; string str; using (var stream = new StringWriter()) using (var writer = XmlWriter.Create(stream, xsettings)) { x.Serialize(writer, de); str = stream.ToString(); } byte[] bytes = Encoding.UTF8.GetBytes(str); System.IO.MemoryStream ms = new MemoryStream(bytes); HttpContent stringContent = new StreamContent(ms); stringContent.Headers.Add("charset", "utf-8"); stringContent.Headers.Add("Content-type", "application/xml"); HttpClient client = new HttpClient(); HttpResponseMessage response = await client.PostAsync( url, stringContent); Debug.WriteLine($"\n\n\nresponse status code is {response.StatusCode}\n\n\n"); } catch (Exception ex) { //Message failed to sen Debug.WriteLine("failed to send message"); Debug.WriteLine($"{ex.Message}"); } }
private void sendTimer_Tick(object sender, ElapsedEventArgs e) { this.sendTimer.Stop(); DEv1_0 de = new DEv1_0(); de.CombinedConfidentiality = "U"; de.DateTimeSent = DateTime.UtcNow; de.DistributionID = PinPointConfig.UnitID; de.SenderID = "*****@*****.**"; de.DistributionReference.Add(PinPointConfig.UnitID + "," + de.SenderID + ",1753-01-01T00:00:00.0000000Z"); de.DistributionStatus = StatusValue.Actual; de.DistributionType = TypeValue.Update; de.Language = "en-US"; Event emlc = new Event(); emlc.EventID = PinPointConfig.UnitID; LocationCylinder loc = new LocationCylinder(); loc.CodeValue = gpsManager.CurrentLocation.CodeValue; loc.LocationCylinderHalfHeightValue = -99999; loc.LocationCylinderRadiusValue = -99999; loc.LocationPoint.Point.Height = gpsManager.CurrentLocation.LocationPoint.Point.Height; loc.LocationPoint.Point.Lat = gpsManager.CurrentLocation.LocationPoint.Point.Lat; loc.LocationPoint.Point.Lon = gpsManager.CurrentLocation.LocationPoint.Point.Lon; loc.LocationPoint.Point.srsName = "http://metadata.ces.mil/mdr/ns/GSIP/crs/WGS84E_3D"; emlc.EventLocation.LocationCylinder = loc; emlc.EventMessageDateTime = DateTime.UtcNow; emlc.EventTypeDescriptor.CodeValue = (EventTypeCodeList)Enum.Parse(typeof(EventTypeCodeList), PinPointConfig.UnitType); emlc.EventTypeDescriptor.EventTypeDescriptorExtension.Add(emlc.EventTypeDescriptor.CodeValue.ToString().Replace("_", ".")); emlc.EventValidityDateTimeRange.StartDate = emlc.EventMessageDateTime; emlc.EventValidityDateTimeRange.EndDate = emlc.EventMessageDateTime.AddMinutes(30); ResourceDetail resourceDetail = new ResourceDetail(); resourceDetail.Status = new ResourceStatus(); TextStatus textStatus = new TextStatus(); textStatus.Description = "Foo"; textStatus.SourceID = "VA.LCFR"; resourceDetail.Status.SecondaryStatus = new List <AltStatus>(); resourceDetail.Status.SecondaryStatus.Add(textStatus); //Log.Info(@"Type: " + unitStatus + " and the file is at " + UNITSTATPATH); resourceDetail.setPrimaryStatus(ResourcePrimaryStatusCodeList.Available); emlc.Details = resourceDetail; List <string> keywords = new List <string>(); keywords.Add("PinPoint AvL"); keywords.Add(PinPointConfig.UnitID); keywords.Add(emlc.EventTypeDescriptor.CodeValue.ToString().Replace("_", ".")); ContentObject co = new ContentObject("http://edxlsharp.codeplex.com/ValueLists/ContentKeywords", keywords); co.XMLContent = new XMLContentType(); co.XMLContent.EmbeddedXMLContent = new List <XElement>(); string str = emlc.ToString(); XElement xe = XElement.Parse(str); co.XMLContent.AddEmbeddedXML(xe); co.ContentDescription = "PinPoint AvL"; de.ContentObjects.Add(co); XmlSerializer x = new XmlSerializer(de.GetType()); XmlWriterSettings xsettings = new XmlWriterSettings(); xsettings.Indent = true; xsettings.OmitXmlDeclaration = true; using (var stream = new StringWriter()) using (var writer = XmlWriter.Create(stream, xsettings)) { x.Serialize(writer, de); str = stream.ToString(); } HttpWebRequest request; HttpWebResponse resp; //WebProxy proxy; string requesturi = PinPointConfig.PostURL; request = (HttpWebRequest)WebRequest.Create(requesturi); request.KeepAlive = true; request.Method = "POST"; request.ContentType = "text/xml"; request.AllowAutoRedirect = true; request.ContentLength = Encoding.UTF8.GetByteCount(str); /*if (!String.IsNullOrWhiteSpace(proxyHostName) && !String.IsNullOrWhiteSpace(proxyPort)) * { * proxy = new WebProxy(); * proxy.Address = new Uri("http://" + proxyHostName + ":" + proxyPort); * if (!string.IsNullOrWhiteSpace(proxyUsername) && !string.IsNullOrEmpty(proxyPassword)) * { * proxy.Credentials = new NetworkCredential(proxyUsername, proxyPassword); * } * request.Proxy = proxy; * }*/ try { SetBody(request, str); resp = (HttpWebResponse)request.GetResponse(); resp.Close(); } catch (Exception ex) { log.Error("Error in HTTPSender: " + ex.ToString()); } OnSent(EventArgs.Empty); this.sendTimer.Start(); }
/// <summary> /// Forwards the DE to another webserver. /// </summary> /// <param name="requesturi">The location to where the DE should be forwarded.</param> /// <param name="distributionElement">The DE to be forwarded</param> private void DoPost(Uri requesturi, DEv1_0 distributionElement) { int numRetries = 0; bool deliveryFailed = false; do { logger.Debug(string.Format("Attempting to federate the message to {0}. This is the attempt #{1}", requesturi, numRetries + 1)); if (deliveryFailed) { Thread.Sleep(1000 * 5); deliveryFailed = false; } try { HttpWebRequest request; string s = distributionElement.ToString(); s = s.Replace("<?xml version=\"1.0\" encoding=\"utf-16\" standalone=\"no\"?>\r\n", String.Empty); request = (HttpWebRequest)WebRequest.Create(requesturi); //request.Timeout = 7000; request.KeepAlive = true; request.Method = "POST"; request.ContentType = "text/xml"; request.AllowAutoRedirect = true; request.ContentLength = Encoding.UTF8.GetByteCount(s); logger.Debug("The Post requesturi is: " + requesturi.ToString()); // HACK HACKITY HACK HACK HACK if (requesturi.ToString() == "https://c2crouter.nics.ll.mit.edu/api/de") { ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; X509Certificate2 clientCert = new X509Certificate2("C:\\public\\ArdentAWS.pfx", "ArdentAWS"); request.ClientCertificates.Add(clientCert); request.PreAuthenticate = true; request.Credentials = CredentialCache.DefaultCredentials; request.CachePolicy = new RequestCachePolicy(RequestCacheLevel.NoCacheNoStore); } this.SetBody(request, s); HttpWebResponse resp = (HttpWebResponse)request.GetResponse(); resp.Close(); } catch (WebException e) { deliveryFailed = true; logger.Info("TLS Info: " + System.Net.ServicePointManager.SecurityProtocol.ToString()); logger.Error("Error POSTing to " + requesturi + ": " + e.Message); logger.Error("Stacktrace: " + e.StackTrace); logger.Error("Err: " + e.ToString()); if (e.InnerException != null) { logger.Error("Inner: " + e.InnerException.Message); } logger.Error("NumRetries: " + numRetries); } }while (deliveryFailed && (numRetries++ < federationConnectionRetryAttempts)); // If the message was never able to be delivered successfully, add it to the unreachable URI map if (deliveryFailed) { //TODO: Change this to add hour 1 after testing unreachableURI.Add(requesturi.ToString(), DateTime.Now.AddHours(1)); logger.Error("Failed to federate message to " + requesturi.ToString()); } else { logger.Debug("Message was federated successfully to " + requesturi.ToString()); } }
/// <summary> /// Base method, writes to stream /// </summary> /// <param name="type">type of object to write</param> /// <param name="value">object to write</param> /// <param name="writeStream">stream to write to</param> /// <param name="content">stuff</param> public override void WriteToStream(Type type, object value, Stream writeStream, HttpContent content) { DEv1_0 de = value as DEv1_0; Event evt = null; try { if (de != null) { ContentObject co = de.ContentObjects[0]; EMLCContent evtHelper = (EMLCContent)DEUtilities.FeedContent(de, co); var settings = new XmlWriterSettings(); settings.Indent = false; settings.OmitXmlDeclaration = false; XmlWriter writer = XmlWriter.Create(writeStream, settings); writer.WriteStartElement("html"); //html writer.WriteStartElement("head"); //head writer.WriteStartElement("meta"); writer.WriteAttributeString("charset", "UTF-8"); // We're returning some DE-related HTML, so set up the page to refresh every 5 seconds // This is not a good way to do it long term. //writer.WriteAttributeString("http-equiv", "refresh"); //string contentValue = $"5; URL={HttpContext.Current.Request.Url}"; //writer.WriteAttributeString("content", contentValue); writer.WriteEndElement(); //meta writer.WriteElementString("title", "TEST"); writer.WriteEndElement(); //head writer.WriteStartElement("body"); //start body writer.WriteStartElement("div"); //start div 1 writer.WriteAttributeString("style", "background-color:black;color:white;padding:5px;"); #region table writer.WriteStartElement("table"); //start table writer.WriteAttributeString("style", "color:white;"); #region row 1 writer.WriteStartElement("tr"); //start row writer.WriteStartElement("td"); //start cell writer.WriteAttributeString("style", "padding:15px;"); writer.WriteStartElement("img"); //start image writer.WriteAttributeString("src", evtHelper.IconURL()); writer.WriteAttributeString("alt", evtHelper.FriendlyName()); writer.WriteEndElement(); //end image writer.WriteEndElement(); //end cell writer.WriteStartElement("td"); //start cell writer.WriteElementString("h1", evtHelper.Title()); writer.WriteEndElement(); //end cell writer.WriteEndElement(); //end row #endregion row 1 #region row 2 writer.WriteStartElement("tr"); //start row writer.WriteStartElement("td"); //start cell writer.WriteAttributeString("colspan", "2"); writer.WriteValue(evtHelper.FriendlyName()); writer.WriteEndElement(); //end cell writer.WriteEndElement(); //end row #endregion row 2 writer.WriteEndElement(); //end table #endregion table writer.WriteEndElement(); //end div 1 // Loop through each kind of details and append HTML for each one if (evtHelper.ResourceDetails != null) { foreach (ResourceDetail rd in evtHelper.ResourceDetails) { string sColor = "color:black"; writer.WriteStartElement("p"); //start paragraph writer.WriteAttributeString("style", sColor); if (rd.Status.PrimaryStatus == ResourcePrimaryStatusCodeList.Available) { sColor = "color:green"; } else if (rd.Status.PrimaryStatus == ResourcePrimaryStatusCodeList.ConditionallyAvailable) { sColor = "color:yellow"; } else if (rd.Status.PrimaryStatus == ResourcePrimaryStatusCodeList.NotAvailable) { sColor = "color:red"; } writer.WriteElementString("p", "Latitude/Longitude: " + evtHelper.Location().Latitude.ToString() + ", " + evtHelper.Location().Longitude.ToString()); //writer.WriteElementString("p", "Lon: " + evtHelper.Location().Latitude.ToString()); string addr = DEUtilities.ReverseGeocodeLookup(evtHelper.Location().Latitude.ToString(), evtHelper.Location().Longitude.ToString()); if (string.IsNullOrWhiteSpace(addr)) { addr = "Not Found"; } writer.WriteElementString("p", "Address: " + addr); //+ some reverse lookup; writer.WriteRaw("Primary Status: <span style=\"font-weight:bold;" + sColor + "\"> " + rd.Status.PrimaryStatus.ToString() + "</ span>" + " "); writer.WriteEndElement(); //end paragraph } } if (evtHelper.IncidentDetails != null) { foreach (IncidentDetail id in evtHelper.IncidentDetails) { string sColor = "color:black"; writer.WriteStartElement("p"); //start paragraph writer.WriteAttributeString("style", sColor); if (id.Status.PrimaryStatus == IncidentPrimaryStatusCodeList.Active) { sColor = "color:green"; } else if (id.Status.PrimaryStatus == IncidentPrimaryStatusCodeList.Pending) { sColor = "color:orange"; } string addr = "Not Found"; writer.WriteElementString("p", "Latitude/Longitude: " + evtHelper.Location().Latitude.ToString() + ", " + evtHelper.Location().Longitude.ToString()); if (id.LocationExtension != null && id.LocationExtension.Address != null) { addr = id.LocationExtension.Address.ToString(); } else { //writer.WriteElementString("p", "Lon: " + evtHelper.Location().Latitude.ToString()); addr = DEUtilities.ReverseGeocodeLookup(evtHelper.Location().Latitude.ToString(), evtHelper.Location().Longitude.ToString()); if (string.IsNullOrWhiteSpace(addr)) { addr = "Not Found"; } } writer.WriteElementString("p", "Address: " + addr); //+ some reverse lookup; writer.WriteRaw("Primary Status: <span style=\"font-weight:bold;" + sColor + "\"> " + id.Status.PrimaryStatus.ToString() + "</ span>" + " "); writer.WriteEndElement(); //end paragraph } } if (evtHelper.SensorDetails != null) { foreach (SensorDetail sensor in evtHelper.SensorDetails) { string sColor = "color:black;"; writer.WriteStartElement("p"); //start paragraph writer.WriteAttributeString("style", sColor); writer.WriteRaw("Sensor ID: " + sensor.ID + " "); writer.WriteEndElement(); //end paragraph writer.WriteStartElement("p"); //start paragraph writer.WriteAttributeString("style", sColor); if (sensor.Status == SensorStatusCodeList.Normal) { sColor = "color:green"; } else if (sensor.Status == SensorStatusCodeList.LowPower) { sColor = "color:orange"; } else if (sensor.Status == SensorStatusCodeList.Error) { sColor = "color:red"; } else if (sensor.Status == SensorStatusCodeList.Sleeping) { sColor = "color:gray"; } writer.WriteRaw("Primary Status: <span style=\"font-weight:bold;" + sColor + "\"> " + sensor.Status.ToString() + "</ span>" + " "); writer.WriteEndElement(); //end paragraph //assumes at least one item of device details is present if (sensor.DeviceDetails != null) { CreateSensorDeviceInfo(writer, sensor.DeviceDetails); } if (sensor.PowerDetails != null) { CreateSensorPowerInfo(writer, sensor.PowerDetails); } if (sensor.PhysiologicalDetails != null) { CreateSensorPhysiologicalInfo(writer, sensor.PhysiologicalDetails); } if (sensor.EnvironmentalDetails != null) { CreateSensorEnvironmentalInfo(writer, sensor.EnvironmentalDetails); } if (sensor.LocationDetails != null) { CreateSensorLocationInfo(writer, sensor.LocationDetails); } } } writer.WriteEndElement(); //end body writer.WriteEndElement(); //end html writer.Flush(); writer.Close(); } } catch (Exception e) { DEUtilities.LogMessage("An error occurred when trying to parse the DE", DEUtilities.LogLevel.Error); CreateErrorInfo(writeStream); } }
public HttpResponseMessage Post([FromBody] DEv1_0 value) { // Not a Valid DE Message if (value == null) { return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, "The message was not a valid format. The DE could not be created")); } string erMsg; if (DEUtilities.ValidateDE(value, out erMsg) == false) { return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, erMsg)); } // Getting DE lookup ID int deID = DEUtilities.ComputeDELookupID(value); if (value.DistributionType == TypeValue.Update) { return(Put(deID, value)); } else if (value.DistributionType == TypeValue.Cancel) { if (this.ArchiveEnabled) { string clientAddress = HttpContext.Current.Request.UserHostAddress; archiveDal.ArchiveDE(value, clientAddress); } return(Delete(deID)); } else if (value.DistributionType == TypeValue.Report) { try { if (dbDal.CreatedDE(value, out deID)) { DELiteDTO retVal = new DELiteDTO(); retVal.LookupID = deID; retVal.DateTimeSent = value.DateTimeSent; retVal.DistributionID = value.DistributionID; retVal.SenderID = value.SenderID; this.CreatedAtRoute("GetSingleDERule", new { lookupID = deID }, value); if (this.ArchiveEnabled) { string clientAddress = HttpContext.Current.Request.UserHostAddress; archiveDal.ArchiveDE(value, clientAddress); } return(Request.CreateResponse(HttpStatusCode.Created, retVal)); } else { // something went wrong return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "The DE could not be created")); } } catch (ArgumentNullException e) { return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, "The DE was invalid")); } catch (NpgsqlException e) { return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Database error occurred")); } catch (FederationException e) { return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Error occurred when federating the DE")); } catch (Exception e) { return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Error occurred when adding the DE")); } } else { return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Unsupported DE Distribution Type Found")); } }
public HttpResponseMessage Put(int lookupID, [FromBody] DEv1_0 value) { string errMsg; // Holds error message //--- Validating the DE if (DEUtilities.ValidateDE(value, out errMsg) == false) { return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, errMsg)); } //--- Checking if Update or Add // If false we are creating a DE. If true, this is an update. bool deExists; try { deExists = dbDal.DEExists(value); if (deExists) { DEUtilities.LogMessage(string.Format("The DE with lookupID {0} exists. This is an update.", lookupID), DEUtilities.LogLevel.Debug); } else { DEUtilities.LogMessage(string.Format("The DE with lookupID {0} does not exist. We are adding a new DE.", lookupID), DEUtilities.LogLevel.Debug); } } catch (NpgsqlException e) { return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Database error occurred.")); } catch (Exception e) { return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Error occurred when validating the request.")); } try { bool wasSuccessful = dbDal.PutDE(value); // If the operation was a success if (wasSuccessful) { if (this.ArchiveEnabled) { string clientAddress = HttpContext.Current.Request.UserHostAddress; archiveDal.ArchiveDE(value, clientAddress); } // If this was an update if (deExists) { return(Request.CreateResponse(HttpStatusCode.OK, "Success")); } else // If this was an add { HttpResponseMessage msg = Request.CreateResponse(HttpStatusCode.Created, value); // Getting location for new DE string location = "" + HttpContext.Current.Request.Url; if (!(location.Contains("" + lookupID))) { location = location.TrimEnd('/') + "/" + lookupID; } msg.Headers.Location = new Uri(location); return(msg); } } else // If the operation failed { // If this was an update if (deExists) { errMsg = "Error occurred when updating the DE"; } else // If this was an add { errMsg = "Error occurred when adding the DE"; } return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, errMsg)); } } catch (NpgsqlException e) { return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Database error occurred")); } catch (InvalidOperationException e) { if (deExists) { return(Request.CreateErrorResponse(HttpStatusCode.Conflict, "This was not a valid update. Make sure the updated DE message is valid and the most recent update.")); } else { return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Failed to add the DE")); } } catch (FederationException e) { return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Error occurred when federating the DE")); } catch (Exception e) { return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Failed to add the DE")); } }