static void Main(string[] args) { // insert your own connection string here, or use one of the other options: var tableStorage = CloudStorage .ForAzureConnectionString("DefaultEndpointsProtocol=https;AccountName=YOURACCOUNT;AccountKey=YOURKEY") .BuildTableStorage(); // 'books' is the name of the table var books = new CloudTable<Book>(tableStorage, "books"); var potterBook = new Book { Author = "J. K. Rowling", Title = "Harry Potter" }; var poemsBook = new Book { Author = "John Keats", Title = "Complete Poems" }; // inserting (or updating record in Table Storage) books.Upsert(new[] { new CloudEntity<Book> {PartitionKey = "UK", RowKey = "potter", Value = potterBook}, new CloudEntity<Book> {PartitionKey = "UK", RowKey = "poems", Value = poemsBook} }); // reading from table foreach(var entity in books.Get()) { Console.WriteLine("{0} by {1} in partition '{2}' and rowkey '{3}'", entity.Value.Title, entity.Value.Author, entity.PartitionKey, entity.RowKey); } Console.WriteLine("Press enter to exit."); Console.ReadLine(); }
void ClearTable(CloudTable table) { var deviceIds = _deviceService.GetDeviceIds(); foreach (var partitionKey in deviceIds) { TableBatchOperation batchDelete = new TableBatchOperation(); // gets all the entities in the table for this partition key string partitionCondition = TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, partitionKey); List<DynamicTableEntity> entities = table.ExecuteQuery(new TableQuery().Where(partitionCondition)).ToList(); entities.ForEach(e => { batchDelete.Add(TableOperation.Delete(e)); // Azure has a limit on batch operations if (batchDelete.Count == 100) { table.ExecuteBatch(batchDelete); batchDelete = new TableBatchOperation(); } }); // flush out whatever is left if (batchDelete.Count > 0) { table.ExecuteBatch(batchDelete); } } }
static void Main(string[] args) { // TODO: change your connection string here var providers = Standalone.CreateProviders("DefaultEndpointsProtocol=https;AccountName=;AccountKey="); // 'books' is the name of the table var books = new CloudTable<Book>(providers.TableStorage, "books"); var potterBook = new Book { Author = "J. K. Rowling", Title = "Harry Potter" }; var poemsBook = new Book { Author = "John Keats", Title = "Complete Poems" }; // inserting (or updating record in Table Storage) books.Upsert(new[] { new CloudEntity<Book> {PartitionKey = "UK", RowKey = "potter", Value = potterBook}, new CloudEntity<Book> {PartitionKey = "UK", RowKey = "poems", Value = poemsBook} }); // reading from table foreach(var entity in books.Get()) { Console.WriteLine("{0} by {1} in partition '{2}' and rowkey '{3}'", entity.Value.Title, entity.Value.Author, entity.PartitionKey, entity.RowKey); } Console.WriteLine("Press enter to exit."); Console.ReadLine(); }
protected override void StartOnSchedule() { var snapshotsToKeep = int.Parse(CloudEnvironment.GetConfigurationSetting(Names.NumberOfSnapshotsToKeepConfig).GetValue("3")); var accounts = Accounts.ListAccounts().ToSet(); var snapshotToDelete = new CloudTable<CompleteSnapshotReport>(TableStorage, Names.CompleteSnapshotReportsTable).Get() .GroupBy(entity => entity.PartitionKey) .Where(group => accounts.Contains(group.Key, StringComparer.OrdinalIgnoreCase) && group.Count() > snapshotsToKeep) .Select(group => group.OrderBy(entity => entity.Value.Completed).First()) .OrderBy(entity => entity.Value.Completed) .FirstOrEmpty(); if(!snapshotToDelete.HasValue) { return; } var snapshot = snapshotToDelete.Value.Value; Put(new DeleteSnapshotCommand { AccountName = snapshot.AccountName, SnapshotId = snapshot.SnapshotId, Credentials = Accounts.BuildSnapshotOnlyCredentials() }); }
// // GET: /Action/ public ActionResult Index(string partKey = PartitionKey) { var entities = new CloudTable<AnalysisAction>(Providers.TableStorage, TableName); var actions = entities.Get(partKey); var actionsView = AutoMapper.Mapper.Map<IEnumerable<CloudEntity<AnalysisAction>>, IEnumerable<AnalysisActionView>>(actions); return View(actionsView); }
public RestorePublisher(CloudInfrastructureProviders providers) { // State: _containerRestores = new CloudTable<ContainerRestoreState>(providers.TableStorage, Names.ContainerRestoreStateTable); // Reports: _indicators = new CloudTable<MonitoringIndicatorReport>(providers.TableStorage, Names.IndicatorReportsTable); _messages = new CloudTable<MonitoringMessageReport>(providers.TableStorage, Names.MessageReportsTable); }
public SnapshotPublisher(CloudInfrastructureProviders providers) { // State: _snapshots = new CloudTable<SnapshotState>(providers.TableStorage, Names.SnapshotStateTable); _containers = new CloudTable<ContainerState>(providers.TableStorage, Names.ContainerStateTable); // Reports: _indicators = new CloudTable<MonitoringIndicatorReport>(providers.TableStorage, Names.IndicatorReportsTable); _messages = new CloudTable<MonitoringMessageReport>(providers.TableStorage, Names.MessageReportsTable); _completeSnapshots = new CloudTable<CompleteSnapshotReport>(providers.TableStorage, Names.CompleteSnapshotReportsTable); }
public static void MyClassInitialize(TestContext testContext) { CloudTableClient tableClient = GenerateCloudTableClient(); currentTable = tableClient.GetTableReference(GenerateRandomTableName()); currentTable.CreateIfNotExists(); // Populate Entities (This will add 1500 entities to a new table, enough to test continuations TableServiceContext ctx = tableClient.GetTableServiceContext(); for (int l = 0; l < totalTestEntities / 100; l++) { for (int m = 0; m < 100; m++) { BaseEntity ent = new BaseEntity("partition" + l, m.ToString()); ent.Randomize(); ent.A = ent.RowKey; ctx.AddObject(currentTable.Name, ent); } ctx.SaveChangesWithRetries(SaveChangesOptions.Batch); } }
public LoginModule(ISaltedHash saltedHash, CloudTable<User> users) : base("/account/login") { _saltedHash = saltedHash; _users = users; Get["/"] = x => { if (IsAuthenticated) return this.AsRedirectQueryStringOrDefault("~/dashboard"); this.CreateNewCsrfToken(); var model = this.Bind<LoginModel>(); return View["account/login", model]; }; Post["/"] = x => { if (IsAuthenticated) return this.AsRedirectQueryStringOrDefault("~/dashboard"); this.ValidateCsrfToken(); var model = this.BindAndValidate<LoginModel>(); if (!ModelValidationResult.IsValid) return View["account/login", model]; var user = VerifyUser(model); if (user == null) return InvalidLogin(model); // TODO: Publish event for CQRS/ES audit logging return this.SignIn(user, model.RememberMe); }; }
public static async Task <IActionResult> End( [HttpTrigger(AuthorizationLevel.Function, "post", Route = ServiceNames.UploadEnd + "/{session}/{filename?}")] HttpRequest req, string session, string filename, [Blob(BlobNames.UploadDirectory + "/{session}")] CloudBlobDirectory uploadDir, [Table(TableNames.CommUpload, CommUploadPartitionKeys.Temp, "{session}")] TableEntityAdapter <UploadSession> upload, [Table(TableNames.CommUpload)] CloudTable uploadTable, [Queue(QueueNames.CommProcess)] CloudQueue processQueue, [Inject] App app, ILogger log) { try { if (session.IsNullOrEmpty()) { throw new ArgumentException("The Session Id is required.", nameof(session)); } // save the file var uploadTo = await req.Body.UploadTo(uploadDir, filename); #region unexpected behaviour notes /* * update the OriginalEntity.Property value has cause some funny error without cloning the object * System.Private.CoreLib: Exception while executing function: TransferEnd. * Microsoft.Azure.WebJobs.Host: Error while handling parameter upload after function returned:. * Microsoft.WindowsAzure.Storage: Not Found. * * upload.OriginalEntity.UploadEnd = app.DateTimeNow; */ #endregion unexpected behaviour notes UploadSession UpdateOriginalEntity(UploadSession uploadSession) { uploadSession.UploadEnd = app.DateTimeNow; uploadSession.ManifestFile = new[] { upload.OriginalEntity.ManifestFile, filename }.IsIfManifest(); uploadSession.LastUploadedFile = new[] { filename, uploadSession.LastUploadedFile }.FirstIsNotEmpty(); return(uploadSession); } // close the upload session upload = await upload.MoveTo(uploadTable , uploadSession => CommUploadPartitionKeys.Completed , updateOriginalEntity : UpdateOriginalEntity ); // raise the UploadCompleted event await new UploadCompleted { SessionId = session }.AddMessageToAsync(processQueue); return(new OkObjectResult(upload.OriginalEntity)); } catch (Exception ex) { log.LogError(ex.StackTrace); return(new BadRequestObjectResult(new UploadSession { Errors = ex.Message })); } }
private async Task MessageReceivedAsync(IDialogContext context, IAwaitable <IMessageActivity> result) { var message = await result; var msg = context.MakeMessage(); msg.Type = ActivityTypes.Typing; await context.PostAsync(msg); var storageAccount = CloudStorageAccount.Parse(ConfigurationManager.AppSettings["AzureWebJobsStorage"]); var tableClient = storageAccount.CreateCloudTableClient(); CloudTable eventTable = tableClient.GetTableReference("Event"); eventTable.CreateIfNotExists(); DateTime thisDay = DateTime.Today; String today = FormatDate(thisDay.ToString("d")); EventEntity eventEntity = null; string codeEntered = ""; if (message.Attachments.FirstOrDefault() != null) { string destinationContainer = "qrcode"; CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient(); var blobContainer = blobClient.GetContainerReference(destinationContainer); blobContainer.CreateIfNotExists(); String newFileName = ""; var a = message.Attachments.FirstOrDefault(); try { using (HttpClient httpClient = new HttpClient()) { var responseMessage = await httpClient.GetAsync(a.ContentUrl); var contentLenghtBytes = responseMessage.Content.Headers.ContentLength; var fileByte = await httpClient.GetByteArrayAsync(a.ContentUrl); newFileName = context.UserData.GetValue <string>(ContextConstants.UserId) + "_" + DateTime.Now.ToString("MMddyyyy-hhmmss") + "_" + "qrcode"; var barcodeReader = new BarcodeReader(); var memoryStream = new MemoryStream(fileByte); string sourceUrl = a.ContentUrl; var barcodeBitmap = (Bitmap)Bitmap.FromStream(memoryStream); var barcodeResult = barcodeReader.Decode(barcodeBitmap); codeEntered = barcodeResult.Text; eventEntity = GetEvent(barcodeResult.Text); memoryStream.Close(); } } catch (Exception e) { Debug.WriteLine(e.ToString()); } } else { codeEntered = message.Text; eventEntity = GetEvent(message.Text); } //Check database if (eventEntity != null) { var eventName = eventEntity.EventName; CloudTable attendanceTable = tableClient.GetTableReference("Attendance"); attendanceTable.CreateIfNotExists(); String filterA = TableQuery.GenerateFilterCondition("SurveyCode", QueryComparisons.Equal, eventEntity.SurveyCode); String filterB = TableQuery.GenerateFilterCondition("RowKey", QueryComparisons.Equal, context.UserData.GetValue <string>(ContextConstants.UserId)); String filterD = TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, eventEntity.RowKey); TableQuery <AttendanceEntity> query = new TableQuery <AttendanceEntity>().Where(TableQuery.CombineFilters(filterA, TableOperators.And, filterB)); TableQuery <AttendanceEntity> todayQuery = new TableQuery <AttendanceEntity>().Where(TableQuery.CombineFilters(TableQuery.CombineFilters(filterA, TableOperators.And, filterB), TableOperators.And, filterD)); var results = attendanceTable.ExecuteQuery(query); var todayResults = attendanceTable.ExecuteQuery(todayQuery); Boolean notDone = true; //Survey Code if (codeEntered == eventEntity.SurveyCode) { if (results != null) { foreach (AttendanceEntity a in results) { if (a.Survey == true) { notDone = false; await context.PostAsync("You have already completed the survey for " + "'" + eventName + "'!"); await context.PostAsync(msg); await context.PostAsync("Talk to me again if you require my assistance."); context.Done(this); } } if (notDone && !ValidPeriod(eventEntity.SurveyEndDate, eventEntity.SurveyEndTime, eventEntity.EventStartDate)) { await context.PostAsync("Sorry, this code is not yet ready for use or have already expired!"); await context.PostAsync(msg); await context.PostAsync("Talk to me again if you require my assistance."); context.Done(this); } } context.UserData.SetValue(ContextConstants.Status, "3"); context.UserData.SetValue(ContextConstants.Survey, eventEntity.Survey); //Attendance Code 1 } else if (codeEntered == eventEntity.AttendanceCode1) { if (todayResults != null) { foreach (AttendanceEntity a in todayResults) { if (a.Morning == true) { notDone = false; await context.PostAsync("You have already registered this attendance for " + "'" + eventName + "'" + " today!"); await context.PostAsync(msg); await context.PostAsync("Talk to me again if you require my assistance."); context.Done(this); } } if (notDone && !ValidTime(eventEntity.AttendanceCode1StartTime, eventEntity.AttendanceCode1EndTime, eventEntity.Day, eventEntity.EventStartDate, eventEntity.EventEndDate)) { await context.PostAsync("Sorry, this code is not yet ready for use or have already expired!"); await context.PostAsync(msg); await context.PostAsync("Talk to me again if you require my assistance."); context.Done(this); } } context.UserData.SetValue(ContextConstants.Status, "1"); }//Attendance code 2 else if (codeEntered == eventEntity.AttendanceCode2) { if (todayResults != null) { foreach (AttendanceEntity a in todayResults) { if (a.Afternoon == true) { notDone = false; await context.PostAsync("You have already registered this attendance for " + "'" + eventName + "'" + " today!"); await context.PostAsync(msg); await context.PostAsync("Talk to me again if you require my assistance."); context.Done(this); } } if (notDone && !ValidTime(eventEntity.AttendanceCode2StartTime, eventEntity.AttendanceCode2EndTime, eventEntity.Day, eventEntity.EventStartDate, eventEntity.EventEndDate)) { await context.PostAsync("Sorry, this code is not yet ready for use or have already expired!"); await context.PostAsync(msg); await context.PostAsync("Talk to me again if you require my assistance."); context.Done(this); } } context.UserData.SetValue(ContextConstants.Status, "2"); } context.UserData.SetValue(ContextConstants.EventCode, eventEntity.RowKey); context.UserData.SetValue(ContextConstants.SurveyCode, eventEntity.SurveyCode); context.UserData.SetValue(ContextConstants.Anonymous, eventEntity.Anonymous); context.UserData.SetValue(ContextConstants.EventName, eventName); context.UserData.SetValue(ContextConstants.Today, today); context.UserData.SetValue(ContextConstants.Description, eventEntity.Description); context.Done(true); } else { await context.PostAsync("I'm sorry, I think you have keyed in the wrong workshop code or have sent an invalid QR Code, let's do this again."); context.Wait(this.MessageReceivedAsync); } }
public static async Task <IActionResult> Run([HttpTrigger("post", Route = "Sessions")] HttpRequest req, [Table("Session")] CloudTable sessions, ILogger log) { log.LogInformation("C# HTTP trigger function processed a request."); string requestBody = await new StreamReader(req.Body).ReadToEndAsync(); var session = JsonConvert.DeserializeObject <Session>(requestBody); session.PartitionKey = session.Id; session.RowKey = session.Id; session.SpeakersIdsJson = JsonConvert.SerializeObject(session.SpeakersIds); log.LogInformation(JsonConvert.SerializeObject(session)); var result = await sessions.ExecuteAsync(TableOperation.InsertOrReplace(session)); return(new OkObjectResult(result.Result)); }
static void CreateTable(CloudTableClient cloudTableClient) { CloudTable cloudTable = cloudTableClient.GetTableReference("table1"); cloudTable.CreateIfNotExists(); }
/// <summary> /// Imports data of DataTable to table storage /// </summary> /// <param name="dtSheetInfo"></param> /// <param name="strSheetName"></param> private void ImportDataToTable(System.Data.DataTable dtSheetInfo, string strSheetName) { var client = storageAccount.CreateCloudTableClient(); string strTableName = txt_TableName.Text; if (!string.IsNullOrEmpty(strTableName)) { Response.Write(new string(' ', 1024)); Response.Write(String.Format("<div>Uploading {0} rows for sheet {1}", dtSheetInfo.Rows.Count, strSheetName.Replace("$", ""))); Response.Flush(); CloudTable table = client.GetTableReference(strTableName); table.CreateIfNotExists(); // Create a new partition key for this data instead of overwriting old data. var partitionKey = strSheetName + DateTime.UtcNow.ToString("o"); var batch = new TableBatchOperation(); for (int j = 0; j < dtSheetInfo.Rows.Count; j++) { ExcelTableEntity entity = new ExcelTableEntity(partitionKey, (j + 2).ToString("D5")); var hasContent = false; for (int i = 0; i < dtSheetInfo.Columns.Count; i++) { string strCloName = dtSheetInfo.Columns[i].ColumnName; if (!(dtSheetInfo.Rows[j][i] is DBNull) && (dtSheetInfo.Rows[j][i] != null)) { hasContent = true; string strValue = dtSheetInfo.Rows[j][i].ToString().Trim(); if (!CheckPropertyExist(strCloName, strValue, entity)) { EntityProperty property = entity.ConvertToEntityProperty(strCloName, dtSheetInfo.Rows[j][i]); if (!entity.properties.ContainsKey(strCloName)) { entity.properties.Add(strCloName, property); } else { entity.properties[strCloName] = property; } } } } if (hasContent) { batch.Add(TableOperation.InsertOrReplace(entity)); } if (batch.Count >= 100) { table.ExecuteBatch(batch); Response.Write("."); Response.Flush(); batch.Clear(); } } if (batch.Count > 0) { table.ExecuteBatch(batch); Response.Write("."); Response.Flush(); } var pointer = new ExcelTableEntity(strSheetName.Replace("$", ""), "Latest"); pointer.properties.Add("ID", new EntityProperty(partitionKey)); table.Execute(TableOperation.InsertOrReplace(pointer)); Response.Write(String.Format("\n PartitionKey: <code>{0}</code></div><hr/>", partitionKey)); Response.Flush(); } }
public override void ClearData() { Table.DeleteIfExists(); _table = null; }
public UserRepository(StorageClientFactory clientFactory) { _table = clientFactory.GetTableClient() .GetTableReference("DataTable"); }
public EvaluationClient() { table = CreateTable(); }
public static async Task <object> Run([HttpTrigger(WebHookType = "genericJson")] HttpRequestMessage req, TraceWriter log, Microsoft.Azure.WebJobs.ExecutionContext execContext) { // Variables int taskindex = 0; int OutputMES = -1; int OutputPremium = -1; int OutputIndex1 = -1; int OutputMesThumbnails = -1; int id = 0; string programid = ""; string programName = ""; string channelName = ""; string programUrl = ""; string programState = ""; string lastProgramState = ""; IJob job = null; ITask taskEncoding = null; int NumberJobsQueue = 0; int intervalsec = 60; // Interval for each subclip job (sec). Default is 60 TimeSpan starttime = TimeSpan.FromSeconds(0); TimeSpan duration = TimeSpan.FromSeconds(intervalsec); log.Info($"Webhook was triggered!"); string triggerStart = DateTime.UtcNow.ToString("o"); string jsonContent = await req.Content.ReadAsStringAsync(); dynamic data = JsonConvert.DeserializeObject(jsonContent); log.Info(jsonContent); if (data.channelName == null || data.programName == null) { return(req.CreateResponse(HttpStatusCode.BadRequest, new { error = "Please pass channel name and program name in the input object (channelName, programName)" })); } if (data.intervalSec != null) { intervalsec = (int)data.intervalSec; } MediaServicesCredentials amsCredentials = new MediaServicesCredentials(); log.Info($"Using Azure Media Service Rest API Endpoint : {amsCredentials.AmsRestApiEndpoint}"); try { AzureAdTokenCredentials tokenCredentials = new AzureAdTokenCredentials(amsCredentials.AmsAadTenantDomain, new AzureAdClientSymmetricKey(amsCredentials.AmsClientId, amsCredentials.AmsClientSecret), AzureEnvironments.AzureCloudEnvironment); AzureAdTokenProvider tokenProvider = new AzureAdTokenProvider(tokenCredentials); _context = new CloudMediaContext(amsCredentials.AmsRestApiEndpoint, tokenProvider); // find the Channel, Program and Asset channelName = (string)data.channelName; var channel = _context.Channels.Where(c => c.Name == channelName).FirstOrDefault(); if (channel == null) { log.Info("Channel not found"); return(req.CreateResponse(HttpStatusCode.BadRequest, new { error = "Channel not found" })); } programName = (string)data.programName; var program = channel.Programs.Where(p => p.Name == programName).FirstOrDefault(); if (program == null) { log.Info("Program not found"); return(req.CreateResponse(HttpStatusCode.BadRequest, new { error = "Program not found" })); } programState = program.State.ToString(); programid = program.Id; var asset = ManifestHelpers.GetAssetFromProgram(_context, programid); if (asset == null) { log.Info($"Asset not found for program {programid}"); return(req.CreateResponse(HttpStatusCode.BadRequest, new { error = "Asset not found" })); } log.Info($"Using asset Id : {asset.Id}"); // Table storage to store and real the last timestamp processed // Retrieve the storage account from the connection string. CloudStorageAccount storageAccount = new CloudStorageAccount(new StorageCredentials(amsCredentials.StorageAccountName, amsCredentials.StorageAccountKey), true); // Create the table client. CloudTableClient tableClient = storageAccount.CreateCloudTableClient(); // Retrieve a reference to the table. CloudTable table = tableClient.GetTableReference("liveanalytics"); // Create the table if it doesn't exist. if (!table.CreateIfNotExists()) { log.Info($"Table {table.Name} already exists"); } else { log.Info($"Table {table.Name} created"); } var lastendtimeInTable = ManifestHelpers.RetrieveLastEndTime(table, programid); // Get the manifest data (timestamps) var assetmanifestdata = ManifestHelpers.GetManifestTimingData(_context, asset, log); if (assetmanifestdata.Error) { return(req.CreateResponse(HttpStatusCode.InternalServerError, new { error = "Data cannot be read from program manifest." })); } log.Info("Timestamps: " + string.Join(",", assetmanifestdata.TimestampList.Select(n => n.ToString()).ToArray())); var livetime = TimeSpan.FromSeconds((double)assetmanifestdata.TimestampEndLastChunk / (double)assetmanifestdata.TimeScale); log.Info($"Livetime: {livetime}"); starttime = ManifestHelpers.ReturnTimeSpanOnGOP(assetmanifestdata, livetime.Subtract(TimeSpan.FromSeconds(intervalsec))); log.Info($"Value starttime : {starttime}"); if (lastendtimeInTable != null) { lastProgramState = lastendtimeInTable.ProgramState; log.Info($"Value ProgramState retrieved : {lastProgramState}"); var lastendtimeInTableValue = TimeSpan.Parse(lastendtimeInTable.LastEndTime); log.Info($"Value lastendtimeInTable retrieved : {lastendtimeInTableValue}"); id = int.Parse(lastendtimeInTable.Id); log.Info($"Value id retrieved : {id}"); if (lastendtimeInTableValue != null) { var delta = (livetime - lastendtimeInTableValue - TimeSpan.FromSeconds(intervalsec)).Duration(); log.Info($"Delta: {delta}"); //if (delta < (new TimeSpan(0, 0, 3*intervalsec))) // less than 3 times the normal duration (3*60s) if (delta < (TimeSpan.FromSeconds(3 * intervalsec))) // less than 3 times the normal duration (3*60s) { starttime = lastendtimeInTableValue; log.Info($"Value new starttime : {starttime}"); } } } duration = livetime - starttime; log.Info($"Value duration: {duration}"); if (duration == new TimeSpan(0)) // Duration is zero, this may happen sometimes ! { return(req.CreateResponse(HttpStatusCode.InternalServerError, new { error = "Stopping. Duration of subclip is zero." })); } // D:\home\site\wwwroot\Presets\LiveSubclip.json string ConfigurationSubclip = File.ReadAllText(Path.Combine(System.IO.Directory.GetParent(execContext.FunctionDirectory).FullName, "presets", "LiveSubclip.json")).Replace("0:00:00.000000", starttime.Subtract(TimeSpan.FromMilliseconds(100)).ToString()).Replace("0:00:30.000000", duration.Add(TimeSpan.FromMilliseconds(200)).ToString()); int priority = 10; if (data.priority != null) { priority = (int)data.priority; } // MES Subclipping TASK // Declare a new encoding job with the Standard encoder job = _context.Jobs.Create("Azure Function - Job for Live Analytics - " + programName, priority); // Get a media processor reference, and pass to it the name of the // processor to use for the specific task. IMediaProcessor processor = MediaServicesHelper.GetLatestMediaProcessorByName(_context, "Media Encoder Standard"); // Change or modify the custom preset JSON used here. // string preset = File.ReadAllText("D:\home\site\wwwroot\Presets\H264 Multiple Bitrate 720p.json"); // Create a task with the encoding details, using a string preset. // In this case "H264 Multiple Bitrate 720p" system defined preset is used. taskEncoding = job.Tasks.AddNew("Subclipping task", processor, ConfigurationSubclip, TaskOptions.None); // Specify the input asset to be encoded. taskEncoding.InputAssets.Add(asset); OutputMES = taskindex++; // Add an output asset to contain the results of the job. // This output is specified as AssetCreationOptions.None, which // means the output asset is not encrypted. var subclipasset = taskEncoding.OutputAssets.AddNew(asset.Name + " subclipped " + triggerStart, JobHelpers.OutputStorageFromParam(data.mesSubclip), AssetCreationOptions.None); log.Info($"Adding media analytics tasks"); //new OutputIndex1 = JobHelpers.AddTask(execContext, _context, job, subclipasset, (data.indexV1 == null) ? (string)data.indexV1Language : ((string)data.indexV1.language ?? "English"), "Azure Media Indexer", "IndexerV1.xml", "English", ref taskindex, specifiedStorageAccountName: JobHelpers.OutputStorageFromParam(data.indexV1)); // MES Thumbnails OutputMesThumbnails = JobHelpers.AddTask(execContext, _context, job, subclipasset, (data.mesThumbnails != null) ? ((string)data.mesThumbnails.Start ?? "{Best}") : null, "Media Encoder Standard", "MesThumbnails.json", "{Best}", ref taskindex, specifiedStorageAccountName: JobHelpers.OutputStorageFromParam(data.mesThumbnails)); job.Submit(); log.Info("Job Submitted"); id++; ManifestHelpers.UpdateLastEndTime(table, starttime + duration, programid, id, program.State); log.Info($"Output MES index {OutputMES}"); // Let store some data in altid of subclipped asset var sid = JobHelpers.ReturnId(job, OutputMES); log.Info($"SID {sid}"); var subclipassetrefreshed = _context.Assets.Where(a => a.Id == sid).FirstOrDefault(); log.Info($"subclipassetrefreshed ID {subclipassetrefreshed.Id}"); subclipassetrefreshed.AlternateId = JsonConvert.SerializeObject(new ManifestHelpers.SubclipInfo() { programId = programid, subclipStart = starttime, subclipDuration = duration }); subclipassetrefreshed.Update(); // Let store some data in altid of index assets var index1sid = JobHelpers.ReturnId(job, OutputIndex1); if (index1sid != null) { var index1assetrefreshed = _context.Assets.Where(a => a.Id == index1sid).FirstOrDefault(); log.Info($"index1assetrefreshed ID {index1assetrefreshed.Id}"); index1assetrefreshed.AlternateId = JsonConvert.SerializeObject(new ManifestHelpers.SubclipInfo() { programId = programid, subclipStart = starttime, subclipDuration = duration }); index1assetrefreshed.Update(); } // Get program URL var publishurlsmooth = MediaServicesHelper.GetValidOnDemandURI(_context, asset); if (publishurlsmooth != null) { programUrl = publishurlsmooth.ToString(); } NumberJobsQueue = _context.Jobs.Where(j => j.State == JobState.Queued).Count(); } catch (Exception ex) { string message = ex.Message + ((ex.InnerException != null) ? Environment.NewLine + MediaServicesHelper.GetErrorMessage(ex) : ""); log.Info($"ERROR: Exception {message}"); return(req.CreateResponse(HttpStatusCode.InternalServerError, new { error = message })); } log.Info("Job Id: " + job.Id); log.Info("Output asset Id: " + ((OutputMES > -1) ? JobHelpers.ReturnId(job, OutputMES) : JobHelpers.ReturnId(job, OutputPremium))); return(req.CreateResponse(HttpStatusCode.OK, new { triggerStart = triggerStart, jobId = job.Id, subclip = new { assetId = JobHelpers.ReturnId(job, OutputMES), taskId = JobHelpers.ReturnTaskId(job, OutputMES), start = starttime, duration = duration, }, mesThumbnails = new { assetId = JobHelpers.ReturnId(job, OutputMesThumbnails), taskId = JobHelpers.ReturnTaskId(job, OutputMesThumbnails) }, indexV1 = new { assetId = JobHelpers.ReturnId(job, OutputIndex1), taskId = JobHelpers.ReturnTaskId(job, OutputIndex1), language = (string)data.indexV1Language }, channelName = channelName, programName = programName, programId = programid, programUrl = programUrl, programState = programState, programStateChanged = (lastProgramState != programState).ToString(), otherJobsQueue = NumberJobsQueue })); }
public ProductsController() { storageAccount = CloudStorageAccount.Parse(ConfigurationManager.ConnectionStrings["AzureWebJobsStorage"].ToString()); tableClient = storageAccount.CreateCloudTableClient(); table = tableClient.GetTableReference("Products"); }
async public Task <string> GetFullString() { TableOperation retrieveOperation1 = TableOperation.Retrieve <varsGenderEntity>("gender", "gender"); TableOperation retrieveOperation2 = TableOperation.Retrieve <varsEntity>("rakaat", "rakaat"); TableOperation retrieveOperation3 = TableOperation.Retrieve <varsEntity>("isWaiting", "isWaiting"); TableOperation retrieveOperation4 = TableOperation.Retrieve <varsEntity>("rakaat1", "rakaat1"); // Execute the retrieve operation. CloudStorageAccount storageAccount = CloudStorageAccount.Parse( CloudConfigurationManager.GetSetting("StorageConnectionString")); CloudTableClient tableClient = storageAccount.CreateCloudTableClient(); CloudTable varsTable = tableClient.GetTableReference("varsTable"); TableResult retrievedResult1 = await varsTable.ExecuteAsync(retrieveOperation1); TableResult retrievedResult2 = await varsTable.ExecuteAsync(retrieveOperation2); TableResult retrievedResult3 = await varsTable.ExecuteAsync(retrieveOperation3); TableResult retrievedResult4 = await varsTable.ExecuteAsync(retrieveOperation4); TimeZoneInfo myTimeZone = TimeZoneInfo.FindSystemTimeZoneById("Israel Standard Time"); DateTime currentDateTime = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, myTimeZone); /*XmlDocument doc1 = new XmlDocument(); * doc1.Load("http://api.xhanch.com/islamic-get-prayer-time.php?lng=35.00931&lat=32.76158&yy=" + currentDateTime.Year.ToString() + * "&mm=" + currentDateTime.Month.ToString() + "&gmt=2"); * * XmlElement root = doc1.DocumentElement;*/ string gender = ((varsGenderEntity)(retrievedResult1.Result)).value; string rakaat = ((varsEntity)(retrievedResult2.Result)).value; string isWaiting = ((varsEntity)(retrievedResult3.Result)).value; string rakaat1 = ((varsEntity)(retrievedResult4.Result)).value; string str = /*(root.GetElementsByTagName("fajr"))[currentDateTime.Day - 1].InnerXml;*/ "02:54"; string fajrtime = "" + (int.Parse("" + str[0] + str[1]) + 1).ToString("00") + ":" + str[3] + str[4]; string str2 = /*(root.GetElementsByTagName("zuhr"))[currentDateTime.Day - 1].InnerXml;*/ "11:37"; string zuhrtime = "" + (int.Parse("" + str2[0] + str2[1]) + 1).ToString("00") + ":" + str2[3] + str2[4]; string str3 = /*(root.GetElementsByTagName("asr"))[currentDateTime.Day - 1].InnerXml;*/ "15:17"; string asrtime = "" + (int.Parse("" + str3[0] + str3[1]) + 1).ToString("00") + ":" + str3[3] + str3[4]; string str4 = /*(root.GetElementsByTagName("maghrib"))[currentDateTime.Day - 1].InnerXml;*/ "18:48"; string maghribtime = "" + (int.Parse("" + str4[0] + str4[1]) + 1).ToString("00") + ":" + str4[3] + str4[4]; string str5 = /*(root.GetElementsByTagName("isha"))[currentDateTime.Day - 1].InnerXml;*/ "20:20"; string ishatime = "" + (int.Parse("" + str5[0] + str5[1]) + 1).ToString("00") + ":" + str5[3] + str5[4]; PrayerTimeController x = new PrayerTimeController(); string currentPrayer = x.GetPrayer(); DateTime a = ((varsGenderEntity)(retrievedResult1.Result)).first; TimeSpan span = ((varsGenderEntity)(retrievedResult1.Result)).last - ((varsGenderEntity)(retrievedResult1.Result)).first; return("" + gender + " " + rakaat + " " + fajrtime + " " + zuhrtime + " " + asrtime + " " + maghribtime + " " + ishatime + " " + currentPrayer + " " + span.Minutes.ToString() + " " + span.Seconds.ToString() + " " + a.Year + " " + a.Month + " " + a.Day + " " + a.Hour + " " + a.Minute + " " + a.Second + " " + currentDateTime.Year + " " + currentDateTime.Month + " " + currentDateTime.Day + " " + currentDateTime.Hour + " " + currentDateTime.Minute + " " + currentDateTime.Second + " " + isWaiting + " " + rakaat1); }
public AzureEventStore(CloudTable eventTable, IMessageSerializer serializer) { _eventTable = eventTable ?? throw new ArgumentNullException(nameof(eventTable)); _serializer = serializer ?? throw new ArgumentNullException(nameof(serializer)); }
public PartnerService(CloudTable table) : base(table) { }
public static Task <IEnumerable <TEntity> > Query <TEntity>(this CloudTable table, string qryString, int Take, int Skip, params string[] columns) where TEntity : ITableEntity, new() { return(TableExtensions.Query <TEntity>(table, qryString, Take, Skip, null, columns)); }
public static async Task <List <T> > GetAllAsync <T>(this CloudTable cloudTable) { TableQuery <DynamicTableEntity> query = new TableQuery <DynamicTableEntity>(); return(await GetAllByQueryAsync <T>(cloudTable, query)); }
public static async Task DeleteEntity(this CloudTable table, ITableEntity entity) { var addItem = TableOperation.Delete(entity); await table.ExecuteAsync(addItem); }
public TableRepository(IGetCloudTable tables) { _CloudTable = tables.GetTable(true); }
public static async Task <ITableEntity> Replace(this CloudTable table, ITableEntity entity) { var replaceItem = TableOperation.Replace(entity); return((await table.ExecuteAsync(replaceItem)).Result as ITableEntity); }
public TableStorageProvider(CloudTable cloudTable) { this.cloudTable = cloudTable; }
public static async Task <T> Get <T>(this CloudTable table, string partitionKey, string rowKey) where T : class, ITableEntity, new() { var entity = await table.ExecuteAsync(TableOperation.Retrieve <T>(partitionKey, rowKey)); return(entity?.Result as T); }
static void CreateMessage(CloudTable table, EmailEntity newemail) { TableOperation insert = TableOperation.Insert(newemail); table.Execute(insert); }
private async Task <Tuple <List <T>, CMPStorageError> > FetchForFilterAsync <T>(CloudTable tableReference, string filterConditionString, FetchProgressCallback <T> fetchProgressCallback = null) where T : CMPTableStorageModel, new() { if ((tableReference == null) || (string.IsNullOrEmpty(filterConditionString) == true)) { return(new Tuple <List <T>, CMPStorageError>(null, null)); } var tableQuery = new TableQuery <T>().Where(filterConditionString); TableContinuationToken token = null; var fetchedResultsList = new List <T>(); do { var tableQuerySegment = await tableReference.ExecuteQuerySegmentedAsync(tableQuery, token); var currentResultsList = tableQuerySegment?.Results?.Cast <T>().ToList(); if (fetchProgressCallback != null) { fetchProgressCallback.Invoke(currentResultsList); } fetchedResultsList.AddRange(currentResultsList); token = tableQuerySegment.ContinuationToken; } while (token != null); return(new Tuple <List <T>, CMPStorageError>(fetchedResultsList, null)); }
public static async Task <IActionResult> Run( [HttpTrigger(AuthorizationLevel.Function, "get", "post", "delete", Route = null)] HttpRequest req, ILogger log) { log.LogInformation("C# HTTP trigger function processed a request."); string nomina = ""; string fecha = ""; if ((string)req.Method == "POST") { log.LogInformation("C# HTTP trigger function processed a request."); nomina = req.Query["nomina"]; fecha = req.Query["fecha"]; string requestBody = await new StreamReader(req.Body).ReadToEndAsync(); dynamic data = JsonConvert.DeserializeObject(requestBody); nomina = nomina ?? data?.nomina; fecha = fecha ?? data?.fecha; nomina = nomina.ToUpper(); var provider = new CultureInfo("es-MX"); DateTime fechaTemp = DateTime.Now; if (fecha == "" && nomina == "") { return(new OkObjectResult(JsonConvert.SerializeObject(new { Resultado = "NoNominaOSesion" }))); } else if (!Regex.IsMatch(nomina.Trim(), @"(^L(\d{8})$)|^l(\d{8})$") || !Regex.IsMatch(fecha.Trim(), @"^20[0-9]{2}\-[0-1]{0,1}[0-9]{1}\-[0-3]{0,1}[0-9]{1}$")) { return(new OkObjectResult(JsonConvert.SerializeObject(new { Resultado = "FormatosIncorrectos" }))); } try{ fechaTemp = DateTime.ParseExact(fecha, "yyyy-M-d", provider); if (DateTime.Now > fechaTemp) { return(new OkObjectResult(JsonConvert.SerializeObject(new { Resultado = "SesionExpirada" }))); } //fecha=fechaTemp;//.ToString("dd-MM-yyyy"); } catch { log.LogInformation("FALLO EN PARSE"); return(new OkObjectResult(JsonConvert.SerializeObject(new { Resultado = "FormatosIncorrectos" }))); } SecretClientOptions options = new SecretClientOptions() { Retry = { Delay = TimeSpan.FromSeconds(2), MaxDelay = TimeSpan.FromSeconds(16), MaxRetries = 5, Mode = RetryMode.Exponential } }; DateTime fechaSesion = DateTime.ParseExact(fechaTemp.ToString("yyyy-MM-dd") + " " + "17:00", "yyyy-MM-dd HH:mm", null).ToUniversalTime(); var client = new SecretClient(new Uri("https://kevaultchatbot.vault.azure.net/"), new DefaultAzureCredential(), options); KeyVaultSecret secret = client.GetSecret("storageTablas"); string secretValue = secret.Value; CloudStorageAccount storageAccount; storageAccount = CloudStorageAccount.Parse(secretValue); CloudTableClient tableClient = storageAccount.CreateCloudTableClient(new TableClientConfiguration()); CloudTable tableAsistente = tableClient.GetTableReference("asistente"); CloudTable tableUsuario = tableClient.GetTableReference("usuario"); CloudTable tableSesion = tableClient.GetTableReference("sesion"); List <Usuario> usuario = tableUsuario.CreateQuery <Usuario>().AsQueryable <Usuario>().Where(e => e.PartitionKey == "Empleado" && e.nomina == nomina).ToList(); List <Sesion> sesion = tableSesion.CreateQuery <Sesion>().AsQueryable <Sesion>().Where(e => e.PartitionKey == "Sesiones" && e.fecha_evento == fechaSesion && e.estatus == "Reservada").ToList(); if (usuario.Count == 1 && sesion.Count == 1) { List <Asistente> asistente = tableAsistente.CreateQuery <Asistente>().AsQueryable <Asistente>().Where(e => e.PartitionKey == sesion[0].idSesion && e.RowKey == nomina).ToList(); if (asistente.Count > 0) { List <Asistente> asistenteRegistrado = tableAsistente.CreateQuery <Asistente>().AsQueryable <Asistente>().Where(e => e.PartitionKey == sesion[0].idSesion && e.RowKey == nomina && e.asistencia == "S").ToList(); if (asistenteRegistrado.Count > 0) { return(new OkObjectResult(JsonConvert.SerializeObject(new { Resultado = "YaRegistrado" }))); } else { try{ asistenteRegistrado[0].asistencia = "S"; asistente[0].fechaRegistro = DateTime.Now.ToString("dd/MM/yyyy"); TableOperation insertOrMergeOperation = TableOperation.InsertOrMerge(asistenteRegistrado[0]); TableResult result = await tableAsistente.ExecuteAsync(insertOrMergeOperation); } catch (Exception e) { log.LogInformation(e.Message); return(new OkObjectResult(JsonConvert.SerializeObject(new { Resultado = "ErrorInsert" }))); } } } else { try{ Asistente entity = new Asistente(); entity.idSesion = sesion[0].idSesion; entity.nomina_asistente = nomina; entity.fechaRegistro = DateTime.Now.ToString("dd/MM/yyyy"); entity.asistencia = "S"; entity.PartitionKey = entity.idSesion; entity.RowKey = nomina; // Create the InsertOrReplace table operation TableOperation insertOrMergeOperation = TableOperation.InsertOrMerge(entity); // Execute the operation. TableResult result = await tableAsistente.ExecuteAsync(insertOrMergeOperation); } catch (Exception e) { log.LogInformation(e.Message); return(new OkObjectResult(JsonConvert.SerializeObject(new { Resultado = "ErrorInsert" }))); } } } else { log.LogInformation(fechaSesion.ToString()); log.LogInformation(sesion.Count.ToString()); log.LogInformation(nomina); return(new OkObjectResult(JsonConvert.SerializeObject(new { Resultado = "NoNominaOSesion" }))); } } if ((string)req.Method == "DELETE") { } return(new OkObjectResult(JsonConvert.SerializeObject(new { Resultado = "OK" }))); }
public void Init() { instance = new CloudTable(); }
public EventSubscriptionStateRepository(CloudTable table) : base(table) { }
public ActionResult DeleteEntity(string id, string partKey = PartitionKey) { try { var entities = new CloudTable<Analysis>(Providers.TableStorage, TableName); entities.Delete(partKey, id); return RedirectToAction("Index"); } catch { return View(); } }
internal bool CheckTableAndContent(string StorageAccountName, string TableName, string FilterString, string WaitChar, bool UseNewTableNames, int TimeoutinMinutes = 15) { var tableExists = false; StorageAccount account = null; if (!String.IsNullOrEmpty(StorageAccountName)) { account = this.GetStorageAccountFromCache(StorageAccountName); } if (account != null) { var endpoint = this.GetCoreEndpoint(StorageAccountName); var key = this.GetAzureStorageKeyFromCache(StorageAccountName); var credentials = new StorageCredentials(StorageAccountName, key); var cloudStorageAccount = new CloudStorageAccount(credentials, endpoint, true); var tableClient = cloudStorageAccount.CreateCloudTableClient(); var checkStart = DateTime.Now; var wait = true; CloudTable table = null; if (UseNewTableNames) { try { table = tableClient.ListTablesSegmentedAsync(currentToken: null) .ConfigureAwait(false).GetAwaiter().GetResult() .FirstOrDefault(tab => tab.Name.StartsWith("WADMetricsPT1M")); } catch { } //#table name should be sorted } else { try { table = tableClient.GetTableReference(TableName); } catch { } } while (wait) { if (table != null && table.ExistsAsync().ConfigureAwait(false).GetAwaiter().GetResult()) { TableQuery query = new TableQuery(); query.FilterString = FilterString; var results = table.ExecuteQuerySegmentedAsync(query, token: null) .ConfigureAwait(false).GetAwaiter().GetResult(); if (results.Count() > 0) { tableExists = true; break; } } WriteHost(WaitChar, newLine: false); TestMockSupport.Delay(5000); if (UseNewTableNames) { try { table = tableClient.ListTablesSegmentedAsync(currentToken: null) .ConfigureAwait(false).GetAwaiter().GetResult().FirstOrDefault(tab => tab.Name.StartsWith("WADMetricsPT1M")); } catch { } //#table name should be sorted } else { try { table = tableClient.GetTableReference(TableName); } catch { } } wait = ((DateTime.Now) - checkStart).TotalMinutes < TimeoutinMinutes; } } return(tableExists); }
private static AnalysisView GetOneAnalysis(string id, string partKey) { AnalysisView view = null; var entities = new CloudTable<Analysis>(Providers.TableStorage, TableName); var analysis = entities.Get(partKey, id); if (analysis.HasValue) view = Mapper.Map<AnalysisView>(analysis.Value); return view; }
private static async Task CreateTableIfNotExistsAsync(DbTableSchema dbTableSchema, CloudTable table) { await table.CreateIfNotExistsAsync(); }
/* * Load Data Button: * Loads data from the azure URL provided in the program instructions. * Populates an azure table storage with entries parsed from the input file * containing a last name, first name, and variable number of attributes */ protected void Button1_Click(object sender, EventArgs e) { const string DataURL = "http://css490.blob.core.windows.net/lab4/input.txt"; // Establish connection to the specified URL and store it as // an object in blob storage // Flow: Account -> Container -> Blob (actual file) Label1.Text = "Connecting to Storage Account"; String storageconn = System.Configuration.ConfigurationManager.AppSettings.Get("StorageConnectionString"); CloudStorageAccount storageacc = CloudStorageAccount.Parse(storageconn); CloudBlobClient blobClient = storageacc.CreateCloudBlobClient(); // Create container "P4Container" if none exists CloudBlobContainer container = blobClient.GetContainerReference("p4container"); container.CreateIfNotExists(); CloudBlockBlob blockBlob = container.GetBlockBlobReference("input.txt"); CloudTableClient tableClient = storageacc.CreateCloudTableClient(); CloudTable inputTable = tableClient.GetTableReference("p4inputTable"); DeleteAllTableEntities(ref blockBlob, ref inputTable); Label1.Text = "Uploading Input File"; // Upload file from DataURL to a blob in the P4Container var req = System.Net.WebRequest.Create(DataURL); using (Stream filestream = req.GetResponse().GetResponseStream()) { blockBlob.UploadFromStream(filestream); } Label1.Text = "Blob Successfully Uploaded"; // Running it again would simply update it, since the same container is reused //-------------- // Next Step, parse the file into Azure Table entries // Delete table entries if previous data was already stored. inputTable.CreateIfNotExists(); // Create a class that defines the properties of each entity // First name, last name, variable number of properties (vector?) // Get the input file text from blockBlob reference string inputText = blockBlob.DownloadText(); using (StringReader reader = new StringReader(inputText)) { // Load all entries into an insert operation. Can't use a batch operation // since the primary key (last name) isn't guaranteed to be the same string line = ""; while ((line = reader.ReadLine()) != null) { // Split string. First and last name are stored in the first two elements. // Everything else is an attribute char[] delimiters = { ' ' }; string[] info = line.Split(delimiters, StringSplitOptions.RemoveEmptyEntries); string attributes = ""; for (int i = 2; i < info.Length; i++) { attributes += info[i] + " "; } InputEntity newEntry = new InputEntity(info[0], info[1], attributes); TableOperation insertOperation = TableOperation.Insert(newEntry); inputTable.ExecuteAsync(insertOperation); } // Push INSERT operation //inputTable.ExecuteBatchAsync(batchOperation); Label1.Text = "Successfully added input to table"; Button3.Enabled = true; Label2.Text = ""; } }
public UniqueNamingScheme(CloudInfrastructureProviders providers) { _containers = new CloudTable<ContainerState>(providers.TableStorage, Names.ContainerStateTable); }
public void TableSASConstructors() { CloudTableClient tableClient = GenerateCloudTableClient(); CloudTable table = tableClient.GetTableReference("T" + Guid.NewGuid().ToString("N")); try { table.Create(); TableServiceContext context = tableClient.GetTableServiceContext(); context.AddObject(table.Name, new BaseEntity("PK", "RK")); context.SaveChangesWithRetries(); // Prepare SAS authentication with full permissions string sasToken = table.GetSharedAccessSignature( new SharedAccessTablePolicy { Permissions = SharedAccessTablePermissions.Add | SharedAccessTablePermissions.Delete | SharedAccessTablePermissions.Query, SharedAccessExpiryTime = DateTimeOffset.Now.AddMinutes(30) }, null /* accessPolicyIdentifier */, null /* startPk */, null /* startRk */, null /* endPk */, null /* endRk */); CloudStorageAccount sasAccount; StorageCredentials sasCreds; CloudTableClient sasClient; CloudTable sasTable; TableServiceContext sasContext; Uri baseUri = new Uri(TestBase.TargetTenantConfig.TableServiceEndpoint); int count; // SAS via connection string parse sasAccount = CloudStorageAccount.Parse(string.Format("TableEndpoint={0};SharedAccessSignature={1}", baseUri.AbsoluteUri, sasToken)); sasClient = sasAccount.CreateCloudTableClient(); sasTable = sasClient.GetTableReference(table.Name); sasContext = sasClient.GetTableServiceContext(); count = sasContext.CreateQuery<BaseEntity>(sasTable.Name).AsTableServiceQuery(sasContext).Execute().Count(); Assert.AreEqual(1, count); // SAS via account constructor sasCreds = new StorageCredentials(sasToken); sasAccount = new CloudStorageAccount(sasCreds, null, null, baseUri); sasClient = sasAccount.CreateCloudTableClient(); sasTable = sasClient.GetTableReference(table.Name); sasContext = sasClient.GetTableServiceContext(); count = sasContext.CreateQuery<BaseEntity>(sasTable.Name).AsTableServiceQuery(sasContext).Execute().Count(); Assert.AreEqual(1, count); // SAS via client constructor URI + Creds sasCreds = new StorageCredentials(sasToken); sasClient = new CloudTableClient(baseUri, sasCreds); sasContext = sasClient.GetTableServiceContext(); count = sasContext.CreateQuery<BaseEntity>(sasTable.Name).AsTableServiceQuery(sasContext).Execute().Count(); Assert.AreEqual(1, count); // SAS via CloudTable constructor Uri + Client sasCreds = new StorageCredentials(sasToken); sasTable = new CloudTable(table.Uri, tableClient); sasClient = sasTable.ServiceClient; sasContext = sasClient.GetTableServiceContext(); count = sasContext.CreateQuery<BaseEntity>(sasTable.Name).AsTableServiceQuery(sasContext).Execute().Count(); Assert.AreEqual(1, count); } finally { table.DeleteIfExists(); } }
/// <summary> /// Initializes a new instance of the <see cref="TableLoggingService"/> class. /// </summary> public TableLoggingService() { logTable = this.GetConnectionTable(); }
private static void SaveAnalysis(Analysis analysis, string partKey = PartitionKey) { var rowkey = ShortGuid.NewGuid().Value; var cloudObject = new CloudEntity<Analysis> { PartitionKey = partKey, RowKey = rowkey, Value = analysis }; var entities = new CloudTable<Analysis>(Providers.TableStorage, TableName); entities.Insert(cloudObject); }
public static HttpResponseMessage AddTable([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequestMessage req, [Table("sampletable")] CloudTable table, ILogger log) { return(new AddTableFunction(table, req, log).Execute()); }
/* * Query button: * Queries the currently stored table for a last name and first name. * Displays the names of matching results and their attributes. * * Precondition: The input file and corresponding table must already * be stored. Query button is disabled otherwise */ protected void Button3_Click(object sender, EventArgs e) { String storageconn = System.Configuration.ConfigurationManager.AppSettings.Get("StorageConnectionString"); CloudStorageAccount storageacc = CloudStorageAccount.Parse(storageconn); CloudBlobClient blobClient = storageacc.CreateCloudBlobClient(); CloudTableClient tableClient = storageacc.CreateCloudTableClient(); CloudTable inputTable = tableClient.GetTableReference("p4inputTable"); // Case 1: Partition and row key provided (last and first name) if (TextBox1.Text != "" && TextBox2.Text != "") { TableOperation retrieveOperation = TableOperation.Retrieve <InputEntity>(TextBox1.Text, TextBox2.Text); TableResult retrievedResult = inputTable.Execute(retrieveOperation); if (retrievedResult.Result != null) { TableRow r = new TableRow(); TableCell cLast = new TableCell(); TableCell cFirst = new TableCell(); TableCell cAtr = new TableCell(); cLast.Text = ((InputEntity)retrievedResult.Result).PartitionKey; cFirst.Text = ((InputEntity)retrievedResult.Result).RowKey; cAtr.Text = ((InputEntity)retrievedResult.Result).attributes; r.Cells.Add(cLast); r.Cells.Add(cFirst); r.Cells.Add(cAtr); Table1.Rows.Add(r); } else { // Output empty row TableRow r = new TableRow(); TableCell cEmpt = new TableCell(); cEmpt.Text = "No results found"; r.Cells.Add(cEmpt); Table1.Rows.Add(r); } } // Case 2: Only partition key provided (last name) // Can return multiple results else if (TextBox1.Text != "") { // Code used from: // https://docs.microsoft.com/en-us/azure/visual-studio/vs-storage-aspnet5-getting-started- TableQuery <InputEntity> query = new TableQuery <InputEntity>().Where (TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, TextBox1.Text)); TableContinuationToken token = null; int resultCount = 0; do { TableQuerySegment <InputEntity> resultSegment = inputTable.ExecuteQuerySegmented(query, token); token = resultSegment.ContinuationToken; foreach (InputEntity entity in resultSegment.Results) { resultCount++; TableRow r = new TableRow(); TableCell cLast = new TableCell(); TableCell cFirst = new TableCell(); TableCell cAtr = new TableCell(); cLast.Text = entity.PartitionKey; cFirst.Text = entity.RowKey; cAtr.Text = entity.attributes; r.Cells.Add(cLast); r.Cells.Add(cFirst); r.Cells.Add(cAtr); Table1.Rows.Add(r); } } while (token != null); if (resultCount == 0) // No results found { // Output empty row TableRow r = new TableRow(); TableCell cEmpt = new TableCell(); cEmpt.Text = "No results found"; r.Cells.Add(cEmpt); Table1.Rows.Add(r); } } // Case 3: Only row key provided (first name) else { TableQuery <InputEntity> query = new TableQuery <InputEntity>().Where (TableQuery.GenerateFilterCondition("RowKey", QueryComparisons.Equal, TextBox2.Text)); TableContinuationToken token = null; int resultCount = 0; do { TableQuerySegment <InputEntity> resultSegment = inputTable.ExecuteQuerySegmented(query, token); token = resultSegment.ContinuationToken; foreach (InputEntity entity in resultSegment.Results) { resultCount++; TableRow r = new TableRow(); TableCell cLast = new TableCell(); TableCell cFirst = new TableCell(); TableCell cAtr = new TableCell(); cLast.Text = entity.PartitionKey; cFirst.Text = entity.RowKey; cAtr.Text = entity.attributes; r.Cells.Add(cLast); r.Cells.Add(cFirst); r.Cells.Add(cAtr); Table1.Rows.Add(r); } } while (token != null); if (resultCount == 0) // No results found { // Output empty row TableRow r = new TableRow(); TableCell cEmpt = new TableCell(); cEmpt.Text = "No results found"; r.Cells.Add(cEmpt); Table1.Rows.Add(r); } } }
public void MyTestInitialize() { CloudTableClient tableClient = GenerateCloudTableClient(); currentTable = tableClient.GetTableReference(GenerateRandomTableName()); currentTable.CreateIfNotExists(); }
public ActionResult Edit(AnalysisView updatedAnalysis) { try { var analysis = Mapper.Map<Analysis>(updatedAnalysis); var cloudObject = new CloudEntity<Analysis>() { PartitionKey = updatedAnalysis.AnalysisPartKey, RowKey = updatedAnalysis.AnalysisRowKey, Value = analysis }; var entities = new CloudTable<Analysis>(Providers.TableStorage, TableName); entities.Update(cloudObject); return RedirectToAction("Index"); } catch { return View(); } }