public async Task <TOutput> InvokeAsync <TPayload, TOutput>(TPayload payload, TraceWriter log) { object result = false; try { log?.Info("WebhookAFunction invoked."); var eventGridEvent = (payload as WebhookAFunctionModel)?.EventPayload; log?.Info($"Webhook A Fired" + $"\n\tId:{eventGridEvent?.Id}" + $"\n\tTopic:{eventGridEvent?.Topic}" + $"\n\tSubject:{eventGridEvent?.Subject}" + $"\n\tType:{eventGridEvent?.EventType}" + $"\n\tData:{eventGridEvent?.Data}"); result = true; } catch (Exception ex) { // log error message log?.Error($"Exception in function WebhookAFunction -> { ex.GetBaseException().Message }"); // bubble up exception, so that function handler can perform common error handling throw; } return(await Task.FromResult((TOutput)result)); }
static void Print(this DocumentClientException dex, TraceWriter log) { if ((int)dex.StatusCode == 429) { log?.Info("TooManyRequests - This means you have exceeded the number of request units per second. Consult the DocumentClientException.RetryAfter value to see how long you should wait before retrying this operation."); } else { switch (dex.StatusCode) { case HttpStatusCode.BadRequest: log?.Info("BadRequest - This means something was wrong with the document supplied. It is likely that disableAutomaticIdGeneration was true and an id was not supplied"); break; case HttpStatusCode.Forbidden: log?.Info("Forbidden - This likely means the collection in to which you were trying to create the document is full."); break; case HttpStatusCode.Conflict: log?.Info("Conflict - This means a Document with an id matching the id field of document already existed"); break; case HttpStatusCode.RequestEntityTooLarge: log?.Info("RequestEntityTooLarge - This means the Document exceeds the current max entity size. Consult documentation for limits and quotas."); break; default: break; } } }
public static IClusterClient GetInstance(TraceWriter log = null) { if (_instance == null) { log?.Info(@"Creating connection to Orleans silo..."); Trace.WriteLine(@"t: Creating connection to Orleans silo..."); //// Parse the IP Address out of app settings //var siloIpAddressString = Environment.GetEnvironmentVariable(@"SiloEndpointIP"); //var siloIpAddressBytes = siloIpAddressString.Split('.').Select(i => byte.Parse(i)).ToArray(); //// parse the port to uint to ensure the value is >=0 //var siloPort = uint.Parse(Environment.GetEnvironmentVariable(@"SiloEndpointPort")); //log?.Info($@" @ {siloIpAddressString}:{siloPort}"); //Trace.WriteLine($@"t: @ {siloIpAddressString}:{siloPort}"); var builder = new ClientBuilder() .Configure <ClusterOptions>(options => { options.ClusterId = @"ForFunctions"; options.ServiceId = @"AzureFunctionsSample"; }) .UseAzureStorageClustering(opt => opt.ConnectionString = Environment.GetEnvironmentVariable(@"ClusterStorageConnectionString")); _instance = builder.Build(); log?.Info(@"Client successfully built with Azure Storage clustering..."); Trace.WriteLine(@"t: Client successfully built with Azure Storage clustering..."); const int maxRetries = 5; int retryCount = 0; _instance.Connect(async ex => { log.Info(ex.Message); if (++retryCount < maxRetries) { await Task.Delay(TimeSpan.FromSeconds(3)); return(true); } else { return(false); } }).Wait(); log?.Info(@"Connected."); Trace.WriteLine(@"t: Connected."); } return(_instance); }
static async Task <(User user, bool created)> GetOrCreateUser(this DocumentClient client, string databaseId, string userId, TraceWriter log) { User user = null; try { log?.Info($" ... getting user ({userId}) in database ({databaseId})"); var response = await client.ReadUserAsync(UriFactory.CreateUserUri(databaseId, userId)); user = response?.Resource; if (user != null) { log?.Info($" ... found existing user ({userId}) in database ({databaseId})"); } return(user, false); } catch (DocumentClientException dcx) { dcx.Print(log); switch (dcx.StatusCode) { case HttpStatusCode.NotFound: log?.Info($" ... did not find user ({userId}) - creating..."); var response = await client.CreateUserAsync(UriFactory.CreateDatabaseUri(databaseId), new User { Id = userId }); user = response?.Resource; if (user != null) { log?.Info($" ... created new user ({userId}) in database ({databaseId})"); } return(user, user != null); default: throw; } } catch (Exception ex) { log?.Error($"Error getting User with Id: {userId}\n", ex); throw; } }
public static GameDTO GetGame(string gameId, TraceWriter log) { try { using (var client = new DocumentClient(new Uri(_endpointUri), _primaryKey)) { var game = client.CreateDocumentQuery <Game>( UriFactory.CreateDocumentCollectionUri(_dbName, _collectionName), new FeedOptions { MaxItemCount = 1 } ).Where(g => g.id == gameId).ToList().FirstOrDefault(); if (game != null) { return(game.ToDTO()); } else { log?.Info($"Could not find game with id {gameId}"); } } } catch (Exception e) { log?.Error(e.ToString()); return(null); } return(null); }
private static void InstallNetworkWatcherExtension(IVirtualMachine vm, TraceWriter log = null) { IVirtualMachineExtension extension = null; IReadOnlyDictionary <string, IVirtualMachineExtension> extensionList = vm.ListExtensions(); if (extensionList.Count > 0) { extension = extensionList.First(x => x.Value.PublisherName == "Microsoft.Azure.NetworkWatcher").Value; } if (extension == null) { log.Info($"VM doesn't have Network Watcher Extension... Installing"); vm.Update() .DefineNewExtension("packetcapture") .WithPublisher("Microsoft.Azure.NetworkWatcher") .WithType("NetworkWatcherAgentWindows") // TODO: determine OS family, can be NetworkWatcherAgentLinux .WithVersion("1.4") .Attach(); log?.Info("Installed Extension on " + vm.Name); } else { log.Info($"VM already has Network Watcher Extension: proceeding..."); } }
public static async Task <string> FindOpenGame(string userName, string clientId, TraceWriter log) { try { using (var client = new DocumentClient(new Uri(_endpointUri), _primaryKey)) { var freeGame = client.CreateDocumentQuery <Game>( UriFactory.CreateDocumentCollectionUri(_dbName, _collectionName), new FeedOptions { MaxItemCount = 1 } ).Where(g => g.SpotAvailable).ToList().FirstOrDefault(); if (freeGame != null) { var d = client.CreateDocumentQuery <Document>( UriFactory.CreateDocumentCollectionUri(_dbName, _collectionName), new FeedOptions { MaxItemCount = 1 } ).Where(g => g.Id == freeGame.id).ToList().FirstOrDefault(); Game toUpdate = (dynamic)d; log?.Info($"Found a game to join with id {freeGame.id} and Player1 {freeGame.Player1.Name} adding player with cid {clientId} and starting game"); GameController.AddPlayer(toUpdate, userName, clientId, false); GameController.StartGame(toUpdate); var replaced = await client.ReplaceDocumentAsync(d.SelfLink, toUpdate); return(replaced.Resource.Id); } else { log?.Info($"Creating a new game for player {userName} with clientid {clientId}"); freeGame = GameController.CreateGame(); GameController.AddPlayer(freeGame, userName, clientId); var d = await client.CreateDocumentAsync(UriFactory.CreateDocumentCollectionUri(_dbName, _collectionName), freeGame); return(d.Resource.Id); } } } catch (Exception e) { log.Error(e.ToString()); return(string.Empty); } }
public async Task <ResourceResponse <Database> > CreateDataBaseAsync(Database newDatabase, TraceWriter log, CancellationToken cts) { if (client != null && client.WriteEndpoint != null) { try { log?.Info($" Creating Database"); databaseConnected = await client.CreateDatabaseIfNotExistsAsync(newDatabase).ConfigureAwait(false); log?.Info($" Database Created"); return(databaseConnected); } catch (Exception e) { log?.Info($" Error while creating database : {e}"); throw; } } return(null); }
public async static Task <WordDefinitions> CachedLookUp(string word, TraceWriter log = null) { log?.Info($"cache lookup: {word}"); string xmlText = await AzureTableStorage.LookupCachedWord(word); var definitions = MariamWebseter.Parse(word, xmlText); if (definitions.Entreis.Any()) { return(definitions); } log?.Info($"2nd level lookup: {word}"); xmlText = await MariamWebseter.LookupMarimWebsterStudent2(word); definitions = MariamWebseter.Parse(word, xmlText); if (definitions.Entreis.Any()) { definitions.AudioFiles = DownloadAndUpdateAudios(definitions.AudioFiles); await AzureTableStorage.SaveWordDefinition(word, xmlText, definitions.AudioFiles); return(definitions); } log?.Info($"3nd level lookup: {word}"); xmlText = await MariamWebseter.LookupMarimWebsterStudent3(word); definitions = MariamWebseter.Parse(word, xmlText); if (definitions.Entreis.Any()) { definitions.AudioFiles = DownloadAndUpdateAudios(definitions.AudioFiles); await AzureTableStorage.SaveWordDefinition(word, xmlText, definitions.AudioFiles); return(definitions); } return(definitions); }
public async Task <ResourceResponse <DocumentCollection> > CreateCollectionAsync(Uri databaseUri, DocumentCollection documentCollection, TraceWriter log, CancellationToken cts) { if (client != null && client.WriteEndpoint != null) { // if (databaseConnected != null) try { log?.Info($" Creating Collection"); ResourceResponse <DocumentCollection> documentResponse = await client.CreateDocumentCollectionIfNotExistsAsync(databaseUri, documentCollection) .ConfigureAwait(false); log?.Info($" Collection created"); return(documentResponse); } catch (Exception e) { log?.Info($" Error while creating database : {e}"); throw; } } return(null); }
public async Task <DocumentClient> ConnectClientAsync(string endpointUrl, string primaryKey, TraceWriter log, CancellationToken cts) { try { client = new DocumentClient(new Uri(endpointUrl), primaryKey); log?.Info($"COSMOS DB Endpoint Connected"); return(await Task.FromResult(client).ConfigureAwait(false)); } catch (DocumentClientException de) { var baseException = de.GetBaseException(); log?.Info($"{de.StatusCode} error occurred: {de.Message}, Message: {baseException.Message}"); } catch (Exception e) { var baseException = e.GetBaseException(); log?.Info($"error occurred: {e.Message}, Message: {baseException.Message}"); } finally { log?.Info($"Cleared Finally"); } return(null); }
public object GetFromDatabase(string query, TraceWriter log) { try { var cnnString = ConfigurationManager.ConnectionStrings["sqldb_connection"].ConnectionString; using (var connection = new SqlConnection(cnnString)) { connection.Open(); using (var command = new SqlCommand(query, connection)) using (var reader = command.ExecuteReader()) { log?.Info("Query executed successfully!"); return(ReaderToObject(reader)); } } } catch (Exception e) { log?.Info(e.ToString()); return(null); } }
private static void InstallNetworkWatcherExtension(IVirtualMachine vm, TraceWriter log = null) { IVirtualMachineExtension extension = vm.ListExtensions().First(x => x.Value.PublisherName == "Microsoft.Azure.NetworkWatcher").Value; if (extension == null) { vm.Update() .DefineNewExtension("packetcapture") .WithPublisher("Microsoft.Azure.NetworkWatcher") .WithType("NetworkWatcherAgentWindows") // TODO: determine OS family, can be NetworkWatcherAgentLinux .WithVersion("1.4") .Attach(); log?.Info("Installed Extension on " + vm.Name); } }
public static async Task <UserStore> UpdateUserStore(this DocumentClient client, UserStore userStore, Permission permission, TraceWriter log = null) { try { if (string.IsNullOrEmpty(userStore?.Id) || string.IsNullOrEmpty(permission?.Token)) { return(null); } await client.EnsureCollection(UserStore.Collection); log?.Info($"Attempting to replace UserStore document with Id: {userStore.Id}"); userStore.Token = permission.Token; userStore.TokenTimestamp = DateTime.UtcNow; var response = await client.ReplaceDocumentAsync(userStore.SelfLink, userStore); var json = response?.Resource?.ToString(); return(string.IsNullOrEmpty(json) ? null : JsonConvert.DeserializeObject <UserStore> (json)); } catch (DocumentClientException dex) { dex.Print(log); switch (dex.StatusCode) { case HttpStatusCode.NotFound: var response = await client.CreateDocumentAsync(UriFactory.CreateDocumentCollectionUri(UserStore.DatabaseId, UserStore.CollectionId), userStore); var json = response?.Resource?.ToString(); return(string.IsNullOrEmpty(json) ? null : JsonConvert.DeserializeObject <UserStore> (json)); default: throw; } } catch (Exception ex) { log?.Error("Error saving new User", ex); throw; } }
private async Task InvokeSagaHandlers <T>(T message, AFBusMessageContext messageContext, TraceWriter log) where T : class { //The message can not be executed in a Saga if (!messageToSagaDictionary.ContainsKey(message.GetType())) { return; } var instantiated = await LookForCommandsProcessedByASaga(message, messageContext, log).ConfigureAwait(false); instantiated = instantiated || await LookForEventsProcessedBySagas(message, messageContext, log).ConfigureAwait(false); if (!instantiated) { log?.Info("Saga not found for message " + serializer.Serialize(message)); } }
public static async Task <dynamic> DataAsync(this HttpRequestMessage req, TraceWriter log = null) { try { string requestBody = await req.Content.ReadAsStringAsync(); log?.Info($"requestBody {requestBody}"); return(JsonConvert.DeserializeObject(requestBody)); } catch (Exception ex) { log?.Error("DataSync error", ex); throw; } }
public static async void Run([EventGridTrigger] EventGridEvent eventGridEvent, TraceWriter log) { log?.Info($"Function WebhookBHandler invoked."); try { var result = await FunctionActivator.Activate <IFunction>("WebhookB") .InvokeAsync <WebhookBFunctionModel, bool>(new WebhookBFunctionModel() { EventPayload = eventGridEvent }, log).ConfigureAwait(false); } catch (Exception ex) { log?.Error($"Exception in function WebhookBHandler -> { ex.GetBaseException().Message }"); } return; }
public static async Task <UserStore> SaveUserStore(this DocumentClient client, string userId, string email, UserRoles role, TraceWriter log = null) { var userStore = new UserStore { Id = userId, Email = email?.ToLower(), UserRole = role }; try { await client.EnsureCollection(UserStore.Collection); log?.Info($"Attempting to create new UserStore document with Id: {userId}"); var response = await client.CreateDocumentAsync(UsersCollectionLink, userStore); var json = response?.Resource?.ToString(); return(string.IsNullOrEmpty(json) ? null : JsonConvert.DeserializeObject <UserStore> (json)); } catch (DocumentClientException dex) { dex.Print(log); switch (dex.StatusCode) { case HttpStatusCode.Conflict: log.Info($"UserStore document with id: {userId} already exists, replacing..."); var response = await client.ReplaceDocumentAsync(UriFactory.CreateDocumentUri(UserStore.DatabaseId, UserStore.CollectionId, userId), userStore); var json = response?.Resource?.ToString(); return(string.IsNullOrEmpty(json) ? null : JsonConvert.DeserializeObject <UserStore> (json)); default: throw; } } catch (Exception ex) { log?.Error("Error saving new User", ex); throw; } }
public async Task <ResourceResponse <Document> > CreateDocumentAsync(string databaseName, string collectionName, VacancySummary vacancySummary, TraceWriter log, CancellationToken cts) { try { //await ConnectClientAsync("https://sfacosmosdb.documents.azure.com:443/", // "yeFYPdLaiTBP7cxEVxBB8x8gaJM5H5DCcthqZuVBUWAzwu5IH6UEpDMTBxFxPqjhArIRjAPtHDKsD1MJbSY2ZA ==", null, // new CancellationToken()); Thread.Sleep(500); //ResourceResponse<Document> writeResponse = await this.client.CreateDocumentAsync( // UriFactory.CreateDocumentCollectionUri(databaseName, collectionName), vacancySummary).ConfigureAwait(false); //return writeResponse; log?.Info($" inserting new record "); ResourceResponse <Document> writeResponse = await client.CreateDocumentAsync( UriFactory.CreateDocumentCollectionUri(databaseName, collectionName), vacancySummary).ConfigureAwait(false); log?.Info($" inserted new record "); return(writeResponse); // READ BELOW COMMENTED FOR TESTING //log?.Info($" check if the record exist with GUid: {vacancySummary.VacancyGuid}"); //ResourceResponse<Document> readResponse = await this.client.ReadDocumentAsync( // UriFactory.CreateDocumentUri(databaseName, collectionName, vacancySummary.VacancyGuid)).ConfigureAwait(false); //log?.Info($" Found record exist with GUid: {vacancySummary.VacancyGuid}"); //return readResponse; } catch (DocumentClientException de) { log?.Info($" IF record not found then got Document client exception : {de.Message}"); if (de.StatusCode == HttpStatusCode.NotFound || de.StatusCode == HttpStatusCode.NoContent) { log?.Info($" inserting new record after Document client exception : {de.Message}"); ResourceResponse <Document> writeResponse = await client.CreateDocumentAsync( UriFactory.CreateDocumentCollectionUri(databaseName, collectionName), vacancySummary).ConfigureAwait(false); log?.Info($" inserted new record "); return(writeResponse); } } catch (Exception exception) { log?.Info($" Application exception occoured : {exception.Message}"); } return(null); }
public static async Task <bool> PlayToEnd(string gameId, TraceWriter log) { try { using (var client = new DocumentClient(new Uri(_endpointUri), _primaryKey)) { var game = client.CreateDocumentQuery <Game>( UriFactory.CreateDocumentCollectionUri(_dbName, _collectionName), new FeedOptions { MaxItemCount = 1 } ).Where(g => g.id == gameId).ToList().FirstOrDefault(); if (game != null) { var d = client.CreateDocumentQuery <Document>( UriFactory.CreateDocumentCollectionUri(_dbName, _collectionName), new FeedOptions { MaxItemCount = 1 } ).Where(g => g.Id == game.id).ToList().FirstOrDefault(); Game toUpdate = (dynamic)d; GameController.PlayToEnd(toUpdate); var replaced = await client.ReplaceDocumentAsync(d.SelfLink, toUpdate); } else { log?.Info($"Could not find game with id {gameId}"); } } } catch (Exception e) { log.Error(e.ToString()); return(false); } return(true); }
public static async Task <UserStore> GetUserStore(this DocumentClient client, string userId, TraceWriter log = null) { try { if (string.IsNullOrEmpty(userId)) { return(null); } await client.EnsureCollection(UserStore.Collection); log?.Info($"Attempting to get UserStore document with Id: {userId}"); var response = await client.ReadDocumentAsync(UriFactory.CreateDocumentUri(UserStore.DatabaseId, UserStore.CollectionId, userId)); var json = response?.Resource?.ToString(); return(string.IsNullOrEmpty(json) ? null : JsonConvert.DeserializeObject <UserStore> (json)); } catch (DocumentClientException dex) { dex.Print(log); switch (dex.StatusCode) { case HttpStatusCode.NotFound: return(null); default: throw; } } catch (Exception ex) { log?.Error("Error saving new User", ex); throw; } }
private static async Task <string> GetAccessTokenSharePoint(string AADDomain, string siteUrl, TraceWriter log = null) { await GetVariables(); //https://blogs.msdn.microsoft.com/richard_dizeregas_blog/2015/05/03/performing-app-only-operations-on-sharepoint-online-through-azure-ad/ AuthenticationResult token; Uri uri = new Uri(siteUrl); string resourceUri = uri.Scheme + "://" + uri.Authority; if (ResourceTokenLookup.TryGetValue(resourceUri, out token) && token.ExpiresOn.UtcDateTime >= DateTime.UtcNow.AddMinutes(-5)) { return(token.AccessToken); } if (token != null) { log?.Info($"Token expired {token.ExpiresOn.UtcDateTime}"); } var cac = GetClientAssertionCertificate(); var authenticationContext = new AuthenticationContext(ADALLogin + AADDomain); bool keepRetry = false; do { TimeSpan?delay = null; try { token = await authenticationContext.AcquireTokenAsync(resourceUri, cac); } catch (Exception ex) { if (!(ex is AdalServiceException) && !(ex.InnerException is AdalServiceException)) { throw; } AdalServiceException serviceException; if (ex is AdalServiceException) { serviceException = (AdalServiceException)ex; } else { serviceException = (AdalServiceException)ex.InnerException; } if (serviceException.ErrorCode == "temporarily_unavailable") { RetryConditionHeaderValue retry = serviceException.Headers.RetryAfter; if (retry.Delta.HasValue) { delay = retry.Delta; } else if (retry.Date.HasValue) { delay = retry.Date.Value.Offset; } if (delay.HasValue) { Thread.Sleep((int)delay.Value.TotalSeconds); // sleep or other keepRetry = true; } } else { throw; } } } while (keepRetry); //token = await authenticationContext.AcquireTokenAsync(resourceUri, cac); ResourceTokenLookup[resourceUri] = token; log?.Info($"Aquired token which expires {token.ExpiresOn.UtcDateTime}"); return(token.AccessToken); }
public void LogInfo(string message) { _functionLogger.Info(message, _source); _redisLogger.Info(message); }
public static void Run(TimerInfo timerInfo, TraceWriter log) { log.Info(Class1.GetMessage()); }
public static void Run([ServiceBusTrigger("blissmotheaterseatsreserve", AccessRights.Manage, Connection = "Endpoint=sb://blissmo.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=BT1A0IXPd6goWbJ4PSidrtMMIQXcKNh4TYJAJcVf364=")] BrokeredMessage myQueueItem, TraceWriter log) { log.Info($"C# ServiceBus queue trigger function processed message: {myQueueItem.GetBody<string>()}"); }
public static async Task <HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequestMessage req, TraceWriter log, ExecutionContext context) { HttpStatusCode responseCode = HttpStatusCode.OK; string status = "Unknown Error"; // parse query parameter string taskId = req.GetQueryNameValuePairs() .FirstOrDefault(q => String.Compare(q.Key, "taskId", StringComparison.OrdinalIgnoreCase) == 0) .Value; if (taskId != null) { try { SecurityHelper security = new SecurityHelper(); responseCode = security.validateSecurity(req, log); if (responseCode == HttpStatusCode.OK) { string siteUrl = Environment.GetEnvironmentVariable("AMSPSiteUrl"); var task = Task.Run(async() => await CSOMHelper.GetClientContext(siteUrl, context.FunctionAppDirectory, log)); task.Wait(); if (task.Result != null) { string title = ""; string itemUrl = ""; using (var ctx = task.Result) { List l = ctx.Web.Lists.GetByTitle("AMTaskList"); ListItem item = l.GetItemById(taskId); //send email item["PercentComplete"] = 1; item.Update(); ctx.Load(item); ctx.ExecuteQuery(); title = item["Title"].ToString(); itemUrl = Environment.GetEnvironmentVariable("AMSPListDisplayForm") + item["ID"]; } string filePath = Path.Combine(context.FunctionAppDirectory, "AMCardComplete.json"); string originator = Environment.GetEnvironmentVariable("AMOriginator"); string jsonAM = System.IO.File.ReadAllText(filePath); var itemPost = string.Format(jsonAM, title, itemUrl, originator); var response = req.CreateResponse(responseCode); response.Headers.Add("CARD-ACTION-STATUS", "The task has been marked complete."); response.Headers.Add("CARD-UPDATE-IN-BODY", "true"); var content = new StringContent(itemPost, Encoding.UTF8, "application/json"); response.Content = content; return(response); } } } catch (Exception ex) { responseCode = HttpStatusCode.InternalServerError; status = ex.Message; log.Info($"AMTaskComplete (Run) error at: {DateTime.Now} - {ex.Message} - {ex.StackTrace}"); } } // You should also return the CARD-ACTION-STATUS header in the response. // The value of the header will be displayed to the user. switch (responseCode) { case HttpStatusCode.Forbidden: status = "This message was not sent through secure channels."; break; case HttpStatusCode.Unauthorized: status = "Thie messages token was not valid."; break; } HttpResponseMessage errorResponse = req.CreateErrorResponse(responseCode, new HttpError()); errorResponse.Headers.Add("CARD-ACTION-STATUS", status); return(errorResponse); }
public static void Run([TimerTrigger("0 0 6 * * *", RunOnStartup = false)] TimerInfo myTimer, TraceWriter log) { InvoiceService.Run(); log.Info($"C# Timer trigger function executed at: {DateTime.Now}"); }
public void RunAndBlock(CancellationToken cancellationToken = default(CancellationToken)) { int consecutiveErrorCount = 0; do { ScriptHost newInstance = null; try { // if we were in an error state retain that, // otherwise move to default if (State != ScriptHostState.Error) { State = ScriptHostState.Default; } // Create a new host config, but keep the host id from existing one _config.HostConfig = new JobHostConfiguration { HostId = _config.HostConfig.HostId }; OnInitializeConfig(_config); newInstance = _scriptHostFactory.Create(_environment, EventManager, _settingsManager, _config); _traceWriter = newInstance.TraceWriter; _logger = newInstance.Logger; _currentInstance = newInstance; lock (_liveInstances) { _liveInstances.Add(newInstance); } OnHostCreated(); string message = string.Format("Starting Host (HostId={0}, Version={1}, ProcessId={2}, Debug={3}, Attempt={4})", newInstance.ScriptConfig.HostConfig.HostId, ScriptHost.Version, Process.GetCurrentProcess().Id, newInstance.InDebugMode.ToString(), consecutiveErrorCount); _traceWriter?.Info(message); _logger?.LogInformation(message); newInstance.StartAsync(cancellationToken).GetAwaiter().GetResult(); // log any function initialization errors LogErrors(newInstance); OnHostStarted(); // only after ALL initialization is complete do we set the // state to Running State = ScriptHostState.Running; LastError = null; consecutiveErrorCount = 0; _restartDelayTokenSource = null; // Wait for a restart signal. This event will automatically reset. // While we're restarting, it is possible for another restart to be // signaled. That is fine - the restart will be processed immediately // once we get to this line again. The important thing is that these // restarts are only happening on a single thread. WaitHandle.WaitAny(new WaitHandle[] { cancellationToken.WaitHandle, _restartHostEvent, _stopEvent }); // Orphan the current host instance. We're stopping it, so it won't listen for any new functions // it will finish any currently executing functions and then clean itself up. // Spin around and create a new host instance. #pragma warning disable 4014 Orphan(newInstance); #pragma warning restore 4014 } catch (Exception ex) { State = ScriptHostState.Error; LastError = ex; consecutiveErrorCount++; // We need to keep the host running, so we catch and log any errors // then restart the host string message = "A ScriptHost error has occurred"; _traceWriter?.Error(message, ex); _logger?.LogError(0, ex, message); // If a ScriptHost instance was created before the exception was thrown // Orphan and cleanup that instance. if (newInstance != null) { Orphan(newInstance, forceStop: true) .ContinueWith(t => { if (t.IsFaulted) { t.Exception.Handle(e => true); } }, TaskContinuationOptions.ExecuteSynchronously); } // attempt restarts using an exponential backoff strategy CreateRestartBackoffDelay(consecutiveErrorCount).GetAwaiter().GetResult(); } }while (!_stopped && !cancellationToken.IsCancellationRequested); }
public static async Task <IActionResult> Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req, TraceWriter log) { log.Info("C# HTTP trigger function processed a request."); bool simple = !(req.Headers["format"] == "extended"); var channel = req.Headers["channel"]; if (!string.IsNullOrWhiteSpace(channel)) { if (!channel.ToString().StartsWith("#")) { channel = "#" + channel; } } string requestBody = new StreamReader(req.Body).ReadToEnd(); var request = JsonConvert.DeserializeObject <WebhookRequest>(requestBody); //var message = data?.message?.text; var detailedMessage = request.DetailedMessage.text; // important - get this data var resourceLink = request.Resource.url; var changesData = await GetVstsResource($"{resourceLink}/changes"); var changes = JsonConvert.DeserializeObject <Changes>(changesData); var changesCount = changes.count; var changesText = ""; foreach (var change in changes.value) { changesText += $"<{change.displayUri}|{change.message}> by *{change.Author.displayName}*\n"; if (!simple) { changesText += $"{change.message}\n\n"; } } var resource = await GetVstsResource(resourceLink); var resourceData = JsonConvert.DeserializeObject <ResourceDetails>(resource); var projectName = resourceData.Project.Name; var buildLink = resourceData._Links.Web.Href; var sourceBranch = resourceData.SourceBranch; var sourceVersion = resourceData.SourceVersion; var repository = resourceData.Repository.Id; var definitionName = request.Resource.definition.name; var gitUrl = $"{repository.Replace(".git", "")}/commit/{sourceVersion}"; var timeline = await GetVstsResource(resourceData._Links.Timeline.Href); var timeLineData = JsonConvert.DeserializeObject <Timeline>(timeline); var failingTask = timeLineData.Records.FirstOrDefault(x => x.Result == "failed"); var slackService = new SlackService(log, KeyManager.GetSecret("SlackWebhookUrl")); var model = new SlackMessageModel { username = "******", icon_emoji = ":vsts:", text = $"*{projectName}/{definitionName} - {failingTask.Name} failed*", channel = channel, attachments = new List <SlackMessageModel.SlackAttachment>() { new SlackMessageModel.SlackAttachment { color = "#ff0000", pretext = $"Repository: {repository}\nBranch: {sourceBranch}\nCommit: {sourceVersion}", title = $"{changesCount} Change(s) in the build: ", text = changesText, actions = new[] { new SlackMessageModel.SlackAction { type = "button", text = ":octocat: Git Repo Url", url = repository }, new SlackMessageModel.SlackAction { type = "button", text = ":octocat: Git Commit Url", url = gitUrl }, new SlackMessageModel.SlackAction { type = "button", text = ":vsts: VSTS Url", url = buildLink } } } } }; if (!simple) { model.attachments.Add(new SlackMessageModel.SlackAttachment { color = "#ff0000", title = "Build message", text = $"{detailedMessage}" }); } slackService.PostToSlack(model); return(new OkObjectResult("")); }
public static async Task <HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequestMessage req, TraceWriter log) { var eindTijdItems = new List <string> { "tot hoe laat", "tot wanneer", "vanaf hoe laat uit", "hoe laat uit", "wanneer uit" }; var begintijdItems = new List <string> { "vanaf hoe laat", "vanaf wanneer", "vanaf", "hoe laat zijn" }; string[] tijd = new string[] { }; log.Info("C# HTTP trigger function processed a request."); string eindTijd = String.Empty; string inputDayofweek = string.Empty; string leerling; string tijdVraag = string.Empty; var googleHomeRequest = await req.Content.ReadAsAsync <GoogleHomeRequest>(); var newGoogleHomeRequest = await req.Content.ReadAsAsync <NewGoogleHomeRequest>(); if (googleHomeRequest != null) { leerling = googleHomeRequest?.Result.Parameters.leerling; inputDayofweek = googleHomeRequest?.Result.Parameters.dayofweek; tijd = googleHomeRequest?.Result.Parameters.tijd; } else { leerling = req.GetQueryNameValuePairs() .FirstOrDefault(q => string.Compare(q.Key, "leerling", StringComparison.OrdinalIgnoreCase) == 0) .Value; } if (string.IsNullOrEmpty(leerling)) { leerling = "wouter"; } string actionDayofweek = string.Empty; if (inputDayofweek == string.Empty) { inputDayofweek = req.GetQueryNameValuePairs() .FirstOrDefault(q => string.Compare(q.Key, "dayofweek", StringComparison.OrdinalIgnoreCase) == 0) .Value; } if (tijd.Length == 0) { tijdVraag = req.GetQueryNameValuePairs() .FirstOrDefault(q => string.Compare(q.Key, "tijd", StringComparison.OrdinalIgnoreCase) == 0) .Value; } switch (inputDayofweek.ToLower()) { case "maandag": actionDayofweek = "Monday"; break; case "dinsdag": actionDayofweek = "Tuesday"; break; case "woensdag": actionDayofweek = "Wednesday"; break; case "donderdag": actionDayofweek = "Thursday"; break; case "vrijdag": actionDayofweek = "Friday"; break; case "morgen": actionDayofweek = DateTime.Now.AddDays(1).DayOfWeek.ToString(); break; default: case "vandaag": actionDayofweek = DateTime.Now.DayOfWeek.ToString(); break; } log.Info($"Parameter passed is '{inputDayofweek}'"); DayOfWeek dow = DayOfWeek.Sunday; if (Enum.IsDefined(typeof(DayOfWeek), actionDayofweek)) { dow = (DayOfWeek)Enum.Parse(typeof(DayOfWeek), actionDayofweek, true); } var scheduleChanges = new ScheduleChanges(); var dateToCheck = scheduleChanges.FindDateByWeekday(dow).ToString("dd-MM-yyyy"); var googleResponse = new Response(); var result = new Announce(); string fullTime = string.Empty; if (tijd != null) { fullTime = String.Join(" ", tijd); } if (eindTijdItems.Contains(fullTime.ToLower())) { result = scheduleChanges.GetStartOrEndTime(leerling, dateToCheck, inputDayofweek.ToLower(), "end"); } else if (begintijdItems.Contains(fullTime.ToLower())) { result = scheduleChanges.GetStartOrEndTime(leerling, dateToCheck, inputDayofweek.ToLower(), "start"); } else { result = scheduleChanges.GetChangesForDay(leerling, dateToCheck); } var i = 0; foreach (var msg in result.Messages) { i++; if (i == result.Messages.Count && result.Messages.Count > 1) { googleResponse.speech += " en " + msg.TheMessage + ". "; } else { googleResponse.speech += msg.TheMessage; } } if (googleResponse.speech != null) { googleResponse.displayText = googleResponse.speech; googleResponse.source = "webhook"; } else { googleResponse.speech = $"Er zijn nog geen wijzigingen bekend voor {leerling} voor deze datum. Het rooster is dus ongewijzigd."; googleResponse.displayText = googleResponse.speech; googleResponse.source = "webhook"; } return(inputDayofweek == null ? req.CreateResponse(HttpStatusCode.BadRequest, "Please pass a name on the query string or in the request body") : req.CreateResponse(HttpStatusCode.OK, googleResponse)); }