public AlertFunctionResult DefaultAlert(AlertSettings settings) { AlertFunctionResult functionResult = new AlertFunctionResult(); functionResult.RanSuccessfully = true; foreach (string target in settings.Targets) { AlertResult result = new AlertResult(); try { Dictionary<string, string> targetSettings = settings.TargetSettings[target]; HaleAlertSlackRecipient recipient = CreateRecipient(targetSettings); SlackMessage msg = CreateSlackMessage(recipient, settings); SendSlackMessage(msg, recipient); result.RanSuccessfully = true; result.Message = "OK"; } catch (Exception x) { functionResult.RanSuccessfully = result.RanSuccessfully = false; functionResult.FunctionException = result.ExecutionException = x; } functionResult.AlertResults.Add(target, result); } return functionResult; }
public AlertFunctionResult DefaultAlert(AlertSettings settings) { var afr = new AlertFunctionResult(); foreach (var target in settings.Targets) { var ar = new AlertResult(); try { var targetSettings = settings.TargetSettings[target]; var recipient = new HaleAlertPushbulletRecipient() { AccessToken = targetSettings["accessToken"], Target = targetSettings["target"], TargetType = (PushbulletPushTarget)Enum.Parse(typeof(PushbulletPushTarget), targetSettings["targetType"]), Name = targetSettings["name"], Id = Guid.NewGuid() }; var response = _api.Push("Hale Alert", string.Format("{0}\n{1}", settings.SourceString, settings.Message), recipient); ar.Message = response.Type; ar.RanSuccessfully = true; } catch (Exception x) { ar.RanSuccessfully = false; ar.ExecutionException = x; } afr.AlertResults.Add(target, ar); } afr.RanSuccessfully = true; return afr; }
/// <summary> /// Create AlertSettings on the Device. /// </summary> private AlertSettings CreateAndValidateAlertSettings(string deviceName) { AlertSettings alertsettingsToCreate = new AlertSettings(AlertEmailNotificationStatus.Enabled); alertsettingsToCreate.AlertNotificationCulture = "en-US"; alertsettingsToCreate.NotificationToServiceOwners = AlertEmailNotificationStatus.Enabled; alertsettingsToCreate.AdditionalRecipientEmailList = new List <string>(); this.Client.DeviceSettings.CreateOrUpdateAlertSettings( deviceName.GetDoubleEncoded(), alertsettingsToCreate, this.ResourceGroupName, this.ManagerName); var alertSettings = this.Client.DeviceSettings.GetAlertSettings( deviceName.GetDoubleEncoded(), this.ResourceGroupName, this.ManagerName); //validation Assert.True(alertSettings != null && alertSettings.AlertNotificationCulture.Equals("en-US") && alertSettings.EmailNotification.Equals(AlertEmailNotificationStatus.Enabled) && alertSettings.NotificationToServiceOwners.Equals(AlertEmailNotificationStatus.Enabled), "Creation of Alert Setting was not successful."); return(alertSettings); }
private void button10_Click(object sender, EventArgs e) { var aset = new AlertSettings { MicalertSettings = VolumeLevel.Micobject.alerts }; aset.ShowDialog(this); aset.Dispose(); }
private void btnAlertSettings_Click(object sender, EventArgs e) { HideFocus(); AlertSettings RESULT = AlertSettings; AlertSettingsForm DSF = new AlertSettingsForm(ref RESULT); //DialogResult DR = DSF.ShowDialog(); DSF.Show(); }
/// <summary> /// Set alert settings for a counter. /// </summary> /// <param name="settings">Alert settings.</param> public static void SetAlert(AlertSettings settings) { // if include stack counters, create the stack dictionary if (settings.IncludeStackCounter) { settings._counters.TraceCounts = new Dictionary <string, ulong>(); } // store settings _alerts[settings.CounterKey] = settings; }
public bool SendEmail(Project project, AlertSettings Alert, double DataPercentage) { try { string body = "<table cellspacing=\"1\" class=\"x_m_-3435250125640658816style1\">" + " <tbody>" + " <tr>" + " <td align=\"center\" bgcolor=\"#EFEFEF\" colspan=\"2\"><img data-imagetype=\"External\" src=\"/wp-content/themes/intelemark2/images/intelemark-logo.png\" width=\"200\"> </td>" + " </tr>" + " <tr>" + $" <td>The project {project.Name}'s data has fallen below the specified percentage</td>" + " </tr>" + " <tr>" + " <td bgcolor=\"#EFEFEF\">Current active percentage</td>" + $" <td bgcolor=\"#EFEFEF\">{DataPercentage}%</td>" + " </tr>" + " <tr>" + " <td>Percentage limit</td>" + $" <td>{Alert.DataPercentage}%</td>" + " </tr>" + " <tr>" + " <td bgcolor=\"#EFEFEF\">Campaign</td>" + $" <td bgcolor=\"#EFEFEF\">{project.Campaign.Identifier}</td>" + " </tr>" + " <tr>" + " <td align=\"center\" bgcolor=\"#f4a201\" colspan=\"2\"><b><font color=\"white\">Intelemark Web Application</font></b></td>" + " </tr>" + " </tbody>" + "</table>"; RestClient client = new RestClient(); client.BaseUrl = new Uri("https://api.mailgun.net/v3"); client.Authenticator = new HttpBasicAuthenticator("api", "key-9b7b33bcc4285cc7337a96e3609a61ec"); RestRequest request = new RestRequest(); request.AddParameter("domain", "mails.inovercy.com", ParameterType.UrlSegment); request.Resource = "{domain}/messages"; request.AddParameter("from", "<*****@*****.**>"); request.AddParameter("to", Alert.NotificationEmails.Replace(',', ';')); request.AddParameter("subject", "Low data notification"); request.AddParameter("html", body); request.Method = Method.POST; var send = client.Execute(request); return(true); } catch (Exception ex) { return(false); } }
public AlertFunctionResult DefaultAlert(AlertSettings settings) { var afr = new AlertFunctionResult(); foreach (var target in settings.Targets) { var result = new AlertResult(); var mbresult = MessageBox.Show(settings.Message, settings.SourceString, MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1); result.RanSuccessfully = true; result.Message = $"{target} -> {mbresult.ToString()}"; result.Target = target; afr.AlertResults.Add(target, result); } afr.RanSuccessfully = true; return afr; }
/// <summary> /// Get AlertSettings on the Device and validate. /// </summary> private void ValidateCreateOrUpdateAlertSettings(string deviceName) { //set new alert settings on the device AlertSettings newAlertSettings = new AlertSettings( this.Client, this.ResourceGroupName, this.ManagerName, "default") { AlertNotificationCulture = "en-US", EmailNotification = AlertEmailNotificationStatus.Enabled, NotificationToServiceOwners = ServiceOwnersAlertNotificationStatus.Disabled, AdditionalRecipientEmailList = new List <string>() { "*****@*****.**" }, }; // Update devices Alert Settings this.Client.Devices.CreateOrUpdateAlertSettings( deviceName.GetDoubleEncoded(), newAlertSettings, this.ResourceGroupName, this.ManagerName); // Retrive the updated alert settings var alertSettings = this.Client.Devices.GetAlertSettings( deviceName.GetDoubleEncoded(), this.ResourceGroupName, this.ManagerName); //validation Assert.True( alertSettings != null && (0 == string.Compare( alertSettings.Name, newAlertSettings.Name, ignoreCase: true)) && alertSettings.AlertNotificationCulture.Equals("en-US") && alertSettings.EmailNotification.Equals(AlertEmailNotificationStatus.Enabled) && alertSettings.NotificationToServiceOwners.Equals(ServiceOwnersAlertNotificationStatus.Disabled) && (0 == string.Compare( string.Join(",", alertSettings.AdditionalRecipientEmailList), string.Join(",", newAlertSettings.AdditionalRecipientEmailList), ignoreCase: true)), "Creation of Alert Setting was not successful."); }
public AlertSettingsForm(ref AlertSettings _AlertSettings) { InitializeComponent(); if (_AlertSettings != null) { AlertSettings = _AlertSettings; tglNotificationOnAlert.Checked = AlertSettings.NotificationOnAlert; tglDiscordOnAlert.Checked = AlertSettings.DiscordOnAlert; tglTweetOnAlert.Checked = AlertSettings.TweetOnAlert; tglMemMapFile.Checked = AlertSettings.MemMapEnabled; txtMyBotName.Text = AlertSettings.MyBotName; txtMyBotStatus.Text = AlertSettings.MyBotStatus; txtReferralsURL.Text = AlertSettings.ReferralURL; txtDisclaimerText.Text = AlertSettings.Disclaimertext; } }
private SlackMessage CreateSlackMessage(HaleAlertSlackRecipient recipient, AlertSettings settings) { SlackMessage msg = new SlackMessage() { Username = recipient.Username , Markdown = true , Icon = recipient.Icon , Pretext = settings.Message , Fields = new List<SlackField>() { new SlackField("Node", settings.SourceHost, false), new SlackField("Check", settings.SourceFunction, false) } , Color = GetAlertLevel(settings) }; return msg; }
// GET api/AlertSettings // מחזיר הגדרות של מחנך לפי המזהה של המחנך public AlertSettings GetByTeacherID(int teacherID) { AlertSettings alertS = new AlertSettings(); return(alertS.getAlertSettingsByTeacherID(teacherID)); }
public bool SendCampaignNotifications(List <OnWatchViewModel> onWatchSettings, AlertSettings Alert) { try { string body = "<table cellspacing=\"1\" class=\"x_m_-3435250125640658816style1\">" + " <tbody>" + " <tr>" + " <td align=\"center\" bgcolor=\"#EFEFEF\" colspan=\"3\"><img data-imagetype=\"External\" src=\"/wp-content/themes/intelemark2/images/intelemark-logo.png\" width=\"300\"> </td>" + " </tr>" + " <tr>" + $" <td colspan=\"3\">The following campaign(s) working hours have reached the notification point:</td>" + " </tr>" + " <tr>" + $" <td><b>Campaign</b></td>" + $" <td><b>Campaign Limit</b></td>" + $" <td><b>Hours Left</b></td>" + " </tr>"; foreach (var item in onWatchSettings) { body += " <tr>" + $" <td bgcolor=\"#EFEFEF\">{item.Campaign.Identifier}</td>" + $" <td bgcolor=\"#EFEFEF\">{item.Campaign.CampaignLimit}</td>" + $" <td bgcolor=\"#EFEFEF\">{item.HoursLeft}</td>" + " </tr>"; } body += "<tr>" + " <td align=\"center\" bgcolor=\"#f4a201\" colspan=\"3\"><b><font color=\"white\">Intelemark Web Application</font></b></td>" + " </tr>" + " </tbody>" + "</table>"; RestClient client = new RestClient(); client.BaseUrl = new Uri("https://api.mailgun.net/v3"); client.Authenticator = new HttpBasicAuthenticator("api", "key-9b7b33bcc4285cc7337a96e3609a61ec"); RestRequest request = new RestRequest(); request.AddParameter("domain", "mails.inovercy.com", ParameterType.UrlSegment); request.Resource = "{domain}/messages"; request.AddParameter("from", "<*****@*****.**>"); request.AddParameter("to", Alert.NotificationEmails.Replace(',', ';')); request.AddParameter("subject", "Campaign hour limit notification"); request.AddParameter("html", body); request.Method = Method.POST; var send = client.Execute(request); return(true); } catch (Exception ex) { return(false); } }
private string GetAlertLevel(AlertSettings settings) { switch (settings.SourceCheckLevel) { case CheckLevel.Critical: return "#ab2a2a"; case CheckLevel.Warning: return "#e47a0a"; case CheckLevel.OK: return "#019477"; default: return "#efefef"; } }
public void InitializeAlertProvider(AlertSettings settings) { this.AddAlertFunction(DefaultAlert); _api = new PushbulletApi(""); }
public void InitializeAlertProvider(AlertSettings settings) { this.AddAlertFunction(DefaultAlert); }
public static AlertFunctionResult ExecuteAlertFunction(string dll, string modulePath, string name, AlertSettings settings) { ModuleDomain moduleDomain = GetDomain(dll, modulePath); return moduleDomain.ExecuteAlertFunction(Path.GetFullPath(Path.Combine(modulePath, dll)), name, settings); }
private async Task LoadAlertSettings() { AlertSettings = await FileHelper.ImportAlertSettings(); }
/// <summary> /// Updates the alert settings for the vault. /// </summary> /// <param name='alertSettingsName'> /// Required. Alert Settings name. /// </param> /// <param name='input'> /// Required. Configure Alerts Request. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Model class for alerts response. /// </returns> public async Task <AlertSettingsResponse> ConfigureAsync(string alertSettingsName, ConfigureAlertSettingsRequest input, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken) { // Validate if (alertSettingsName == null) { throw new ArgumentNullException("alertSettingsName"); } if (input == null) { throw new ArgumentNullException("input"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary <string, object> tracingParameters = new Dictionary <string, object>(); tracingParameters.Add("alertSettingsName", alertSettingsName); tracingParameters.Add("input", input); tracingParameters.Add("customRequestHeaders", customRequestHeaders); TracingAdapter.Enter(invocationId, this, "ConfigureAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/Subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(this.Client.ResourceGroupName); url = url + "/providers/"; url = url + Uri.EscapeDataString(this.Client.ResourceNamespace); url = url + "/"; url = url + Uri.EscapeDataString(this.Client.ResourceType); url = url + "/"; url = url + Uri.EscapeDataString(this.Client.ResourceName); url = url + "/replicationAlertSettings/"; url = url + Uri.EscapeDataString(alertSettingsName); List <string> queryParameters = new List <string>(); queryParameters.Add("api-version=2015-11-10"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Put; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("Accept-Language", customRequestHeaders.Culture); httpRequest.Headers.Add("Agent-Authentication", customRequestHeaders.AgentAuthenticationHeader); httpRequest.Headers.Add("x-ms-client-request-id", customRequestHeaders.ClientRequestId); httpRequest.Headers.Add("x-ms-version", "2015-01-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Serialize Request string requestContent = null; JToken requestDoc = null; JObject configureAlertSettingsRequestValue = new JObject(); requestDoc = configureAlertSettingsRequestValue; if (input.Properties != null) { JObject propertiesValue = new JObject(); configureAlertSettingsRequestValue["properties"] = propertiesValue; if (input.Properties.SendToOwners != null) { propertiesValue["sendToOwners"] = input.Properties.SendToOwners; } if (input.Properties.CustomEmailAddresses != null) { if (input.Properties.CustomEmailAddresses is ILazyCollection == false || ((ILazyCollection)input.Properties.CustomEmailAddresses).IsInitialized) { JArray customEmailAddressesArray = new JArray(); foreach (string customEmailAddressesItem in input.Properties.CustomEmailAddresses) { customEmailAddressesArray.Add(customEmailAddressesItem); } propertiesValue["customEmailAddresses"] = customEmailAddressesArray; } } if (input.Properties.Locale != null) { propertiesValue["locale"] = input.Properties.Locale; } } requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json"); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result AlertSettingsResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new AlertSettingsResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { AlertSettings alertInstance = new AlertSettings(); result.Alert = alertInstance; JToken propertiesValue2 = responseDoc["properties"]; if (propertiesValue2 != null && propertiesValue2.Type != JTokenType.Null) { AlertSettingsProperties propertiesInstance = new AlertSettingsProperties(); alertInstance.Properties = propertiesInstance; JToken sendToOwnersValue = propertiesValue2["sendToOwners"]; if (sendToOwnersValue != null && sendToOwnersValue.Type != JTokenType.Null) { string sendToOwnersInstance = ((string)sendToOwnersValue); propertiesInstance.SendToOwners = sendToOwnersInstance; } JToken customEmailAddressesArray2 = propertiesValue2["customEmailAddresses"]; if (customEmailAddressesArray2 != null && customEmailAddressesArray2.Type != JTokenType.Null) { foreach (JToken customEmailAddressesValue in ((JArray)customEmailAddressesArray2)) { propertiesInstance.CustomEmailAddresses.Add(((string)customEmailAddressesValue)); } } JToken localeValue = propertiesValue2["locale"]; if (localeValue != null && localeValue.Type != JTokenType.Null) { string localeInstance = ((string)localeValue); propertiesInstance.Locale = localeInstance; } } JToken idValue = responseDoc["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); alertInstance.Id = idInstance; } JToken nameValue = responseDoc["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); alertInstance.Name = nameInstance; } JToken typeValue = responseDoc["type"]; if (typeValue != null && typeValue.Type != JTokenType.Null) { string typeInstance = ((string)typeValue); alertInstance.Type = typeInstance; } JToken locationValue = responseDoc["location"]; if (locationValue != null && locationValue.Type != JTokenType.Null) { string locationInstance = ((string)locationValue); alertInstance.Location = locationInstance; } JToken tagsSequenceElement = ((JToken)responseDoc["tags"]); if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null) { foreach (JProperty property in tagsSequenceElement) { string tagsKey = ((string)property.Name); string tagsValue = ((string)property.Value); alertInstance.Tags.Add(tagsKey, tagsValue); } } JToken clientRequestIdValue = responseDoc["ClientRequestId"]; if (clientRequestIdValue != null && clientRequestIdValue.Type != JTokenType.Null) { string clientRequestIdInstance = ((string)clientRequestIdValue); result.ClientRequestId = clientRequestIdInstance; } JToken correlationRequestIdValue = responseDoc["CorrelationRequestId"]; if (correlationRequestIdValue != null && correlationRequestIdValue.Type != JTokenType.Null) { string correlationRequestIdInstance = ((string)correlationRequestIdValue); result.CorrelationRequestId = correlationRequestIdInstance; } JToken dateValue = responseDoc["Date"]; if (dateValue != null && dateValue.Type != JTokenType.Null) { string dateInstance = ((string)dateValue); result.Date = dateInstance; } JToken contentTypeValue = responseDoc["ContentType"]; if (contentTypeValue != null && contentTypeValue.Type != JTokenType.Null) { string contentTypeInstance = ((string)contentTypeValue); result.ContentType = contentTypeInstance; } } } result.StatusCode = statusCode; if (httpResponse.Content != null && httpResponse.Content.Headers.Contains("Content-Type")) { result.ContentType = httpResponse.Content.Headers.GetValues("Content-Type").FirstOrDefault(); } if (httpResponse.Headers.Contains("Date")) { result.Date = httpResponse.Headers.GetValues("Date").FirstOrDefault(); } if (httpResponse.Headers.Contains("x-ms-client-request-id")) { result.ClientRequestId = httpResponse.Headers.GetValues("x-ms-client-request-id").FirstOrDefault(); } if (httpResponse.Headers.Contains("x-ms-correlation-request-id")) { result.CorrelationRequestId = httpResponse.Headers.GetValues("x-ms-correlation-request-id").FirstOrDefault(); } if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return(result); } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } }
/// <summary> /// Stab. /// </summary> public static void SetAlert(AlertSettings settings) { }
/// <summary> /// Creates or updates the alert settings of the specified device. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='deviceName'> /// The device name /// </param> /// <param name='parameters'> /// The alert settings to be added or updated. /// </param> /// <param name='resourceGroupName'> /// The resource group name /// </param> /// <param name='managerName'> /// The manager name /// </param> public static AlertSettings CreateOrUpdateAlertSettings(this IDeviceSettingsOperations operations, string deviceName, AlertSettings parameters, string resourceGroupName, string managerName) { return(operations.CreateOrUpdateAlertSettingsAsync(deviceName, parameters, resourceGroupName, managerName).GetAwaiter().GetResult()); }
// PUT api/AlertSettings public int Put(AlertSettings alertSettings) { AlertSettings alertS = new AlertSettings(); return(alertS.putAlertSettings(alertSettings)); }
public static AlertFunctionResult ExecuteAlertFunction(this IAlertProvider alertProvider, string action, AlertSettings settings) { return alertProvider.ExecuteFunction(action, settings, "alert") as AlertFunctionResult; }
/// <summary> /// Creates or updates the alert settings of the specified device. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='deviceName'> /// The device name /// </param> /// <param name='parameters'> /// The alert settings to be added or updated. /// </param> /// <param name='resourceGroupName'> /// The resource group name /// </param> /// <param name='managerName'> /// The manager name /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task <AlertSettings> BeginCreateOrUpdateAlertSettingsAsync(this IDeviceSettingsOperations operations, string deviceName, AlertSettings parameters, string resourceGroupName, string managerName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.BeginCreateOrUpdateAlertSettingsWithHttpMessagesAsync(deviceName, parameters, resourceGroupName, managerName, null, cancellationToken).ConfigureAwait(false)) { return(_result.Body); } }
public void CreateDomainLevel1() { try { var ctx = ApplicationDbContext.Create(); //already OK if (ctx.Campaigns.Any()) { return; } var reader = new ReadOnlyContext(); var db = MemoryDB.LoadDomainLevel1(reader); var container = new MemoryDB(); foreach (var item in db.Campaigns) { var campaign = new Campaign { Id = item.Id, //AccountManager = accountManager, //AccountManagerId = accountManager?.Id, AccountManagerId = item.AccountManagerId, //Client = client, //ClientId = client?.Id, ClientId = item.ClientId, ActiveControl = item.ActiveControl, BillingPH = item.BillingPH, CampaignLimit = item.CampaignLimit, CompanyLink = item.CompanyLink, CreationDate = item.CreationDate, Description = item.Description, Identifier = item.Identifier, IsDeleted = item.IsDeleted, LastUpdate = item.LastUpdate, MaxAttempt = item.MaxAttempt, Objective = item.Objective, SpellCheck = item.SpellCheck, }; container.Campaigns.Add(campaign); } foreach (var item in db.Projects) { var project = new Project { Id = item.Id, //Campaign = campaign, //CampaignId = campaign.Id, CampaignId = item.CampaignId, CreationDate = item.CreationDate, Description = item.Description, IsDeleted = item.IsDeleted, LastUpdate = item.LastUpdate, Name = item.Name, Priority = item.Priority, }; container.Projects.Add(project); } foreach (var item in db.TimeZones) { var timeZone = new Entities.TimeZone { Id = item.Id, Code = item.Code, CreationDate = item.CreationDate, CurrentTime = item.CurrentTime, DST = item.DST, IsDeleted = item.IsDeleted, LastUpdate = item.LastUpdate, Name = item.Name, STD = item.STD, }; container.TimeZones.Add(timeZone); } foreach (var item in db.Penalties) { var penalty = new Penalty { Id = item.Id, CreationDate = item.CreationDate, From = item.From, IsDeleted = item.IsDeleted, LastUpdate = item.LastUpdate, PayRate = item.PayRate, PenaltyFee = item.PenaltyFee, To = item.To, }; container.Penalties.Add(penalty); } foreach (var item in db.AlertSettings) { var alertSettings = new AlertSettings { Id = item.Id, LastUpdate = item.LastUpdate, CreationDate = item.CreationDate, DataPercentage = item.DataPercentage, IsDeleted = item.IsDeleted, NotificationEmails = item.NotificationEmails, }; container.AlertSettings.Add(alertSettings); } foreach (var item in db.AreaCodes) { var areaCode = new AreaCode { Id = item.Id, //TimeZone = timeZone, //TimeZoneId = timeZone.Id, TimeZoneId = item.TimeZoneId, CreationDate = item.CreationDate, IsDeleted = item.IsDeleted, LastUpdate = item.LastUpdate, Name = item.Name, TZ = item.TZ, }; container.AreaCodes.Add(areaCode); } foreach (var item in db.CallCodes) { var campaign = container.Campaigns .SingleOrDefault(x => x.Id == item.CampaignId); var callCode = new CallCode( campaign, item.Name, item.Code, item.Behavior, item.IsSuccess, item.CreationDate); callCode.IsDeleted = item.IsDeleted; container.CallCodes.Add(callCode); } foreach (var item in db.ExportSettings) { var exportSettings = new ExportSettings { Id = item.Id, //NOT FK CampaignId = item.CampaignId, CreationDate = item.CreationDate, IsDeleted = item.IsDeleted, Key = item.Key, LastUpdate = item.LastUpdate, Name = item.Name, Value = item.Value, }; container.ExportSettings.Add(exportSettings); } foreach (var item in db.ProjectPriorities) { var projectPriority = new ProjectPriority { Id = item.Id, //Project = item.Project, //ProjectId = project.Id, ProjectId = item.ProjectId, LastUpdate = item.LastUpdate, IsDeleted = item.IsDeleted, CreationDate = item.CreationDate, Field = item.Field, PriorityValue = item.PriorityValue, }; container.ProjectPriorities.Add(projectPriority); } foreach (var item in db.ProjectPriorityDetails) { var projectPriorityDetail = new ProjectPriorityDetail { Id = item.Id, //ProjectPriority = projectPriority, //ProjectPriorityId = projectPriority.Id, ProjectPriorityId = item.ProjectPriorityId, CreationDate = item.CreationDate, FieldPriorityValue = item.FieldPriorityValue, FieldValue = item.FieldValue, IsDeleted = item.IsDeleted, LastUpdate = item.LastUpdate, }; container.ProjectPriorityDetails.Add(projectPriorityDetail); } foreach (var item in db.StateRestrictions) { var stateRestriction = new StateRestriction { Id = item.Id, //TimeZone = timeZone, //TimeZoneId = timeZone.Id, TimeZoneId = item.TimeZoneId, LastUpdate = item.LastUpdate, IsDeleted = item.IsDeleted, Abbreviation = item.Abbreviation, CreationDate = item.CreationDate, IsRestricted = item.IsRestricted, Name = item.Name, }; container.StateRestrictions.Add(stateRestriction); } foreach (var item in db.OnWatchSettings) { var onWatchSettings = new OnWatchSettings { Id = item.Id, //Campaign = campaign, //CampaignId = campaign.Id, CampaignId = item.CampaignId, CreationDate = item.CreationDate, HoursLeft = item.HoursLeft, IsDeleted = item.IsDeleted, LastUpdate = item.LastUpdate, }; container.OnWatchSettings.Add(onWatchSettings); } ctx.Campaigns.AddRange(container.Campaigns); ctx.Projects.AddRange(container.Projects); ctx.TimeZones.AddRange(container.TimeZones); ctx.Penalties.AddRange(container.Penalties); ctx.AlertSettings.AddRange(container.AlertSettings); ctx.AreaCodes.AddRange(container.AreaCodes); ctx.CallCodes.AddRange(container.CallCodes); ctx.ExportSettings.AddRange(container.ExportSettings); ctx.ProjectPriorities.AddRange(container.ProjectPriorities); ctx.ProjectPriorityDetails.AddRange(container.ProjectPriorityDetails); ctx.StateRestrictions.AddRange(container.StateRestrictions); ctx.SaveChanges(); } catch (Exception ex) { var str = ex.ToString(); System.Diagnostics.Debug.WriteLine(str); } }
static AlertMapperInitialise() { // View to DTO Mapper.AddMap <AlertSettingsViewModel, AlertSettingsDto>(x => { //var settings = new AlertSettingsDto //{ // AlertRules = x.AlertRules // .Select(c => new AlertRulesDto().InjectFrom(c)).Cast<AlertRulesDto>() // .ToList() //}; var settings = new AlertSettingsDto(); settings.InjectFrom(x); foreach (var a in x.AlertRules) { var newA = new AlertRulesDto(); newA.InjectFrom(a); newA.AlertType = (AlertTypeDto)(int)a.AlertType; settings.AlertRules.Add(newA); } return(settings); }); // DTO to Entity Mapper.AddMap <AlertSettingsDto, AlertSettings>(x => { //var settings = new AlertSettings //{ // AlertRules = x.AlertRules // .Select(c => new DataAccessLayer.Models.Settings.AlertRules().InjectFrom(c)).Cast<DataAccessLayer.Models.Settings.AlertRules> () // .ToList() //}; var settings = new AlertSettings { AlertRules = new List <DataAccessLayer.Models.Settings.AlertRules>() }; settings.InjectFrom(x); foreach (var a in x.AlertRules) { var newA = new DataAccessLayer.Models.Settings.AlertRules(); newA.InjectFrom(a); newA.AlertType = (DataAccessLayer.Models.Settings.AlertType)(int) a.AlertType; settings.AlertRules.Add(newA); } return(settings); }); // Entity to DTO Mapper.AddMap <AlertSettings, AlertSettingsDto>(x => { var settings = new AlertSettingsDto { AlertRules = new List <AlertRulesDto>() }; settings.InjectFrom(x); //foreach (var entityAr in x.AlertRules) //{ // settings.AlertRules.Add((AlertRulesDto)new AlertRulesDto().InjectFrom(entityAr)); //} foreach (var entityAr in x.AlertRules) { var newA = new AlertRulesDto(); newA.InjectFrom(entityAr); newA.AlertType = (AlertTypeDto)(int)entityAr.AlertType; settings.AlertRules.Add(newA); } return(settings); }); // DTO to View Mapper.AddMap <AlertSettingsDto, AlertSettingsViewModel>(x => { //var settings = new AlertSettingsViewModel //{ // AlertRules = x.AlertRules // .Select(c => new AlertRules().InjectFrom(c)).Cast<AlertRules>() // .ToList() //}; var settings = new AlertSettingsViewModel(); settings.InjectFrom(x); foreach (var entityAr in x.AlertRules) { var newA = new AlertRules(); newA.InjectFrom(entityAr); newA.AlertType = (AlertType)(int)entityAr.AlertType; settings.AlertRules.Add(newA); } return(settings); }); // View to DTO Mapper.AddMap <AlertRules, AlertRulesDto>(x => { var dto = new AlertRulesDto(); dto.InjectFrom(x); dto.AlertType = (AlertTypeDto)(int)x.AlertType; return(dto); }); // DTO to Entity Mapper.AddMap <AlertRulesDto, DataAccessLayer.Models.Settings.AlertRules>(x => { var dto = new DataAccessLayer.Models.Settings.AlertRules(); dto.InjectFrom(x); dto.AlertType = (DataAccessLayer.Models.Settings.AlertType)(int) x.AlertType; return(dto); }); // Entity to DTO Mapper.AddMap <DataAccessLayer.Models.Settings.AlertRules, AlertRulesDto>(x => { var dto = new AlertRulesDto(); dto.InjectFrom(x); dto.AlertType = (AlertTypeDto)(int)x.AlertType; return(dto); }); // DTO to View Mapper.AddMap <AlertRulesDto, AlertRules>(x => { var dto = new AlertRules(); dto.InjectFrom(x); dto.AlertType = (AlertType)(int)x.AlertType; return(dto); }); }
public static MvcHtmlString Messages([NotNull] this HtmlHelper thisValue, AlertSettings alertSettings = null) { AlertSettings settings = alertSettings ?? new AlertSettings(); StringBuilder sb = new StringBuilder(); IList <TagBuilder> tags = new List <TagBuilder>(); // Error tags.Clear(); string value = Convert.ToString(thisValue.ViewBag.Error); if (!string.IsNullOrEmpty(value)) { tags.Add(new TagBuilder(HtmlTextWriterTag.Div.ToString()) { InnerHtml = value }); } value = thisValue.ViewContext.TempData.ContainsKey("Error") ? Convert.ToString(thisValue.ViewContext.TempData["Error"]) : null; if (!string.IsNullOrEmpty(value)) { tags.Add(new TagBuilder(HtmlTextWriterTag.Div.ToString()) { InnerHtml = value }); } if (!thisValue.ViewContext.ViewData.ModelState.IsValid && thisValue.ViewContext.ViewData.ModelState.ContainsKey(string.Empty) && thisValue.ViewContext.ViewData.ModelState[string.Empty].Errors.Count > 0) { value = thisValue.ValidationSummary(true)?.ToHtmlString(); if (tags.Count > 0 || !string.IsNullOrEmpty(value)) { TagBuilder divError = new TagBuilder(HtmlTextWriterTag.Div.ToString()); divError.AddCssClass(settings.CssClass); if (settings.ErrorIsDismissable) { divError.AddCssClass(settings.CssDismissableClass); } divError.AddCssClass(settings.CssErrorClass); if (tags.Count > 0) { divError.InnerHtml += string.Concat(tags); } if (!string.IsNullOrEmpty(value)) { divError.InnerHtml += value; } sb.Append(divError); } } // Warning tags.Clear(); value = Convert.ToString(thisValue.ViewBag.Warning); if (!string.IsNullOrEmpty(value)) { tags.Add(new TagBuilder(HtmlTextWriterTag.Div.ToString()) { InnerHtml = value }); } value = thisValue.ViewContext.TempData.ContainsKey("Warning") ? Convert.ToString(thisValue.ViewContext.TempData["Warning"]) : null; if (!string.IsNullOrEmpty(value)) { tags.Add(new TagBuilder(HtmlTextWriterTag.Div.ToString()) { InnerHtml = value }); } if (tags.Count > 0) { TagBuilder divWarning = new TagBuilder(HtmlTextWriterTag.Div.ToString()); divWarning.AddCssClass(settings.CssClass); if (settings.ErrorIsDismissable) { divWarning.AddCssClass(settings.CssDismissableClass); } divWarning.AddCssClass(settings.CssWarningClass); divWarning.InnerHtml = string.Concat(tags); sb.Append(divWarning); } // Success tags.Clear(); value = Convert.ToString(thisValue.ViewBag.Success); if (!string.IsNullOrEmpty(value)) { tags.Add(new TagBuilder(HtmlTextWriterTag.Div.ToString()) { InnerHtml = value }); } value = thisValue.ViewContext.TempData.ContainsKey("Success") ? Convert.ToString(thisValue.ViewContext.TempData["Success"]) : null; if (!string.IsNullOrEmpty(value)) { tags.Add(new TagBuilder(HtmlTextWriterTag.Div.ToString()) { InnerHtml = value }); } if (tags.Count > 0) { TagBuilder divSuccess = new TagBuilder(HtmlTextWriterTag.Div.ToString()); divSuccess.AddCssClass(settings.CssClass); if (settings.ErrorIsDismissable) { divSuccess.AddCssClass(settings.CssDismissableClass); } divSuccess.AddCssClass(settings.CssSuccessClass); divSuccess.InnerHtml = string.Concat(tags); sb.Append(divSuccess); } // Message tags.Clear(); value = Convert.ToString(thisValue.ViewBag.Message); if (!string.IsNullOrEmpty(value)) { tags.Add(new TagBuilder(HtmlTextWriterTag.Div.ToString()) { InnerHtml = value }); } value = thisValue.ViewContext.TempData.ContainsKey("Message") ? Convert.ToString(thisValue.ViewContext.TempData["Message"]) : null; if (!string.IsNullOrEmpty(value)) { tags.Add(new TagBuilder(HtmlTextWriterTag.Div.ToString()) { InnerHtml = value }); } if (tags.Count > 0) { TagBuilder divMessage = new TagBuilder(HtmlTextWriterTag.Div.ToString()); divMessage.AddCssClass(settings.CssClass); if (settings.ErrorIsDismissable) { divMessage.AddCssClass(settings.CssDismissableClass); } divMessage.AddCssClass(settings.CssInfoClass); divMessage.InnerHtml += string.Concat(tags); sb.Append(divMessage); } return(new MvcHtmlString(sb.ToString())); }