public SitesController() { _helper = AzureStorageHelper.Connect( ConfigurationManager.ConnectionStrings["AzureJobsRuntime"] .ConnectionString ); }
/// <summary> /// save patient demography to file/Azure Storage /// </summary> /// <param name="savePath"></param> /// <param name="id"></param> /// <returns></returns> public PatientViewModel GetPatient(string savePath, string id, bool saveToFile = true) { string getPatientUrl = AppSettings.FhirAPIBaseUrl + string.Format("Patient/{0}", id); //call API to get patient list string response = APIHelper.CallFhirApi(BearerToken, getPatientUrl); string fhirXml = RemoveAllEmptyNode(response); if (saveToFile) { if (AppSettings.StoredPatientInAzure) { //stored the patient information into azure storage to demo MemoryStream stream = new MemoryStream(); StreamWriter writer = new StreamWriter(stream); writer.Write(fhirXml); writer.Flush(); stream.Position = 0; AzureStorageHelper.UploadBlobToAzure("", string.Format("{0}.xml", id), stream); } else { //stored the patient information into local folder to demo string saveFilePath = Path.Combine(savePath, string.Format("{0}.xml", id)); File.WriteAllText(saveFilePath, fhirXml); } } FhirXmlParser fxp = new FhirXmlParser(); var patient = fxp.Parse <Hl7.Fhir.Model.Patient>(fhirXml); return(ConvertFhirToViewModel(patient)); }
/// <summary> /// Adds a message (an activity) to the log associated with the given user. /// </summary> /// <param name="activity">The activity to add.</param> /// <param name="user">The user associated with the message.</param> public async Task AddMessageLog(Microsoft.Bot.Schema.Activity activity, ConversationReference user, bool replace = false) { if (_messageLogsTable != null) { // Add to AzureTable var body = new MessageLog(user); body.AddMessage(activity); var msg = new MessageLogEntity { PartitionKey = PartitionKey, RowKey = activity.Conversation.Id, Body = body.ToJson() }; if (!replace) { await AzureStorageHelper.InsertAsync(_messageLogsTable, msg); } else { await AzureStorageHelper.ReplaceAsync(_messageLogsTable, msg); } } else { // Add to InMemory storage } }
public static void MyClassInitialize(TestContext testContext) { Aspx451TestWebApplication = new IISTestWebApplication { AppName = "Aspx451", Port = DeploymentAndValidationTools.Aspx451Port, }; Aspx451TestWebApplicationWin32 = new IISTestWebApplication { AppName = "Aspx451Win32", Port = DeploymentAndValidationTools.Aspx451PortWin32, EnableWin32Mode = true, }; DeploymentAndValidationTools.Initialize(); AzureStorageHelper.Initialize(); Aspx451TestWebApplication.Deploy(); Aspx451TestWebApplicationWin32.Deploy(); Trace.TraceInformation("IIS Restart begin."); Iis.Reset(); Trace.TraceInformation("IIS Restart end."); Trace.TraceInformation("HttpTests class initialized"); }
public async System.Threading.Tasks.Task <IActionResult> Index() { ViewData["SubscriptionId"] = subscription_id; try { var token = await MsiHelper.GetToken("https://storage.azure.com/"); ViewData["BlobTokenStatus"] = string.IsNullOrEmpty(token) ? "Failed to get token for storage.azure.com/" : "Got an ARM token for storage.azure.com/"; ViewData["DecodedToken"] = JwtHelper.DecodeToJson(token); if (string.IsNullOrEmpty(token)) { ViewData["Containers"] = "Get StorageToken was unsuccessful"; } else { ViewData["ContainersXML"] = AzureStorageHelper.GetAllContainerNamesXml(token, storage_account); } } catch (Exception ex) { Console.WriteLine(ex.Message); ViewData["Exception"] = ex?.Message; ViewData["InnerException"] = ex?.InnerException?.Message; } return(View()); }
public async Task <IHttpActionResult> ChangePhoto(ChangePhotoBindingModel model) { if (ModelState.IsValid) { var user = await RepositoryProvider.UserStore.FindByIdAsync(CurrentAccess.UserId); var oldPhotoPath = user.PhotoPath; Stream s = new MemoryStream(model.Photo.Buffer); ImageHelper.Resize(s, s, 300, ImageFormat.Jpeg); var azureStorageHelper = new AzureStorageHelper(ConfigHelper.AzureStorageConnectionString); var newPhotoPath = await azureStorageHelper.SaveFileStream(s, Guid.NewGuid() + ".jpg", AzureStorageHelper.FileUsage.UserPhotos); user.PhotoPath = newPhotoPath; await UserManager.UpdateAsync(user); if (!string.IsNullOrEmpty(oldPhotoPath)) { await azureStorageHelper.DeleteFile(oldPhotoPath, AzureStorageHelper.FileUsage.UserPhotos); } return(Ok(new { photoPath = newPhotoPath })); } return(BadRequest()); }
static async Task Main(string[] args) { CallLog callLog = new CallLog(); while (callLog.PayLoad.MoreAvailable) { var apiURL = APIHelper.GenerateTheAPIURL(Enums.ObjectType.Events); //setting the flag back to false callLog.IsCallSuccess = false; while (!callLog.IsCallSuccess) { callLog = APIHelper.CallTheAPI(apiURL); } // get the DB PK ID of the row just inserted var dbid = DatabaseHelper.InsertCallLogInToDatabse(callLog); // convert response data into ojbect using database Key for new record created above var PL = Newtonsoft.Json.JsonConvert.DeserializeObject <PayLoad>(callLog.Response); // build AzureStorageHelper MessagePayload with Datbase ID AzureStorageHelper.AzureConfigSettings azureconfig = new AzureStorageHelper.AzureConfigSettings() { storageConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["SQLConnectionString"].ToString(), blobcontainer = System.Configuration.ConfigurationManager.AppSettings["AzureContainerName"].ToString(), queuename = System.Configuration.ConfigurationManager.AppSettings["AzureQueueName"].ToString() }; var data = new AzureStorageHelper.Response() { ID = (int)dbid, RESPONSE = callLog.Response }; await AzureStorageHelper.PostMessageToQueueAsync(azureconfig, data); } }
public static void Run([QueueTrigger("spotify-queue", Connection = "AzureWebJobsStorage")] string myQueueItem, ILogger log) { log.LogInformation($"C# Queue trigger function processed: {myQueueItem}"); // parse the json queue data for party code var jObject = JObject.Parse(myQueueItem); var jToken = jObject.GetValue("party_code"); string partyCode = jToken.ToString(); KeyVaultHelper.LogIntoKeyVault(); var connectionString = KeyVaultHelper.GetSecret("https://spotify-matchmaker.vault.azure.net/secrets/storage-connection-string/"); var table = AzureStorageHelper.GetOrCreateTableAsync("partyCodes", connectionString).Result; var accessTokens = AzureStorageHelper.GetParty(partyCode, table).GetAccessTokens(); log.LogInformation($"Access token for party code: {partyCode}"); foreach (var token in accessTokens) { // log.LogInformation($"Access token: {token}"); } //take the party code and go to Azure Cosmos DB to lookup the party //grab spotify tokens from Cosmos DB and snoop through their music collections ; }
private void SubmitBtn_Click(object sender, RoutedEventArgs e) { for (int i = 0; i < 5; i++) { switch (i) { case 0: AzureStorageHelper.UpdateLunchMenu(days[i], MainMonTbx.Text, SideMonTbx.Text, double.Parse(CalMonTbx.Text)); break; case 1: AzureStorageHelper.UpdateLunchMenu(days[i], MainTuesTbx.Text, SideTuesTbx.Text, double.Parse(CalTuesTbx.Text)); break; case 2: AzureStorageHelper.UpdateLunchMenu(days[i], MainWedTbx.Text, SideWedTbx.Text, double.Parse(CalWedTbx.Text)); break; case 3: AzureStorageHelper.UpdateLunchMenu(days[i], MainThurTbx.Text, SideThurTbx.Text, double.Parse(CalThurTbx.Text)); break; case 4: AzureStorageHelper.UpdateLunchMenu(days[i], MainFriTbx.Text, SideFriTbx.Text, double.Parse(CalFriTbx.Text)); break; } } }
protected override void ProcessRecord() { if (_parametersValid) { // generate temp zip file in users %temp% dir and zip the project dir Random r = new Random(); string zipPath = Path.GetTempPath() + "job" + r.Next(1, 16777216).ToString() + ".zip"; ZipUp(zipPath, _jobDataDirectoryPath); // create storage helper var subscription = new AzureSubscription() { SubscriptionId = _azureParameters.parameters.SubscriptionID, ManagementCertificate = new System.Security.Cryptography.X509Certificates.X509Certificate2( _azureParameters.parameters.PathToManagementCertificate, _azureParameters.parameters.CertificateEncryptedPassword), StorageAccount = _azureParameters.parameters.StorageAccountName, StorageAccountKey = _azureParameters.parameters.StorageAccountKey }; AzureStorageHelper storage = new AzureStorageHelper(subscription, _clusterName); AzureCloudController controller = new AzureCloudController(subscription, _azureParameters.parameters.AffinityGroupName); AzureDynamicCluster cluster = new AzureDynamicCluster(storage, controller); // upload zip with exectable and data, and run the job (automaticaly from Azure Worker role) try { string jobID = cluster.SubmitJob(new JobItem() { CorePerNode = _coresPerNode, //needs to be adjusted in the future Executable = _executableFileName, Parameters = _executableArguments, NumNodes = _azureParameters.parameters.NumberOfNodes, InfoTag = "test", JobType = _jobType }, zipPath); // delete temp zip file; File.Delete(zipPath); // write true to the pipeline indicating successful upload WriteObject(jobID); } catch (Exception ex) { // delete temp zip file; File.Delete(zipPath); throw ex; } } else { WriteObject(null); } }
public async Task <IHttpActionResult> Register(RegisterBindingModel model) { var user = new ApplicationUser { UserName = model.Email, Email = model.Email, FirstName = model.FirstName, LastName = model.LastName, CreateDate = DateTime.UtcNow, LastLoginDate = DateTime.UtcNow, Status = Enums.UserStatus.Active.ToString() }; var createUserResult = await UserManager.CreateAsync(user, model.Password); if (!createUserResult.Succeeded) { return(GetErrorResult(createUserResult)); } var addToRoleResult = await UserManager.AddToRoleAsync(user.Id, Enums.RoleType.User.ToString()); if (!addToRoleResult.Succeeded) { await UserManager.DeleteAsync(user); return(GetErrorResult(addToRoleResult)); } //string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id); //var callbackUrl = Request.RequestUri.Scheme + "://" + Request.RequestUri.Host + // (Request.RequestUri.IsDefaultPort ? string.Empty : (":" + Request.RequestUri.Port)) + // "/Account/ConfirmEmail?userid=" + user.Id + "&code=" + code; //var emailTemplate = // await RepositoryProvider.Get<EmailTemplateRepository>() // .FirstOrDefaultAsync(p => p.Type == Enums.EmailType.ConfirmYourAccount.ToString()); //if (emailTemplate != null) //{ // emailTemplate.ReplaceWordsHolder(new KeyValuePair<string, string>("URL", callbackUrl)); // await UserManager.SendEmailAsync(user.Id, emailTemplate.Title, emailTemplate.Content); //} if (model.Photo != null && model.Photo.Buffer.Length > 0) { Stream s = new MemoryStream(model.Photo.Buffer); ImageHelper.Resize(s, s, 300, ImageFormat.Jpeg); var azureStorageHelper = new AzureStorageHelper(ConfigHelper.AzureStorageConnectionString); var photoUrl = await azureStorageHelper.SaveFileStream(s, Guid.NewGuid() + ".jpg", AzureStorageHelper.FileUsage.UserPhotos); user.PhotoPath = photoUrl; } await UserManager.UpdateAsync(user); return(Ok()); }
public bool Delete <T>(T entity) where T : ITableEntity, new() { table = table ?? tableClient.GetTableReference(typeof(T).Name); TableOperation replaceOperation = TableOperation.Delete(entity); var result = table.Execute(replaceOperation); return(AzureStorageHelper.IsSuccessStatusCode(result.HttpStatusCode)); }
public void GivenThereIsNoBlobPresentForThisID(Table table) { _customerData = table.CreateInstance <CustomerData>(); var blobName = string.Format("{0}-{1}", _customerData.Id, _customerData.Name); AzureStorageHelper.DeleteJsonFromBlob(blobName); }
protected void btnUpload_Click(object sender, EventArgs e) { if (filePicture.HasFile && filePicture.PostedFile != null) { AzureStorageHelper.UploadPicture(filePicture.PostedFile.InputStream, filePicture.PostedFile.FileName); } Response.Redirect("/Default.aspx"); }
protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { rptPhotos.DataSource = AzureStorageHelper.GetPicturesRefrences(); rptPhotos.DataBind(); } }
public async Task ReceiveAsync(WebSocket socket, string conversationId, SpeakerType speakerType) { // PCM format, 16000 samples per second, 16 bits per sample, 1 channel (mono) var outFormat = new WaveFormat(16000, 16, 1); var localDirectory = Environment.GetEnvironmentVariable("LocalAppData"); var outFilePath = Path.Combine(localDirectory, $"{Guid.NewGuid()}.wav"); var startTime = DateTime.Now; using (var outFileWriter = new WaveFileWriter(outFilePath, outFormat)) { await speech.StartContinuousRecognitionAsync(conversationId, speakerType, startTime).ConfigureAwait(false); var socketBuffer = new byte[Settings.ReceiveBufferSize]; if (socket != null) { var result = await socket.ReceiveAsync(new ArraySegment <byte>(socketBuffer), CancellationToken.None).ConfigureAwait(false); while (!result.CloseStatus.HasValue) { outFileWriter.Write(socketBuffer, 0, result.Count); if (result.Count > 0) { speech.PushStream.Write(socketBuffer, result.Count); } result = await socket.ReceiveAsync(new ArraySegment <byte>(socketBuffer), CancellationToken.None).ConfigureAwait(false);; } await speech.StopContinuousRecognitionAsync().ConfigureAwait(false); await socket.CloseAsync(result.CloseStatus.Value, result.CloseStatusDescription, CancellationToken.None).ConfigureAwait(false); } outFileWriter.Close(); } try { if (File.Exists(outFilePath)) { var culture = CultureInfo.InvariantCulture; var timestamp = startTime.ToString("s", culture); var blobName = $"{conversationId}/{conversationId}-{culture.TextInfo.ToLower(speakerType.ToString())}-{timestamp}.wav"; await AzureStorageHelper.UploadAudioFileAsync(outFilePath, config["Azure.Storage.ConnectionString"], config["Azure.Storage.Container.Audio"], blobName).ConfigureAwait(false); File.Delete(outFilePath); logger.LogInformation($"Successfully uploaded audio file for {conversationId}:{speakerType.ToString()}."); } } catch (IOException ex) { logger.LogError(ex, $"Issue when uploading (or deleting) audio file for {conversationId}:{speakerType.ToString()}."); }; }
public static async Task <IActionResult> Run( [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req, [Table("BasicInformation")] CloudTable cloudTable, ILogger log) { log.LogInformation("C# HTTP trigger function processed a request."); return((ActionResult) new OkObjectResult(await AzureStorageHelper.GetBasicInfoAsync(cloudTable))); }
public void ThenCustomerBlobShouldBeCreated(Table table) { _customerData = table.CreateInstance <CustomerData>(); var blobName = string.Format("{0}-{1}", _customerData.Id, _customerData.Name); var blobfound = AzureStorageHelper.VerifyJsonFromBlob(blobName); Assert.IsTrue(blobfound); }
private async void Grid_Loaded(object sender, RoutedEventArgs e) { var data = await AzureStorageHelper.GetBasicInfoAsync(); this.NameTbx.Text = data.Name; this.LocTbx.Text = data.Location; this.DescriptionTbx.Text = data.Description; this.ImgBox.Text = data.Image; this.StaTbx.Text = data.StationCode ?? ""; }
protected bool ExecuteConnection(Party conversationOwnerParty, Party conversationClientParty) { return(AzureStorageHelper.Insert <ConnectionEntity>(_connectionsTable, new ConnectionEntity() { PartitionKey = conversationClientParty.ConversationAccount.Id, RowKey = conversationOwnerParty.ConversationAccount.Id, Client = JsonConvert.SerializeObject(new PartyEntity(conversationClientParty, PartyEntityType.Client)), Owner = JsonConvert.SerializeObject(new PartyEntity(conversationOwnerParty, PartyEntityType.Owner)), })); }
public DocumentOutput GetDocumentWriteMode(Document doc) { //Generate READ Mode SAS Token. var companyInfo = _companyRepository.FindByCompanyID(doc.CompanyId); var sastoken = AzureStorageHelper.GetBlobSasToken(companyInfo.AzureStorageAccount, companyInfo.BlobContainer, doc.Title, SharedAccessBlobPermissions.Write); var document = _mapper.Map <DocumentOutput>(doc); document.Path = doc.URI + sastoken; return(document); }
public static void MyClassCleanup() { AzureStorageHelper.Cleanup(); DeploymentAndValidationTools.CleanUp(); Aspx451TestWebApplication.Remove(); Aspx451TestWebApplicationWin32.Remove(); Trace.TraceInformation("IIS Restart begin."); Iis.Reset(); Trace.TraceInformation("IIS Restart end."); Trace.TraceInformation("HttpTests class cleaned up"); }
/// <summary> /// Method to Download template for UserToUserMapping. /// </summary> /// <returns>File to browser's response.</returns> public async Task <ActionResult> DownloadTemplateAsync() { using (var memStream = await AzureStorageHelper.DownloadFileFromBlobAsync( this.appSettings.StorageConnectionString, this.appSettings.TemplatesContainerName, this.appSettings.KronosShiftUserMappingTemplateName, this.telemetryClient).ConfigureAwait(false)) { return(this.File(memStream.ToArray(), this.appSettings.ExcelContentType, this.appSettings.KronosShiftUserMappingTemplateName)); } }
public ActionResult Index() { CloudTable table = AzureStorageHelper.GetAzureTable("Customer"); TableQuery <Customer> query = new TableQuery <Customer>(); var customers = table.ExecuteQuery(query); if (Request.IsAjaxRequest()) { return(PartialView("_List", customers)); } return(View(customers)); }
public static async Task UploadToAzure(IConfigurationRoot config, Employee employee) { var AzureStorageConnectionString = config.GetSection("AzureStorageConfig:StorageConnectionString").Value; var AzureStorageContainer = config.GetSection("AzureStorageConfig:Container").Value; string output = JsonConvert.SerializeObject(employee); byte[] byteArray = Encoding.UTF8.GetBytes(output); MemoryStream stream = new MemoryStream(byteArray); await AzureStorageHelper.UploadFileAsBlob(AzureStorageConnectionString, AzureStorageContainer, "", $"employeeid{employee.id}.json", stream); }
public async Task CanRemoveElementFromBlobConfigFile(string userId, string roleName, string fileId, bool expectedResult) { var policy = await AzureStorageHelper.GetConfigFileAsync(fileId); PolicyServerRuntimeManager = new PolicyServerRuntimeManager(policy); PolicyServerRuntimeManager.RemoveUserFromRole(userId, roleName); var result = await PolicyServerRuntimeManager.SaveChangesAsync(fileId); Assert.Equal(expectedResult, result); }
private async void DownloadButton_Click(object sender, RoutedEventArgs e) { Button pickFileButton = (Button)sender; Grid parent = (Grid)VisualTreeHelper.GetParent(pickFileButton); FileDetail fileDetail = (FileDetail)parent.Tag; fileDetail.IsUploadingOrDownloading = true; CloudBlobContainer container = await AzureStorageHelper.GetBlobContainer(); Task.Run(() => DownloadBlob(container, fileDetail.FileName, fileDetail.FileId, fileDetail.FileSize)); }
private async void PostBtn_Click(object sender, RoutedEventArgs e) { try { AzureStorageHelper.PostAnnouncement(DateTime.Now.ToString(), TitleTbx.Text, PosterTbx.Text, "a", ContentTbx.Text, ImgBox.Text); await new MessageDialog("Successfully posted.").ShowAsync(); } catch { await new MessageDialog("Error").ShowAsync(); } }
public override async Task <bool> SaveChangesAsync(string fileId = null) { try { await AzureStorageHelper.UpdateConfigFileAsync(_policy, fileId); return(true); } catch (Exception) { return(false); } }
/// <summary> /// Constructor. /// </summary> /// <param name="connectionString">The connection string for Azure Table Storage.</param> public MessageLogs(string connectionString) { if (string.IsNullOrEmpty(connectionString)) { System.Diagnostics.Debug.WriteLine("WARNING!!! No connection string - storing message logs in memory"); _inMemoryMessageLogs = new List <MessageLog>(); } else { System.Diagnostics.Debug.WriteLine("Using Azure Table Storage for storing message logs"); _messageLogsTable = AzureStorageHelper.GetTable(connectionString, MessageLogsTableName); MakeSureConversationHistoryTableExistsAsync().Wait(); } }