private async Task <InvokeResult <CloudBlobContainer> > GetStorageContainerAsync(string containerName) { var client = CreateBlobClient(); var container = client.GetContainerReference(containerName); try { var options = new BlobRequestOptions() { MaximumExecutionTime = TimeSpan.FromSeconds(15) }; var opContext = new OperationContext(); await container.CreateIfNotExistsAsync(options, opContext); return(InvokeResult <CloudBlobContainer> .Create(container)); } catch (ArgumentException ex) { _logger.AddException("CloudFileStorage_GetStorageContainerAsync", ex, containerName.ToKVP(nameof(containerName))); return(InvokeResult <CloudBlobContainer> .FromException("CloudFileStorage_GetStorageContainerAsync_InitAsync", ex)); } catch (StorageException ex) { _logger.AddException("ReportsLibraryRepo_GetStorageContainerAsync", ex, containerName.ToKVP(nameof(containerName))); return(InvokeResult <CloudBlobContainer> .FromException("CloudFileStorage_GetStorageContainerAsync", ex)); } }
public void SetConnection(String accountName, string accountKey) { _accountKey = accountKey; if (String.IsNullOrEmpty(_accountKey)) { var ex = new InvalidOperationException($"Invalid or missing account key information on {GetType().Name}"); _logger.AddException($"{GetType().Name}_SetConnection", ex); throw ex; } _accountName = accountName; if (String.IsNullOrEmpty(_accountName)) { var ex = new InvalidOperationException($"Invalid or missing account name information on {GetType().Name}"); _logger.AddException($"{GetType().Name}_SetConnection", ex); throw ex; } var credentials = new StorageCredentials(_accountName, _accountKey); var storageAccount = new CloudStorageAccount(credentials, true); _tableClient = storageAccount.CreateCloudTableClient(); _table = _tableClient.GetTableReference(GetTableName()); _srvrPath = $"https://{_accountName}.table.core.windows.net/{GetTableName()}"; }
public async Task <InvokeResult> AddModelAsync(string orgId, string modelId, int revisionId, byte[] model) { var retryCount = 0; Exception ex = null; while (retryCount++ < 5) { try { var cloudClient = CreateBlobClient(); var primaryContainer = cloudClient.GetContainerReference(GetContainerName(orgId)); await primaryContainer.CreateIfNotExistsAsync(); var blob = primaryContainer.GetBlockBlobReference(GetBlobName(modelId, revisionId)); await blob.UploadFromByteArrayAsync(model, 0, model.Length); return(InvokeResult.Success); } catch (Exception exc) { ex = exc; _adminLogger.AddException("MLModelRepo_GetModelAsync", ex); Console.WriteLine("Exception deserializeing: " + ex.Message); await Task.Delay(retryCount * 250); } } return(InvokeResult.FromException("MLModelRepo_GetModelAsync", ex)); }
public async Task <InvokeResult> SendConfirmationEmailAsync(EntityHeader orgHeader, EntityHeader userHeader) { var appUser = await _userManager.FindByIdAsync(userHeader.Id); if (appUser == null) { _adminLogger.AddCustomEvent(Core.PlatformSupport.LogLevel.Error, "UserVerifyController_SendConfirmationEmailAsync", "Could not get current user."); return(InvokeResult.FromErrors(UserAdminErrorCodes.AuthCouldNotFindUserAccount.ToErrorMessage())); } try { var token = await _userManager.GenerateEmailConfirmationTokenAsync(appUser); var encodedToken = System.Net.WebUtility.UrlEncode(token); var callbackUrl = $"{GetWebURI()}/Account/Verify?userId={appUser.Id}&code={encodedToken}"; var mobileCallbackUrl = $"nuviot:confirmemail/?userId={appUser.Id}&code={encodedToken}"; #if DEBUG _adminLogger.AddCustomEvent(Core.PlatformSupport.LogLevel.Message, "UserVerifyController_SendConfirmationEmailAsync", "SentToken", token.ToKVP("token"), appUser.Id.ToKVP("appUserId"), encodedToken.ToKVP("encodedToken"), appUser.Email.ToKVP("toEmailAddress")); #endif var subject = UserAdminResources.Email_Verification_Subject.Replace("[APP_NAME]", _appConfig.AppName); var body = UserAdminResources.Email_Verification_Body.Replace("[CALLBACK_URL]", callbackUrl).Replace("[MOBILE_CALLBACK_URL]", mobileCallbackUrl); var result = await _emailSender.SendAsync(appUser.Email, subject, body); _adminLogger.LogInvokeResult("UserVerficationManager_SendConfirmationEmailAsync", result, new KeyValuePair <string, string>("token", token), new KeyValuePair <string, string>("toUserId", appUser.Id), new KeyValuePair <string, string>("toEmail", appUser.Email)); return(result); } catch (Exception ex) { _adminLogger.AddException("UserVerficationManager_SendConfirmationEmailAsync", ex, new KeyValuePair <string, string>("toUserId", appUser.Id), new KeyValuePair <string, string>("toEmail", appUser.Email)); return(InvokeResult.FromErrors(UserAdminErrorCodes.RegErrorSendingEmail.ToErrorMessage(), new ErrorMessage() { Message = ex.Message })); } }
public void SetConnection(String endPoint, string sharedKey, string dbName) { var endpoint = endPoint; if (!Uri.TryCreate(endpoint, UriKind.Absolute, out _endpoint)) { var ex = new InvalidOperationException($"Invalid or missing end point information on {GetType().Name}"); _logger.AddException($"{GetType().Name}_CTor", ex); throw ex; } _sharedKey = sharedKey; if (String.IsNullOrEmpty(_sharedKey)) { var ex = new InvalidOperationException($"Invalid or missing shared key information on {GetType().Name}"); _logger.AddException($"{GetType().Name}_CTor", ex); throw ex; } _dbName = dbName; if (String.IsNullOrEmpty(_dbName)) { var ex = new InvalidOperationException($"Invalid or missing database name information on {GetType().Name}"); _logger.AddException($"{GetType().Name}_CTor", ex); throw ex; } _collectionName = typeof(TEntity).Name; if (!_collectionName.ToLower().EndsWith("s")) { _collectionName += "s"; } }
public async Task <InvokeResult <string> > SendAsync(MessageTransmissionPlan plan) { IsBusy = true; _pointIndex = 0; var messageTemplate = plan.Message.Value; try { InvokeResult res = InvokeResult.FromError(""); switch (messageTemplate.Transport.Value) { case TransportTypes.TCP: res = await SendTCPMessage(plan); break; case TransportTypes.UDP: res = await SendUDPMessage(plan); break; case TransportTypes.AzureServiceBus: res = await SendServiceBusMessage(plan); break; case TransportTypes.AzureEventHub: res = await SendEventHubMessage(plan); break; case TransportTypes.AzureIoTHub: res = await SendIoTHubMessage(plan); break; case TransportTypes.MQTT: res = await SendMQTTMessage(plan); break; case TransportTypes.RestHttps: case TransportTypes.RestHttp: res = await SendRESTRequestAsync(plan); break; } if (res.Successful) { var msg = BuildRequestContent(plan); return(InvokeResult <string> .Create(msg)); } else { return(InvokeResult <string> .FromInvokeResult(res)); } } catch (Exception ex) { _adminLogger.AddException("Send", ex); ReceivedContent = ex.Message; await _notificationPublisher.PublishTextAsync(Targets.WebSocket, Channels.Simulator, InstanceId, $"Error sending {messageTemplate.Transport.Value} message {ex.Message}."); return(InvokeResult <string> .FromException("SendAsync", ex)); } finally { IsBusy = false; } }
public async Task <ListResponse <DeviceSummaryData> > GetDeviceGroupSummaryDataAsync(DeviceRepository deviceRepo, string groupId, ListRequest listRequest) { SetConnection(deviceRepo.DeviceStorageSettings.Uri, deviceRepo.DeviceStorageSettings.AccessKey, deviceRepo.DeviceStorageSettings.ResourceName); var options = new FeedOptions() { MaxItemCount = (listRequest.PageSize == 0) ? 50 : listRequest.PageSize }; if (!String.IsNullOrEmpty(listRequest.NextRowKey)) { options.RequestContinuation = listRequest.NextRowKey; } var query = @"SELECT c.id, c.Status, c.Speed, c.Heading, c.Name, c.DeviceType, c.DeviceConfiguration, c.DeviceRepository, c.DeviceId, c.Attributes, c.States, c.Properties, c.GeoLocation FROM c join d in c.DeviceGroups where c.EntityType = 'Device' and c.DeviceRepository.Id = @repodid and d.Id = @groupid"; var sqlParams = new SqlParameterCollection(); sqlParams.Add(new SqlParameter("@repodid", deviceRepo.Id)); sqlParams.Add(new SqlParameter("@groupid", groupId)); try { var spec = new SqlQuerySpec(query, sqlParams); var link = await GetCollectionDocumentsLinkAsync(); var docQuery = Client.CreateDocumentQuery <DeviceSummaryData>(link, spec, options).AsDocumentQuery(); var result = await docQuery.ExecuteNextAsync <DeviceSummaryData>(); var listResponse = ListResponse <DeviceSummaryData> .Create(result); listResponse.NextRowKey = result.ResponseContinuation; listResponse.PageSize = result.Count; listResponse.HasMoreRecords = result.Count == listRequest.PageSize; listResponse.PageIndex = listRequest.PageIndex; return(listResponse); } catch (Exception ex) { _logger.AddException("DeviceManagementRepo_GetDeviceGroupSummaryDataAsync", ex, typeof(DeviceSummaryData).Name.ToKVP("entityType"), groupId.ToKVP("groupId"), deviceRepo.Id.ToKVP("deviceRepoId")); var listResponse = ListResponse <DeviceSummaryData> .Create(new List <DeviceSummaryData>()); listResponse.Errors.Add(new ErrorMessage(ex.Message)); return(listResponse); } }
public async Task <InvokeResult> SendAsync(string email, string subject, string body) { try { body = $@"<body> <img src=""{_appConfig.AppLogo}"" /> <h1>{_appConfig.AppName}</h1> <h2>{subject}</h2> {body} <img src=""{_appConfig.CompanyLogo}"" /> <p>Please do not reply to this email as it is an unmonitored address</p> <a href=""mailto:[email protected]"">Contact Support</a> </body>"; var msg = new MimeMessage() { Subject = subject, Body = new TextPart("html", body), }; msg.To.Add(new MailboxAddress(email)); msg.From.Add(new MailboxAddress(_settings.SmtpFrom)); using (var client = new SmtpClient()) { await client.ConnectAsync(_settings.SmtpServer.Uri.ToString(), 587, false); await client.AuthenticateAsync(_settings.SmtpServer.UserName, _settings.SmtpServer.Password); await client.SendAsync(msg); await client.DisconnectAsync(true); } _adminLogger.AddCustomEvent(Core.PlatformSupport.LogLevel.Verbose, "SendGridEmailServices_SendAsync", "EmailSent", new System.Collections.Generic.KeyValuePair <string, string>("Subject", subject), new System.Collections.Generic.KeyValuePair <string, string>("to", email)); return(InvokeResult.Success); } catch (Exception ex) { _adminLogger.AddException("SendGridEmailServices_SendAsync", ex, new System.Collections.Generic.KeyValuePair <string, string>("Subject", subject), new System.Collections.Generic.KeyValuePair <string, string>("to", email)); return(InvokeResult.FromException("SendGridEmailServices_SendAsync", ex)); } }
protected async Task <Database> GetDatabase(DocumentClient client) { if (String.IsNullOrEmpty(_dbName)) { var ex = new InvalidOperationException($"Invalid or missing database name information on {GetType().Name}"); _logger.AddException($"{GetType().Name}_CTor", ex); throw ex; } var databases = client.CreateDatabaseQuery().Where(db => db.Id == _dbName).ToArray(); if (databases.Any()) { return(databases.First()); } return(await client.CreateDatabaseAsync(new Database() { Id = _dbName })); }
public async Task <InvokeResult> SendAsync(string number, string contents) { try { TwilioClient.Init(_settings.SmsServer.AccountId, _settings.SmsServer.AccessKey); var restClient = new TwilioRestClient(_settings.SmsServer.AccountId, _settings.SmsServer.AccessKey); await MessageResource.CreateAsync(to : new PhoneNumber(number), from : new PhoneNumber(_settings.FromPhoneNumber), body : contents); _adminLogger.AddCustomEvent(Core.PlatformSupport.LogLevel.Verbose, "TwilioSMSSender_SendAsync", "EmailSent", new System.Collections.Generic.KeyValuePair <string, string>("Subject", number), new System.Collections.Generic.KeyValuePair <string, string>("to", contents)); return(InvokeResult.Success); } catch (Exception ex) { _adminLogger.AddException("SendGridEmailServices_SendAsync", ex, new System.Collections.Generic.KeyValuePair <string, string>("number", number), new System.Collections.Generic.KeyValuePair <string, string>("contents", contents)); return(InvokeResult.FromException("TwilioSMSSender_SendAsync", ex)); } }
public async Task <InvokeResult> SendAsync(string email, string subject, string body) { try { body = $@" <!DOCTYPE html PUBLIC ""-//W3C//DTD XHTML 1.0 Strict//EN"" ""http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd""><html xmlns=""http://www.w3.org/1999/xhtml""><head> <meta name=""viewport"" content=""width=device-width, initial-scale=1, minium-scale=1, maxium-scale=1""> <title>NuvIoT - IoT Eneablement Platform</title> <style type=""text/css""> body {{ width: 100% !important; -webkit-text-size-adjust: 100%; -ms-text-size-adjust: 100%; margin: 0; padding: 0; }} .ExternalClass {{ width: 100%; }} #backgroundTable {{ margin: 0; padding: 0; width: 100% !important; line-height: 100% !important; }} img {{ outline: none; text-decoration: none; -ms-interpolation-mode: bicubic; }} a img {{ border: none; }} .image-fix {{ display: block; }} Bring inline: Yes. */ p {{ margin: 1em 0; }} /* Hotmail header color reset Bring inline: Yes. */ h1, h2, h3, h4, h5 {{ color: #333333 !important; font-weight:400; }} h6 {{ color: #666666 !important; }} h1 a, h2 a, h3 a, h4 a, h5 a, h6 a {{ color: #2172ba !important; }} h1 a:active, h2 a:active, h3 a:active, h4 a:active, h5 a:active, h6 a:active {{ color: #2172ba !important; }} h1 a:visited, h2 a:visited, h3 a:visited, h4 a:visited, h5 a:visited, h6 a:visited {{ color: #2172ba !important; }} /* Outlook 07, 10 Padding issue fix */ table td {{ border - collapse: collapse; }} .ssrContent{{ font - size: 12px; }} /* Remove spacing around Outlook 07, 10 tables */ table {{ /*border-collapse:collapse;*/ mso - table - lspace: 0pt; mso-table-rspace: 0pt; }} a {{ color: #2172ba; text-decoration: none; }} a:hover {{ color: #2172ba; text-decoration: underline; }} .ad-width{{ width: 275px !important; }} /*.non-mobile-image, .non-mobile-email{{ display:block !important; }}*/ td[class=""mobile-email""], td[class=""mobile-image""] {{ display: none !important; max - height: 0 !important; width: 0 !important; font - size: 0 !important; line - height: 0 !important; padding: 0 !important; mso - hide: all; /* hide elements in Outlook 2007-2013 */ }} /*div[class=""mobile-mp-card-info""] {{ margin:0 !important; padding:90px 0 0 0 !important; }}*/ /* Apple Mail to limit that table's size on desktop*/ @media screen and(min - width: 600px) {{ .container {{ width: 601px!important; }} }} @media only screen and(max-width: 525px) {{ div[class= ""mobile - mp - card - section""] {{ padding:0 !important; margin:-25px 0 0 -150px !important; }} }} /* More Specific Targeting */ /* MOBILE TARGETING 480px */ @media only screen and(min-width: 480px) {{ /*table[class=""table""], td[class=""cell""] {{ width: 304px !important; }}*/ td[class= ""mobile - ad - spacing""] {{ padding-bottom: 15px !important; }} td[class=""mobile-image""] {{ display: inline-block !important; }} td[class=""non-mobile-image""] /*, .non-mobile-email*/ {{ display: none !important; max-height: 0 !important; width: 0 !important; font-size: 0 !important; line-height: 0 !important; padding: 0 !important; /*mso-hide: all; hide elements in Outlook 2007-2013 */ }} /*.mobile-email{{ display:block !important; }}*/ tr[class=""mobile-footer""] {{ background-color: #ffffff !important; }} body[class=""mobile-body""] {{ background-color: #ffffff !important; }} div[class=""navigation""] {{ width:100% !important; }} div[class=""navigation""] a {{ display:block !important; text-decoration:none !important; text-align:center !important; font-size:16px !important; }} /*Controlling phone number linking for mobile. */ a[href ^= ""tel""], a[href ^= ""sms""] {{ text-decoration: none; color: #2172ba; pointer-events: none; cursor: default; }} .mobile_link a[href ^= ""telephone""], .mobile_link a[href ^= ""sms""] {{ text-decoration: none; color: #2172ba !important; pointer-events: auto; cursor: default; }} a[class=""mobile-show""], a[class=""mobile-hide""] {{ display: block !important; color: #2172ba !important; border-radius: 20px; padding: 0 8px; text-decoration: none; font-weight: bold; font-family: ""Helvetica Neue"", Helvetica, sans-serif; font-size: 11px; position: absolute; top: 25px; right: 10px; text-align: center; width: 40px; }} div[class=""ad-width""]{{ width:300px !important; }} }} @media only screen and(min-device-width: 768px) and(max-device-width: 1024px) {{ /*ipad (tablets, smaller screens, etc) */ a[href ^= ""tel""],a[href ^= ""sms""] {{ text-decoration: none; color: #2172ba; pointer-events: none; cursor: default; }} .mobile_link a[href ^= ""tel""], .mobile_link a[href ^= ""sms""] {{ text - decoration: default; color: #2172ba !important; pointer - events: auto; cursor: default; }} }} @media only screen and(-webkit-min-device-pixel-ratio: 2) {{ /*iPhone 4g styles */ tr[class= ""non-mobile-image""],img[class= ""non - mobile - image""], table[class=""non-mobile-email""] {{ display: none !important; max-height: 0; width: 0; font-size: 0; line-height: 0; padding: 0; mso-hide: all; /* hide elements in Outlook 2007-2013 */ }} </style> <body style=""padding: 0; margin: 0; -webkit-text-size-adjust: none; -ms-text-size-adjust: 100%; background-color: #e6e6e6;"" class=""mobile-body""> <!--[if (gte mso 9)|(IE)]> <![endif]--> <table width=""100%"" cellpadding=""20"" cellspacing=""0"" border=""0"" style=""max-width:600px; background-color:white""><div> <tr> <td> <img src=""{_appConfig.AppLogo}"" /> <h1>{_appConfig.AppName}</h1> <h2>{subject}</h2> <div style=""width:550px""> {body} </div> </td> </tr> </table> <p>Please do not reply to this email as it is an unmonitored address.</p> <a href=""mailto:[email protected]"">Contact Support</a> </div> </body> </html>"; var msg = new MimeMessage() { Subject = subject, Body = new TextPart("html", body), }; msg.To.Add(new MailboxAddress(email)); msg.From.Add(new MailboxAddress(_settings.SmtpFrom)); using (var client = new SmtpClient()) { await client.ConnectAsync(_settings.SmtpServer.Uri.ToString(), 587, false); await client.AuthenticateAsync(_settings.SmtpServer.UserName, _settings.SmtpServer.Password); await client.SendAsync(msg); await client.DisconnectAsync(true); } _adminLogger.AddCustomEvent(Core.PlatformSupport.LogLevel.Verbose, "SendGridEmailServices_SendAsync", "EmailSent", new System.Collections.Generic.KeyValuePair <string, string>("Subject", subject), new System.Collections.Generic.KeyValuePair <string, string>("to", email)); return(InvokeResult.Success); } catch (Exception ex) { _adminLogger.AddException("SendGridEmailServices_SendAsync", ex, new System.Collections.Generic.KeyValuePair <string, string>("Subject", subject), new System.Collections.Generic.KeyValuePair <string, string>("to", email)); return(InvokeResult.FromException("SendGridEmailServices_SendAsync", ex)); } }