/EntLib/CE.WebServiceClient.DRHub/DRHubClient.cs
C# | 947 lines | 720 code | 136 blank | 91 comment | 55 complexity | cef5466f1b324ba15bb97f7376975088 MD5 | raw file
- using CE.ContentModel;
- using CE.ContentModel.ContentCache;
- using CE.NotificationManager.Entities;
- using Newtonsoft.Json.Linq;
- using System;
- using System.Collections.Generic;
- using System.Configuration;
- using System.Data;
- using System.Data.SqlClient;
- using System.IO;
- using System.Linq;
- using System.Net;
- using System.Net.Http;
- using System.Net.Http.Headers;
- using System.Text;
- using System.Threading;
- using System.Threading.Tasks;
- using System.Xml;
- using System.Xml.Linq;
- using System.Xml.Serialization;
- namespace CE.WebServiceClient.DRHub
- {
- public class DRHubClient : IDRHub
- {
- #region "private variables"
- private DRHubConfig _config;
- private readonly NLogger.ASyncLogger _logger;
- private string _environment;
- private readonly int _clientId;
- private bool _configSetUp;
- private string _tokenId;
- private string _cookieName;
- //private bool _simulation;
- //private int _simulationInterval;
- #endregion
- #region "private const"
- private const string PjmNoticationEvent = "PJM Notification Event";
- private const string SeverityHigh = "High";
- private const string SeverityMedium = "Medium";
- private const string SeverityLow = "Low";
- private const string CatagoryPoll = "Poll";
- private const string CatagoryPingPoll = "Ping Poll";
- private const string CatagoryAck = "Acknowledge";
- private const string EventBegin = "Begins";
- private const string EventEnd = "Ends";
- private const string MsgPollEvents = "PJM Poll Event";
- private const string MsgAckEvents = "Acknowledge Event";
- private const string MsgProcessResponse = "Process PJM Response";
- private const string MsgSimulateEvents = "PJM Event Simulation";
- private const string MsgProcessEvents = "Process PJM Events";
- private const string MsgEventsReceived = "Event Received";
- private const string MsgRequest = "Request";
- private const string MsgResponse = "Response";
- private const string MsgPingEvents = "Ping Poll Event";
- private const string MsgNoEvent = "No Event";
- private const string MsgNoTeamNameMapping = "No Team Name Mapping for Registration ID";
- private const string HeaderVerbGet = "get";
- private const string HeaderVerbChange = "change";
- private const string HeaderNounEvent = "event";
- private const string HeaderRevision = "1.0";
- private const string HeaderSource = "OECSP";
- private const string RequestOptionUnAck = "unack";
- private const string RequestOptionAck = "ack";
- private const string PayloadFormat = "XML";
- private const string ReplyCodeOkay = "ok";
- private const string ReplyCodeWarning = "warning";
- private const string ReplyCodeFatal = "fatal";
- private const string ErrorCode = "4005";
- private const int DefaultMaxRetry = 5;
- private const string MsgLeadTimeWarning = "Invalid Lead Time, default to Quick_30";
-
- #endregion
- public DRHubClient(int clientId)
- {
- //_environment = environment;
- _clientId = clientId;
- Console.WriteLine("Initiate Logger" );
- _logger = new NLogger.ASyncLogger(clientId, _environment);
- GetDRHubConfig(clientId);
- }
- #region "public methods"
- /// <summary>
- /// call the api to poll events
- /// </summary>
- /// <returns></returns>
- public EventsCollection PollEvents()
- {
- EventsCollection eventsCol = null;
- //#if DEBUG
- // _config.Simulation = true;
- //#endif
- if (_configSetUp)
- {
- if (_config.Simulation)
- {
- var simulate = false;
- var currentTime = DateTime.Now;
- switch (_config.SimulationInterval)
- {
- case 5:
- if (currentTime.Minute % 5 == 0)
- simulate = true;
- break;
- case 15:
- if (currentTime.Minute % 15 == 0)
- simulate = true;
- break;
- case 30:
- if (currentTime.Minute % 30 == 0)
- simulate = true;
- break;
- case 60:
- if (currentTime.Minute % 60 == 0)
- simulate = true;
- break;
- case 1440:
- if (currentTime.TimeOfDay.Ticks == 0)
- simulate = true;
- break;
- }
- // simulate poll pjm events
- eventsCol = Simulate(simulate ? GetEventsResponseString() : GetNoEventResponseString());
- }
- else
- {
- // poll pjm events
- eventsCol = Poll(0);
- }
- }
- return eventsCol;
- }
- /// <summary>
- /// call api to acknowledge events
- /// </summary>
- /// <param name="events"></param>
- /// <param name="retry"></param>
- public void AcknowledgeEvents(EventsCollection events, int retry)
- {
- if (_configSetUp)
- {
-
-
- string ackEventUri = _config.ServiceUrl + _config.AcknowledgeEventsAction;
- HttpClient client = new HttpClient();
- //var authCTS = new CancellationTokenSource();
- //Task task = Task.Run(async () =>
- //{
- client = GetAuthDRHubClient(ackEventUri, CatagoryAck);
- //}, authCTS.Token);
- //authCTS.CancelAfter(3000);
- //await task;
- try
- {
- Console.WriteLine("{0} {1}", MsgAckEvents, EventBegin);
- _logger.Info(CatagoryAck, SeverityLow, PjmNoticationEvent, string.Format("{0} {1}", MsgAckEvents, EventBegin));
- // create payload events and convert into xml doc
- var acknowledgementPayloadStr = events.Xml;
-
- var xmlDoc = new XmlDocument();
- xmlDoc.LoadXml(acknowledgementPayloadStr);
- var httpContent = new StringContent(acknowledgementPayloadStr, Encoding.UTF8, "application/xml");
- // log the request info TODO: Is this the right thing to log?
- _logger.Info(CatagoryAck, SeverityLow, PjmNoticationEvent, acknowledgementPayloadStr, string.Empty, MsgRequest);
- // TODO: #DRHUB change call to get response from REST
- Console.WriteLine("Send Request");
- HttpResponseMessage responseFromPost = new HttpResponseMessage();
- string responseContent = string.Empty;
- //var cts = new CancellationTokenSource();
- //Task responseTask = Task.Run(async () =>
- //{
- responseFromPost = client.PutAsync(new Uri(ackEventUri), httpContent).Result;
- //responseFromPost.EnsureSuccessStatusCode();
- responseContent = responseFromPost.Content.ReadAsStringAsync().Result;
- //}, cts.Token);
- //cts.CancelAfter(3000);
- //await responseTask;
-
- Console.WriteLine("Response Received");
- if (!responseFromPost.IsSuccessStatusCode)
- {
- string errorMsg = responseFromPost.StatusCode.ToString() + " " + responseFromPost.ReasonPhrase;
- _logger.Error(CatagoryAck, SeverityHigh, PjmNoticationEvent, acknowledgementPayloadStr, responseContent, string.Format("Response fatal - {0}", errorMsg));
- throw new Exception(string.Format("Response fatal - {0}", errorMsg));
- }
- else
- {
- //log the response info
- Console.WriteLine(responseContent);
- _logger.Info(CatagoryAck, SeverityLow, PjmNoticationEvent, string.Empty, responseContent, MsgResponse);
- }
- _logger.Info(CatagoryAck, SeverityLow, PjmNoticationEvent, string.Format("{0} {1}", MsgAckEvents, EventEnd));
- Console.WriteLine("{0} {1}", MsgAckEvents, EventEnd);
- }
- catch (Exception ex)
- {
- _logger.ErrorException(CatagoryAck, SeverityHigh, PjmNoticationEvent, ex);
- if (retry < _config.MaxRetry)
- {
- retry++;
- _logger.Info(CatagoryAck, SeverityLow, PjmNoticationEvent, string.Format("{0} {1}", MsgAckEvents, EventEnd));
- #if DEBUG
- Console.WriteLine("{0} {1}", MsgAckEvents, EventEnd);
- #endif
- Task.Delay(_config.RetryWaitDuration);
- _logger.Info(CatagoryAck, SeverityMedium, PjmNoticationEvent, string.Format("Retry Attempt: {0}", retry));
- #if DEBUG
- Console.WriteLine("Retry Attempt: {0}", retry);
- #endif
- AcknowledgeEvents(events, retry);
- }
- else
- {
- _logger.Info(CatagoryAck, SeverityLow, PjmNoticationEvent, string.Format("{0} {1}", MsgAckEvents, EventEnd));
- Console.WriteLine("{0} {1}", MsgAckEvents, EventEnd);
- _logger.EmailErrorException(CatagoryAck, SeverityHigh, PjmNoticationEvent, ex);
- throw;
- }
- //_logger.Error(catagoryAck, string.Empty, string.Empty, ex.Message);
- }
- finally
- {
- client.Dispose();
- }
- return;
- }
- }
-
- /// <summary>
- /// for standalone DRHUB REST service pinging
- /// </summary>
- public void Ping(int retry)
- {
- string getEventUri = _config.ServiceUrl + _config.GetEventsAction;
- HttpClient client = new HttpClient();
- //var authCTS = new CancellationTokenSource();
- //Task task = Task.Run(async () =>
- //{
- client = GetAuthDRHubClient(getEventUri, CatagoryPingPoll);
- //}, authCTS.Token);
- //authCTS.CancelAfter(3000);
- //await task;
-
- try
- {
- Console.WriteLine("{0} {1}", MsgPingEvents, EventBegin);
- _logger.Info(CatagoryPingPoll, SeverityLow, PjmNoticationEvent, string.Format("{0} {1}", MsgPingEvents, EventBegin));
- #if DEBUG
- Console.WriteLine("Send Request");
- #endif
- HttpResponseMessage restResponse = client.GetAsync(getEventUri).Result;
- #if DEBUG
- Console.WriteLine("Response Received");
- #endif
- _logger.Info(CatagoryPingPoll, SeverityLow, PjmNoticationEvent, string.Format("{0} Succeeded", MsgPingEvents));
- Console.WriteLine("{0} Succeeded", MsgPingEvents);
- _logger.Info(CatagoryPingPoll, SeverityLow, PjmNoticationEvent, string.Format("{0} {1}", MsgPingEvents, EventEnd));
- Console.WriteLine("{0} {1}", MsgPingEvents, EventEnd);
- }
- catch (Exception ex)
- {
- _logger.ErrorException(CatagoryPingPoll, SeverityMedium, PjmNoticationEvent, ex);
- if (retry < _config.MaxRetry)
- {
- retry++;
- _logger.Info(CatagoryPingPoll, SeverityLow, PjmNoticationEvent, string.Format("{0} {1}", MsgPingEvents, EventEnd));
- #if DEBUG
- Console.WriteLine("{0} {1}", MsgPingEvents, EventEnd);
- #endif
- Task.Delay(_config.RetryWaitDuration);
- _logger.Info(CatagoryPingPoll, SeverityMedium, PjmNoticationEvent, string.Format("Retry Attempt: {0}", retry));
- Console.WriteLine("Retry Attempt: {0}", retry);
- Ping(retry);
- }
- else
- {
- _logger.Info(CatagoryPingPoll, SeverityLow, PjmNoticationEvent, string.Format("{0} {1}", MsgPingEvents, EventEnd));
- Console.WriteLine("{0} {1}", MsgPingEvents, EventEnd);
- _logger.EmailErrorException(CatagoryPingPoll, SeverityMedium, PjmNoticationEvent, ex);
- throw;
- }
- }
- finally
- {
- client.Dispose();
- }
- }
- #endregion
- #region "private methods"
- private EventsCollection Poll(int retry)
- {
- string getEventUri = _config.ServiceUrl + _config.GetEventsAction;
- //var authCTS = new CancellationTokenSource();
- HttpClient client = new HttpClient();
- //Task task = Task.Run(async () =>
- //{
- client = GetAuthDRHubClient(getEventUri, CatagoryPoll);
- //}, authCTS.Token);
- //authCTS.CancelAfter(3000);
- //await task;
- EventsCollection events = new EventsCollection();
- try
- {
- Console.WriteLine("{0} {1}", MsgPollEvents, EventBegin);
- _logger.Info(CatagoryPoll, SeverityLow, PjmNoticationEvent, string.Format("{0} {1}", MsgPollEvents, EventBegin));
- client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("text/html"));
- client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xhtml+xml"));
- client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml"));
- client.DefaultRequestHeaders.AcceptEncoding.Add(new StringWithQualityHeaderValue("gzip"));
- client.DefaultRequestHeaders.AcceptEncoding.Add(new StringWithQualityHeaderValue("deflate"));
- client.DefaultRequestHeaders.AcceptEncoding.Add(new StringWithQualityHeaderValue("sdch"));
- client.DefaultRequestHeaders.AcceptEncoding.Add(new StringWithQualityHeaderValue("br"));
- var cts = new CancellationTokenSource();
- HttpResponseMessage restResponse = new HttpResponseMessage();
- //Task responseTask = Task.Run(async () =>
- //{
- restResponse = client.GetAsync(getEventUri).Result;
- restResponse.EnsureSuccessStatusCode();
- events = ProcessResponse(restResponse);
- //}, cts.Token);
- //cts.CancelAfter(3000);
- //await responseTask;
-
-
- }
- catch (Exception ex)
- {
- if (retry < _config.MaxRetry)
- {
- retry++;
- Console.WriteLine("{0} {1}", MsgPollEvents, EventEnd);
- _logger.Info(CatagoryPoll, SeverityLow, PjmNoticationEvent, string.Format("{0} {1}", MsgPollEvents, EventEnd));
- Task.Delay(_config.RetryWaitDuration);
- #if DEBUG
- Console.WriteLine("Retry Attempt: {0}", retry);
- #endif
- _logger.Info(CatagoryPoll, SeverityMedium, PjmNoticationEvent, string.Format("Retry Attempt: {0}", retry));
- events = Poll(retry);
- }
- else
- {
- var currentTime = TimeZoneInfo.ConvertTimeBySystemTimeZoneId(DateTime.UtcNow, "Eastern Standard Time");
- if (currentTime.TimeOfDay >= Convert.ToDateTime("10:00").TimeOfDay && currentTime.TimeOfDay <= Convert.ToDateTime("20:30").TimeOfDay)
- {
- _logger.ErrorException(CatagoryPoll, SeverityHigh, PjmNoticationEvent, ex);
- _logger.EmailErrorException(CatagoryPoll, SeverityHigh, PjmNoticationEvent, ex);
- }
- else
- {
- _logger.ErrorException(CatagoryPoll, SeverityLow, PjmNoticationEvent, ex);
- _logger.EmailErrorException(CatagoryPoll, SeverityLow, PjmNoticationEvent, ex);
- }
- //_logger.Error(catagoryPoll, string.Empty, string.Empty, ex.Message);
- _logger.Info(CatagoryPoll, SeverityLow, PjmNoticationEvent, string.Format("{0} {1}", MsgPollEvents, EventEnd));
- Console.WriteLine("{0} {1}", MsgPollEvents, EventEnd);
- throw;
- }
- }
- finally
- {
- client.Dispose();
- }
- return events;
- }
- private void GetDRHubConfig(int clientId)
- {
- var cacheKey = string.Empty;
- Console.WriteLine("Initiate content model factory contentful");
- var cf = new ContentModelFactoryContentful();
- Console.WriteLine("Create ContentCacheProvider");
- var contentCashProvider = ContentCacheProviderFactory.CreateContentCacheProvider();
- try
- {
- Console.WriteLine("Create/Retrieve DRHub Config Begins");
- var contentRepository = cf.CreateContentRepository(clientId);
- Console.WriteLine("Get Content Eviornment");
- _environment = contentRepository.GetContentEnvironment();
- _logger.Envirnoment = _environment;
- Console.WriteLine("Create cache Key");
- // TODO: HOW DO WE CHANGE THE CACHE KEY HERE TO REMOVE THE ELRS reference?
- cacheKey = string.Format("ElrsConfig_{0}_{1}", clientId, _environment);
- Console.WriteLine("Get cached config");
- _config = (DRHubConfig)contentCashProvider.Get(cacheKey);
-
- }
- catch
- {
- _config = null;
- }
- if (_config != null)
- {
- _configSetUp = true;
- Console.WriteLine("Create/Retrieve DRHub Config Ends");
- return;
- }
- try
- {
- Console.WriteLine("No cache, create new config");
- _config = new DRHubConfig();
- Console.WriteLine("Create ContentProvider");
- var cp = cf.CreateContentProvider(clientId);
- var configurationList = cp.GetContentConfiguration(ContentCategory.Notification.ToString().ToLower(), string.Empty);
- if (configurationList.Any())
- {
- //_config.WebServiceEndPoint = configurationList.Find(item => item.Key == "webserviceclient.elrs.endpoint").Value;
- _config.Username = configurationList.Find(item => item.Key == "webserviceclient.drhub.username").Value;
- _config.Password = configurationList.Find(item => item.Key == "webserviceclient.drhub.password").Value;
- _config.EventTypes = configurationList.Find(item => item.Key == "webserviceclient.drhub.eventtypes").Value
- .Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList();
- _config.ServiceUrl = configurationList.Find(item => item.Key == "webserviceclient.drhub.serviceurl").Value;
- _config.GetEventsAction = configurationList.Find(item => item.Key == "webserviceclient.drhub.geteventsaction").Value;
- _config.AcknowledgeEventsAction = configurationList.Find(item => item.Key == "webserviceclient.drhub.ackeventsaction").Value;
- _config.AuthUrl = configurationList.Find(item => item.Key == "webserviceclient.drhub.authurl").Value;
- _config.MaxRetry = Convert.ToInt32(configurationList.Find(item => item.Key == "webserviceclient.global.maxretry").Value);
- if (_config.MaxRetry > DefaultMaxRetry) _config.MaxRetry = DefaultMaxRetry;
- _config.RetryWaitDuration = Convert.ToInt32(configurationList.Find(item => item.Key == "webserviceclient.global.retrywaitduration").Value);
- _config.Simulation = Convert.ToBoolean(configurationList.Find(item => item.Key == "webserviceclient.drhub.enablesimulation").Value);
- _config.SimulationInterval = Convert.ToInt32(configurationList.Find(item => item.Key == "webserviceclient.drhub.simulationeventinterval").Value);
- _config.CookieName = configurationList.Find(item => item.Key == "webserviceclient.drhub.cookiename").Value;
- }
- _configSetUp = true;
- contentCashProvider.Set(cacheKey, _config, DateTime.Now.AddMinutes(30));
- Console.WriteLine("Create/Retrieve DRHub Config Ends");
- }
- catch (Exception ex)
- {
- _logger.ErrorException(CatagoryPoll, SeverityHigh, PjmNoticationEvent, ex);
- _logger.EmailErrorException(CatagoryPoll, SeverityHigh, PjmNoticationEvent, ex);
- throw;
- }
- }
- private EventsCollection ProcessResponse(HttpResponseMessage response)
- {
- // responseData should contain events in xml format.
- EventsCollection eventsCol = null;
- string reqString = _config.ServiceUrl + _config.GetEventsAction;
- string respString = string.Empty;
- Console.WriteLine("{0} {1}", MsgProcessResponse, EventBegin);
- _logger.Info(CatagoryPoll, SeverityLow, PjmNoticationEvent, string.Format("{0} {1}", MsgProcessResponse, EventBegin));
- if (response.IsSuccessStatusCode)//if (response.ReasonPhrase.ToLower() == ReplyCodeOkay)
- {
- respString = response.Content.ReadAsStringAsync().Result;
- if (!respString.Contains("</ns2:events>")) // closing tag that will only be present if events are sent
- {
- // no events sent
- Console.WriteLine(MsgNoEvent);
- _logger.Info(CatagoryPoll, SeverityMedium, PjmNoticationEvent, reqString.ToString(), respString.ToString(), MsgNoEvent);
- } else
- {
- // there are events. process them.
- _logger.Info(CatagoryPoll, SeverityLow, PjmNoticationEvent, reqString.ToString(), respString.ToString(), string.Empty);
- eventsCol = ProcessEvents(respString);
- }
- }
- else // fatal error
- {
- _logger.EmailError(CatagoryPoll, SeverityHigh, PjmNoticationEvent, reqString.ToString(), respString.ToString(), "some really bad error"); //response.Reply.Error[0]);
- _logger.Error(CatagoryPoll, SeverityHigh, PjmNoticationEvent, reqString.ToString(), respString.ToString(), "some really bad error");// response.Reply.Error[0]);
- }
- _logger.Info(CatagoryPoll, SeverityLow, PjmNoticationEvent, string.Format("{0} {1}", MsgProcessResponse, EventEnd));
- Console.WriteLine("{0} {1}", MsgProcessResponse, EventEnd);
- return eventsCol;
- }
-
-
-
- private EventsCollection Simulate(string serializedResponse)
- {
- try
- {
- //Console.WriteLine("{0} {1}", MsgSimulateEvents, EventBegin);
- _logger.Info(CatagoryPoll, SeverityLow, PjmNoticationEvent, string.Format("{0} {1}", MsgSimulateEvents, EventBegin));
-
- var reader = new StringReader(serializedResponse);
- _logger.Info(CatagoryPoll, SeverityLow, PjmNoticationEvent, string.Format("{0} {1}", MsgSimulateEvents, EventEnd));
- Console.WriteLine("{0} {1}", MsgSimulateEvents, EventEnd);
-
- EventsCollection events = ProcessEvents(serializedResponse);
- events.Xml = serializedResponse;
-
- return events;
- }
- catch (Exception ex)
- {
- _logger.ErrorException(CatagoryPoll, SeverityHigh, PjmNoticationEvent, ex);
- _logger.Info(CatagoryPoll, SeverityLow, PjmNoticationEvent, string.Format("{0} {1}", MsgSimulateEvents, EventEnd));
- _logger.EmailErrorException(CatagoryPoll, SeverityHigh, PjmNoticationEvent, ex);
- throw;
- }
- }
- private EventsCollection ProcessEvents(string responseData)
- {
- Console.WriteLine("{0} {1}", MsgProcessEvents, EventBegin);
- _logger.Info(CatagoryPoll, SeverityLow, PjmNoticationEvent, string.Format("{0} {1}", MsgProcessEvents, EventBegin));
- // pull the team name mapping list from configuration
- var teamNames = GetTeamNameMappingList();
- var response = new EventsCollection {Xml = responseData};
- string eventId = string.Empty;
- string type = String.Empty;
- string target = string.Empty; // CURRENTLY NOT CAPTURED. MODEL CHANGED IN XML.
- string status = string.Empty;
- string regLeadTime = string.Empty;
- var startTime = DateTime.MinValue;
- var notifyTime = DateTime.MinValue;
- var endTime = DateTime.MinValue;
- var startUtcTime = DateTime.MinValue;
- var notifyUtcTime = DateTime.MinValue;
- var endUtcTime = DateTime.MinValue;
- var sleadTime = string.Empty;
- var zone = string.Empty;
- XmlDocument doc = new XmlDocument();
- doc.LoadXml(responseData);
- var nsmgr = new XmlNamespaceManager(doc.NameTable);
- nsmgr.AddNamespace("ns2", "http://drhub.pjm.com/");
- XmlNode eventsNode = doc.SelectSingleNode("//ns2:events", nsmgr);
- foreach (XmlNode eventSummary in eventsNode)
- {
- XmlNode idNode = eventSummary.SelectSingleNode("id");
- eventId = idNode.InnerText;
- XmlNode infoNode = eventSummary.SelectSingleNode("eventSummaryInfo");
- status = infoNode["status"].InnerText;
- regLeadTime = infoNode["regLeadTime"].InnerText;
- notifyTime = Convert.ToDateTime(infoNode["notifyTime"].InnerText);
- notifyUtcTime = Convert.ToDateTime(infoNode["notifyTime"].InnerText).ToUniversalTime();
- startTime = Convert.ToDateTime(infoNode["startTime"].InnerText);
- startUtcTime = Convert.ToDateTime(infoNode["startTime"].InnerText).ToUniversalTime();
- zone = infoNode["zone"].InnerText;
- if (infoNode["endTime"] != null)
- {
- endTime = Convert.ToDateTime(infoNode["endTime"].InnerText);
- endUtcTime = Convert.ToDateTime(infoNode["endTime"].InnerText).ToUniversalTime();
- }
- zone = infoNode["zone"].InnerText;
- var eventStatus = EventStatus.None;
- switch (status.ToLower())
- {
- case "scheduled":
- eventStatus = EventStatus.Scheduled;
- break;
- case "active":
- eventStatus = EventStatus.Active;
- break;
- case "completed":
- eventStatus = EventStatus.Completed;
- break;
- case "canceled":
- case "cancelled":
- eventStatus = EventStatus.Canceled;
- break;
- }
- var eventType = EventType.LoadManagement;
- switch (type.ToLower())
- {
- case "load management":
- eventType = EventType.LoadManagement;
- break;
- case "real-time dispatch":
- eventType = EventType.RealTimeDispatch;
- break;
- case "synchronized reserved":
- eventType = EventType.SynchronizedReserved;
- break;
- case "zonal test":
- eventType = EventType.ZonalTest;
- break;
- case "zonal retest":
- eventType = EventType.ZonalRetest;
- break;
- }
- var leadTime = LeadTimeType.Quick30;
- switch (regLeadTime.ToLower())
- {
- case "long_120":
- leadTime = LeadTimeType.Long120;
- break;
- case "short_60":
- leadTime = LeadTimeType.Short60;
- break;
- case "quick_30":
- leadTime = LeadTimeType.Quick30;
- break;
- default:
- leadTime = LeadTimeType.Quick30;
- //_logger.Error(CatagoryPoll, SeverityMedium, PjmNoticationEvent, MsgLeadTimeWarning);
- break;
- }
- var regInfoList = new List<RegistrationInfo>();
- XmlNode detailNode = eventSummary.SelectSingleNode("eventDetail");
- foreach (XmlNode evt in detailNode)
- {
- string regId = evt.SelectSingleNode("eventRegistration").SelectSingleNode("registrationId").InnerText;
- regInfoList.Add(new RegistrationInfo { RegistrationId = regId, Zone = zone, Target=target }); // TODO: CHECK ADDITION OF TARGET TO REGINFO.
- }
- var regIds = string.Empty;
- regInfoList.ForEach(r =>
- {
- if (regIds != string.Empty)
- regIds += ",";
- regIds += r.RegistrationId;
- });
- _logger.Info(CatagoryPoll, SeverityLow, PjmNoticationEvent, MsgEventsReceived, eventSummary.OuterXml);
- Console.WriteLine(eventSummary.OuterXml);
- GetTeamName(regInfoList, teamNames);
- response.Events.Add(new EventInfo
- {
- EndTime = endTime,
- EndUtcTime = endUtcTime,
- EventId = eventId,
- EventType = eventType,
- LeadTime = leadTime,
- NotifyTime = notifyTime,
- NotifyUtcTime = notifyUtcTime,
- RegistrationInfoList = regInfoList,
- StartTime = startTime,
- StartUtcTime = startUtcTime,
- Status = eventStatus,
- Target = target,
- EventXml = eventSummary.InnerXml
- });
- }
-
- return response;
- }
- /// <summary>
- /// get team name based on registration id
- /// </summary>
- /// <param name="regInfoList"></param>
- /// <param name="teamNames"></param>
- /// <returns></returns>
- private void GetTeamName(List<RegistrationInfo> regInfoList, List<TeamNameMapping> teamNames)
- {
- regInfoList.ForEach(r =>
- {
- var team = teamNames.Find(t => t.RegistrationId == r.RegistrationId);
- if (team != null)
- {
- r.TeamName = team.TeamName;
- r.IsHoneywellDlc = team.IsHoneywellDlc;
- }
- else
- {
- _logger.Error(CatagoryPoll, SeverityHigh, PjmNoticationEvent, string.Format("{0} {1}", MsgNoTeamNameMapping, r.RegistrationId));
- _logger.EmailError(CatagoryPoll, SeverityHigh, PjmNoticationEvent, string.Format("{0} {1}", MsgNoTeamNameMapping, r.RegistrationId));
- }
- });
- }
- private void SetPJMTokenId(int retry, string catagory)
- {
-
- CookieContainer cookies = new CookieContainer();
- HttpClientHandler handler = new HttpClientHandler();
- handler.CookieContainer = cookies;
- HttpClient client = new HttpClient(handler);
- HttpRequestMessage msg = new HttpRequestMessage()
- {
- RequestUri = new Uri(_config.AuthUrl),
- Method = HttpMethod.Post
- };
- // TODO: get username and password from config
- string username = _config.Username;
- string password = _config.Password;
- msg.Headers.Add("X-OpenAM-Username", username);
- msg.Headers.Add("X-OpenAM-Password", password);
- HttpResponseMessage response = new HttpResponseMessage();
- string responseBody = string.Empty;
- //var authCTS = new CancellationTokenSource();
- //Task task = Task.Run(async () =>
- //{
- response = client.SendAsync(msg).Result;
- //}, authCTS.Token);
- //authCTS.CancelAfter(3000);
- //await task;
- responseBody = response.Content.ReadAsStringAsync().Result;
- _tokenId = GetTokenId(responseBody);
-
- // retry - max 5 times; otherwise throw exception
- if (string.IsNullOrEmpty(_tokenId))
- {
- if (retry < _config.MaxRetry)
- {
- retry++;
-
- _logger.Info(catagory, SeverityMedium, PjmNoticationEvent, string.Format("Set PJM Token Id Retry Attempt: {0}", retry));
- #if DEBUG
- Console.WriteLine("Set PJM Token Id Retry Attempt: {0}", retry);
- #endif
- SetPJMTokenId(retry, catagory);
- }
- else
- {
- var exception = new Exception("Unable to set PJM Token Id");
- _logger.EmailErrorException(catagory, SeverityHigh, PjmNoticationEvent, exception);
- throw exception;
- }
- }
- }
- private HttpClient GetAuthDRHubClient(string requestUri, string catagory)
- {
- if (string.IsNullOrEmpty(_tokenId))
- {
- SetPJMTokenId(0, catagory);
-
- }
- // SET AUTH COOKIE
- HttpClientHandler dataClientHandler = new HttpClientHandler();
- dataClientHandler.CookieContainer = new CookieContainer();
- dataClientHandler.CookieContainer.Add(new Uri(requestUri), new Cookie(_config.CookieName, _tokenId));
- // Create client
- HttpClient dataClient = new HttpClient(dataClientHandler);
- return dataClient;
- }
- private List<TeamNameMapping> GetTeamNameMappingList()
- {
- var teamNames = new List<TeamNameMapping>();
- var mappingStr = GetTeamNameMappingXml();
- var teamNameDoc = XDocument.Load(new StringReader(mappingStr));
- var teamNameMapping = teamNameDoc.Descendants("TeamNameMapping").Select(x => x).ToList();
- teamNameMapping.ForEach(tm =>
- {
- tm.Descendants("MapInfo").Select(m => m).ToList().ForEach(t =>
- {
- var honeywellDlc = false;
- if (t.Attribute("HoneywellDLC") != null)
- {
- honeywellDlc = Convert.ToBoolean(t.Attribute("HoneywellDLC").Value);
- }
- teamNames.Add(new TeamNameMapping
- {
- RegistrationId = t.Attribute("key").Value,
- IsHoneywellDlc = honeywellDlc,
- TeamName = t.Value.Replace("&", "&")
- });
- });
- });
- return teamNames;
- }
- /// <summary>
- /// retreive team name mapping xml from database
- /// </summary>
- /// <returns></returns>
- private string GetTeamNameMappingXml()
- {
- string mappingStr;
- var connectionStr = ConfigurationManager.ConnectionStrings["InsightsMetaDataConn"].ConnectionString;
- using (var sqlConnection = new SqlConnection(connectionStr))
- {
- var cmd = new SqlCommand
- {
- CommandText = "[dbo].[GetComponentXmlConfiguration]",
- CommandType = CommandType.StoredProcedure,
- Connection = sqlConnection
- };
- cmd.Parameters.Add(new SqlParameter("@ClientId", SqlDbType.Int) { Value = _clientId });
- cmd.Parameters.Add(new SqlParameter("@ComponentName", SqlDbType.Text) { Value = "notification" });
- var param = cmd.CreateParameter();
- param.ParameterName = "@XmlConfiguration";
- param.Direction = ParameterDirection.Output;
- param.DbType = DbType.Xml;
- cmd.Parameters.Add(param);
- sqlConnection.Open();
- cmd.ExecuteNonQuery();
- mappingStr = param.Value.ToString();
- }
- return mappingStr;
- }
- // TODO: I DON'T THINK THIS IS NECESSARY OR WORKS. JUST SEND BACK XML FOR ACKNOWLEDGEMENT.
- /// <summary>
- /// set up the acknowledgement pay load
- /// </summary>
- /// <param name="events"></param>
- /// <returns></returns>
- private string GetAcknowledgementPayloadString(List<EventInfo> events)
- {
- var acknowledgementPayloadStr = @"<Events xmlns='http://www.pjm.com/schema/drbiznet/2009/model'>";
- foreach (var e in events)
- {
- acknowledgementPayloadStr += "<Event><id>" + e.EventId + "</id>";
- double amount;
- if (double.TryParse(e.Target, out amount))
- acknowledgementPayloadStr += "<summaryInfo><ackAmount>" + e.Target + "</ackAmount></summaryInfo>";
- acknowledgementPayloadStr += "</Event>";
- }
- acknowledgementPayloadStr += @"</Events>";
- return acknowledgementPayloadStr;
- }
- private string GetNoEventResponseString()
- {
- var xmlDoc = new XmlDocument();
- xmlDoc.Load("Samples\\SimulateNoEvent.xml");
- var objectStr = xmlDoc.InnerXml;
- return objectStr;
- }
- // TODO: REPLACE THIS XML STUFF
- private string GetEventsResponseString()
- {
- var xmlDoc = new XmlDocument();
- xmlDoc.Load("Samples\\SimulateEvent.xml");
- var objectStr = xmlDoc.InnerXml;
- return objectStr;
- }
- public string GetTokenId(string jsonString)
- {
- var jObj = JObject.Parse(jsonString);
- var token = jObj.SelectToken("tokenId");
- return token.Value<string>();
- }
- #endregion
- }
- [Serializable]
- public class DRHubConfig
- {
- public string Username { get; set; }
- public string Password { get; set; }
- public string WebServiceEndPoint { get; set; }
- public string GetEventsAction { get; set; }
- public string AcknowledgeEventsAction { get; set; }
- public string ServiceUrl { get; set; }
- public string AuthUrl { get; set; }
- public List<string> EventTypes { get; set; }
- public int MaxRetry { get; set; }
- public int RetryWaitDuration { get; set; }
- public bool Simulation { get; set; }
- public int SimulationInterval { get; set; }
- public string CookieName { get; set; }
- }
- [Serializable]
- public class TeamNameMapping
- {
- public string RegistrationId { get; set; }
- public string TeamName { get; set; }
- public bool IsHoneywellDlc { get; set; }
- }
- }