Ejemplo n.º 1
0
        /// <summary>
        /// Trace information for an unhandled exception.
        /// Each request handler should perform its logic within a try block, and call this handler within the catch block.
        /// </summary>
        /// <param name="ex">the exception caught at top level</param>
        /// <param name="tracer">Tracer that will be used to send telemetry on the failure</param>
        /// <param name="fallbackTracer">Fallback tracer, in case the tracer fails</param>
        public static void TraceUnhandledException(Exception ex, IExtendedTracer tracer, TraceWriter fallbackTracer)
        {
            // Trace the full exception details
            string errorToTrace = $"Top level exception: {ex}";

            try
            {
                // Write to trace
                tracer?.TraceError(errorToTrace);

                // Report the exception
                if (ex != null && tracer != null)
                {
                    AggregateException aggregateException = ex as AggregateException;
                    if (aggregateException != null)
                    {
                        aggregateException.InnerExceptions.ToList().ForEach(tracer.ReportException);
                    }
                    else
                    {
                        tracer.ReportException(ex);
                    }
                }

                // Flush all traces
                tracer?.Flush();
            }
            catch (Exception traceException)
            {
                try
                {
                    // Try to write to the fallback tracer
                    fallbackTracer?.Error($"Tracer failed - using fallback tracer. Tracer error: {traceException}");
                    fallbackTracer?.Error(errorToTrace);
                    fallbackTracer?.Flush();
                }
                catch (Exception fallbackTraceException)
                {
                    try
                    {
                        // Try to write to console
                        Console.WriteLine($"Tracer failed - using fallback tracer. Tracer error: {traceException}");
                        Console.WriteLine($"Fallback tracer failed - using console. Fallback tracer error: {fallbackTraceException}");
                        Console.WriteLine(errorToTrace);
                    }
                    catch (Exception)
                    {
                        // Just swallow, nothing better to do here..
                    }
                }
            }
        }
        private static async Task <INetworkWatcher> EnsureNetworkWatcherExists(IAzure azure, Region region, TraceWriter log = null)
        {
            // Retrieve appropriate Network Watcher, or create one
            INetworkWatcher networkWatcher = azure.NetworkWatchers.List().First(x => x.Region == region);

            if (networkWatcher == null)
            {
                try
                {
                    // Create Resource Group for Network Watcher if Network Watcher does not exist
                    IResourceGroup networkWatcherRG = azure.ResourceGroups.GetByName("NetworkWatcherRG");
                    if (networkWatcherRG == null)
                    {
                        // The RG is conventionally created in USWestCentral even though the Network Watcher region may be different
                        networkWatcherRG = await azure.ResourceGroups
                                           .Define("NetworkWatcherRG")
                                           .WithRegion(Region.USWestCentral)
                                           .CreateAsync();
                    }

                    string networkWatcherName = "NetworkWatcher_" + region.Name.ToString().ToLower();
                    networkWatcher = await azure.NetworkWatchers.Define(networkWatcherName).WithRegion(region).WithExistingResourceGroup(networkWatcherRG).CreateAsync();
                }
                catch (Exception ex)
                {
                    log?.Error($"Unable to create ResourceGroup or Network Watcher: {ex}. Exiting.");
                    throw;
                }
            }

            return(networkWatcher);
        }
        internal ApplicationPerformanceCounters GetPerformanceCounters(TraceWriter traceWriter = null)
        {
            string json = _settingsManager.GetSetting(EnvironmentSettingNames.AzureWebsiteAppCountersName);

            if (!string.IsNullOrEmpty(json))
            {
                try
                {
                    // TEMP: need to parse this specially to work around bug where
                    // sometimes an extra garbage character occurs after the terminal
                    // brace
                    int idx = json.LastIndexOf('}');
                    if (idx > 0)
                    {
                        json = json.Substring(0, idx + 1);
                    }

                    return(JsonConvert.DeserializeObject <ApplicationPerformanceCounters>(json));
                }
                catch (JsonReaderException ex)
                {
                    traceWriter?.Error($"Failed to deserialize application performance counters. JSON Content: \"{json}\"", ex);
                }
            }

            return(null);
        }
Ejemplo n.º 4
0
        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);
        }
Ejemplo n.º 5
0
        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));
        }
Ejemplo n.º 6
0
        private static async Task <INetworkWatcher> EnsureNetworkWatcherExists(IAzure azure, Region region, TraceWriter log = null)
        {
            // Retrieve appropriate Network Watcher, or create one
            INetworkWatcher networkWatcher = null;
            IEnumerable <INetworkWatcher> networkWatcherList = azure.NetworkWatchers.List();

            if (networkWatcherList != null && networkWatcherList.Count() > 0)
            {
                log.Verbose($"Network Watchers found in subscription - checking if any are in region {region.Name}");
                try
                {
                    networkWatcher = azure.NetworkWatchers.List().First(x => x.Region == region);
                }
                catch (Exception)
                {
                    log.Info($"No network watchers found in region {region.Name}");
                }
            }
            else
            {
                log.Verbose("No Network Watchers found in subscription.");
            }
            if (networkWatcher == null)
            {
                try
                {
                    string networkWatcherRGName = "NetworkWatcherRG";
                    log.Info($"No Network Watcher exists in region {region.Name}. Will attempt to create in ResourceGroup {networkWatcherRGName}");
                    // Create Resource Group for Network Watcher if Network Watcher does not exist
                    IResourceGroup networkWatcherRG = azure.ResourceGroups.GetByName(networkWatcherRGName);
                    if (networkWatcherRG == null)
                    {
                        Region targetNetworkWatcherRGRegion = region;
                        log.Info($"Resource Group {networkWatcherRGName} does not exist. Creating it in region: {targetNetworkWatcherRGRegion.Name}. Note - the region of the Network Watcher's Resource Group does not have to match the region of the Network Watcher.");
                        networkWatcherRG = await azure.ResourceGroups
                                           .Define(networkWatcherRGName)
                                           .WithRegion(targetNetworkWatcherRGRegion)
                                           .CreateAsync();

                        log.Info("Created Resource Group");
                    }

                    string networkWatcherName = "NetworkWatcher_" + region.Name.ToString().ToLower();
                    log.Info($"Creating the network watcher {networkWatcherName} in resource group {networkWatcherRG.Name}");
                    networkWatcher = await azure.NetworkWatchers.Define(networkWatcherName).WithRegion(region).WithExistingResourceGroup(networkWatcherRG).CreateAsync();

                    log.Info($"Network Watcher created successfully");
                }
                catch (Exception ex)
                {
                    log?.Error($"Unable to create ResourceGroup or Network Watcher: {ex}. Exiting.");
                    throw ex;
                }
            }

            return(networkWatcher);
        }
        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 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;
            }
        }
        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;
            }
        }
        private static async Task <string[]> QueryMLModel(TraceWriter log, QueueNotificationImageUploaded notificationImageUploaded)
        {
            string[] matchingImages = { };
            try
            {
                HttpClient httpClient = new HttpClient();

                string mlServiceEndpoint = ConfigurationManager.AppSettings["MLQueryServiceEndpoint"];

                /* Only if the ML Service Endpoint is defined */
                if (!String.IsNullOrEmpty(mlServiceEndpoint))
                {
                    HttpRequestMessage httpRequestMessage = new HttpRequestMessage
                    {
                        // Uri: http://52.178.119.58/api/v1/service/irisapp/score
                        RequestUri = new Uri(ConfigurationManager.AppSettings["MLQueryServiceEndpoint"]),
                        Method     = HttpMethod.Post
                    };

                    if (!String.IsNullOrEmpty(ConfigurationManager.AppSettings["MLQueryServiceAuthHeader"]))
                    {
                        httpRequestMessage.Headers.Add("Authorization", ConfigurationManager.AppSettings["MLQueryServiceAuthHeader"]);
                        //httpRequestMessage.Headers.Add("Authorization", "Bearer 44a392fb3a6a4c30bfa5bc668c10508e");
                    }

                    string httpBody = JsonConvert.SerializeObject(notificationImageUploaded.ImageFile);
                    httpBody = "{\"input_df\": [{\"petal length\": 1.3, \"sepal length\": 3.0, \"sepal width\": 3.6, \"petal width\": 0.25}]}";

                    httpRequestMessage.Content = new StringContent(httpBody, null, "application/json");
                    httpRequestMessage.Content.Headers.Remove("Content-Type");
                    httpRequestMessage.Content.Headers.Add("Content-Type", "application/json");

                    HttpResponseMessage httpResponseMessage = await httpClient.SendAsync(httpRequestMessage);

                    string response = await httpResponseMessage.Content.ReadAsStringAsync();
                }
            }
            catch (Exception ex)
            {
                log.Error("Error occured communicating with the ML Model Service.", ex);
            }

            return(matchingImages);
        }
Ejemplo n.º 11
0
        public static void Run([TimerTrigger("0 0 9,18 * * 1-5")] TimerInfo myTimer, TraceWriter log)
        {
            Logger = log;

            Logger.Info($"C# Timer trigger function executed at: {DateTime.Now}");

            try
            {
                var rainStatus = WeatherHelper.GetRainInNextHour();
                if (rainStatus.WillItRain)
                {
                    DrySafe.Logger.Info($"Rain is planned ! Sending notification.");
                    NotificationHelper.SendNotification(rainStatus.GetDescription());
                }
                else
                {
                    DrySafe.Logger.Info($"No rain planned.");
                }
            }
            catch (Exception e)
            {
                Logger.Error($"Error: {e.Message}");
                try
                {
                    NotificationHelper.SendNotification($"DrySafe - Erreur: {e.Message}");
                }
                catch (Exception e2)
                {
                    MailHelper.SendMail("DrySafe: Error", "One or more errors occured during DrySafe execution: "
                                        + Environment.NewLine
                                        + e.Message
                                        + Environment.NewLine
                                        + e.StackTrace
                                        + Environment.NewLine
                                        + Environment.NewLine
                                        + e2.Message
                                        + Environment.NewLine
                                        + e2.StackTrace
                                        + Environment.NewLine
                                        + Environment.NewLine
                                        ).Wait();
                }
            }
        }
Ejemplo n.º 12
0
        public static void UpsertStripeTransaction(StripeTransaction trans, TraceWriter log)
        {
            try
            {
                var cnnString = ConfigurationManager.ConnectionStrings["PP_ConnectionString"].ConnectionString;

                using (var connection = new SqlConnection(cnnString))
                {
                    connection.Open();


                    using (SqlCommand cmd = new SqlCommand(upsertCommand, connection))
                    {
                        cmd.Parameters.Add("@APITransactionID", SqlDbType.VarChar, 50).Value = trans.APITransactionId ?? (object)DBNull.Value;
                        cmd.Parameters.Add("@TransactionType", SqlDbType.VarChar, 25).Value  = trans.TransactionType ?? (object)DBNull.Value;
                        cmd.Parameters.Add("@Description", SqlDbType.VarChar, 255).Value     = trans.Description ?? (object)DBNull.Value;
                        cmd.Parameters.Add("@CreatedTime", SqlDbType.DateTime).Value         = trans.CreatedTime;
                        cmd.Parameters.Add("@Amount", SqlDbType.Decimal).Value                   = trans.Amount ?? (object)DBNull.Value;
                        cmd.Parameters.Add("@Currency", SqlDbType.VarChar, 10).Value             = trans.Currency ?? (object)DBNull.Value;
                        cmd.Parameters.Add("@FeeAmount", SqlDbType.Decimal).Value                = trans.FeeAmount ?? (object)DBNull.Value;
                        cmd.Parameters.Add("@FeeDetails", SqlDbType.NVarChar).Value              = trans.FeeDetails ?? (object)DBNull.Value;
                        cmd.Parameters.Add("@TaxAmount", SqlDbType.Decimal).Value                = trans.TaxAmount ?? (object)DBNull.Value;
                        cmd.Parameters.Add("@LiveMode", SqlDbType.Bit).Value                     = trans.LiveMode ?? (object)DBNull.Value;
                        cmd.Parameters.Add("@Status", SqlDbType.VarChar, 50).Value               = trans.Status ?? (object)DBNull.Value;
                        cmd.Parameters.Add("@CustomerStripeID", SqlDbType.VarChar, 25).Value     = trans.CustomerStripeId ?? (object)DBNull.Value;
                        cmd.Parameters.Add("@Captured", SqlDbType.Bit).Value                     = trans.Captured ?? (object)DBNull.Value;
                        cmd.Parameters.Add("@Card", SqlDbType.NVarChar).Value                    = trans.Card ?? (object)DBNull.Value;
                        cmd.Parameters.Add("@InvoiceID", SqlDbType.VarChar, 50).Value            = trans.InvoiceId ?? (object)DBNull.Value;
                        cmd.Parameters.Add("@CardBrand", SqlDbType.VarChar, 25).Value            = trans.CardBrand ?? (object)DBNull.Value;
                        cmd.Parameters.Add("@DestinationAccountId", SqlDbType.VarChar, 50).Value = trans.DestinationAccountId ?? (object)DBNull.Value;
                        cmd.Parameters.Add("@TransferID", SqlDbType.VarChar, 50).Value           = trans.TransferId ?? (object)DBNull.Value;
                        cmd.Parameters.Add("@TransferGroup", SqlDbType.VarChar, 50).Value        = trans.TransferGroup ?? (object)DBNull.Value;
                        cmd.Parameters.Add("@Metadata", SqlDbType.NVarChar).Value                = trans.Metadata ?? (object)DBNull.Value;
                        cmd.Parameters.Add("@RefundChargeId", SqlDbType.VarChar, 50).Value       = trans.RefundChargeId ?? (object)DBNull.Value;
                        var resultCount = cmd.ExecuteNonQuery();
                    }
                }
            }
            catch (Exception ex)
            {
                //dberrorhandler.inserterror(trans, ex, log);
                log.Error("InsertStripeTransaction error", ex);
            }
        }
Ejemplo n.º 13
0
        public static void Run(FulfillmentResponse responsemessage, ICollector <string> errormessage, TraceWriter log)
        {
            try
            {
                log.Verbose($"C# trigger queue function processed a request. inputmessage={responsemessage}", "JE.RMS.Services.OnRewardsResponseRecieved");
                #region Update Audit Fields
                //Update timestapm in Audit fields
                List <SqlParameter> AuditParam = new List <SqlParameter>();
                AuditParam.Add(new SqlParameter("@RMSRewardID", responsemessage.RMSRewardID));

                var RMSRewardID = MSSQLConnection.ExecuteStoredProcedure <string>(USPContstants.UpdateAuditFieldsInRewardsTrx, AuditParam);
                log.Verbose($"FulfillmentResponseTimestamp updated successfully. RMSRewardID={RMSRewardID[0]}", "JE.RMS.Services.OnRewardsResponseRecieved");
                string RewardTrxStatus = "Fulfillment completed";
                if (responsemessage.Status == "Fail")
                {
                    RewardTrxStatus = "Error";
                }

                List <SqlParameter> MessageLogParams = new List <SqlParameter>();
                MessageLogParams.Add(new SqlParameter("@RMSRewardID", responsemessage.RMSRewardID));
                MessageLogParams.Add(new SqlParameter("@MessageType", MessageType.RewardFulfillmentResponse.GetDescription()));
                MessageLogParams.Add(new SqlParameter("@IPAddress", responsemessage.ClientIP));
                MessageLogParams.Add(new SqlParameter("@Message", JsonConvert.SerializeObject(responsemessage)));
                MessageLogParams.Add(new SqlParameter("@RewardsTrxID", null));
                var ErrorMessageLogID = MSSQLConnection.ExecuteStoredProcedure <long>(USPContstants.SaveMessageLog, MessageLogParams);
                log.Verbose($"MessageLog stored successfully. MessageLogID={ErrorMessageLogID[0]}", "JE.RMS.Services.ProcessFulfillmentForEnergyEarth");

                ////Call stored procedure to Save RewardTrxChangeLog
                List <SqlParameter> RewardTrxChangeLogParams = new List <SqlParameter>();
                RewardTrxChangeLogParams.Add(new SqlParameter("@RMSRewardID", responsemessage.RMSRewardID));
                RewardTrxChangeLogParams.Add(new SqlParameter("@RewardTrxStatus", RewardTrxStatus));
                RewardTrxChangeLogParams.Add(new SqlParameter("@Comment", string.Empty));
                RewardTrxChangeLogParams.Add(new SqlParameter("@RewardsTrxID", null));

                var RewardTrxChangeLogID = MSSQLConnection.ExecuteStoredProcedure <long>(USPContstants.SaveRewardTrxChangeLog, RewardTrxChangeLogParams);
                log.Verbose($"RewardTrxChangeLog stored successfully. RewardTrxChangeLogID={RewardTrxChangeLogID[0]}", "JE.RMS.Services.OnRewardsResponseRecieved");
                #endregion
            }
            catch (Exception ex)
            {
                log.Error($"Exception ={ex}", ex, "JE.RMS.Services.OnRewardsRequestRecieved");
                errormessage.Add(JsonConvert.SerializeObject(ex).ToString());
            }
        }
Ejemplo n.º 14
0
        public static void Run([EventGridTrigger] EventGridEvent eventData, TraceWriter log)
        {
            try
            {
                var data           = (JObject)eventData.Data;
                var storageDetails = JsonConvert.DeserializeObject <StorageBlobCreatedEventData>(data.ToString());
                log.Info($"Blob created at the following URL: {storageDetails.Url}");

                var parsedUrl = BlobUrlParser.Parse(storageDetails.Url);
                if (parsedUrl.ContainerName == Configuration.FileUploadContainerName)
                {
                    workflowClient.Value.ExecuteAsync(parsedUrl).Wait();
                }
            }
            catch (Exception err)
            {
                log.Error(err.ToString());
            }
        }
Ejemplo n.º 15
0
        static async Task WriteDevicesToBlob(string instanceId, IList <ExportImportDevice> devices, TraceWriter log)
        {
            try
            {
                CloudStorageAccount storage = CloudStorageAccount.Parse(Settings.Instance.StorageAccountConnectionString);
                CloudBlobClient     client  = storage.CreateCloudBlobClient();


                CloudBlobContainer container = client.GetContainerReference(instanceId);
                await container.CreateIfNotExistsAsync();

                var blob   = container.GetBlockBlobReference(Utils.DeviceToImportBlobName);
                var buffer = new StringBuilder();

                using (var stream = await blob.OpenWriteAsync())
                {
                    for (var i = 0; i < devices.Count;)
                    {
                        // write in blocks of 100
                        for (var y = 0; y < 100 && i < devices.Count; i++, y++)
                        {
                            buffer.AppendLine(JsonConvert.SerializeObject(devices[i]));
                        }

                        var bytes = Encoding.UTF8.GetBytes(buffer.ToString());
                        await stream.WriteAsync(bytes, 0, bytes.Length);

                        buffer.Length = 0;
                    }

                    if (buffer.Length > 0)
                    {
                        var bytes = Encoding.UTF8.GetBytes(buffer.ToString());
                        await stream.WriteAsync(bytes, 0, bytes.Length);
                    }
                }
            }
            catch (Exception ex)
            {
                log.Error("Failed writing import file to blog", ex);
                throw;
            }
        }
        public static void RunComplexMessage(
            [ServiceBusTrigger("das-test-complex-messages", AccessRights.Manage, Connection = "ServiceBusConnectionString")]
            BrokeredMessage message,
            ExecutionContext executionContext,
            TraceWriter log)
        {
            log.Info($"C# ServiceBus queue trigger receiving message: {message.MessageId}");

            try
            {
                var complexMessageEvent = message.DeserializeJsonMessage<ComplexMessageEvent>();
                log.Info($"C# ServiceBus queue trigger function processed event: {complexMessageEvent}");
            }
            catch (Exception e)
            {
                log.Error($"Unable to deserialize message body for StringMessage. messageId: {message.MessageId} {{ID={executionContext.InvocationId}}}", e);
                message.Defer();
            }
        }
 private static string CreateXMLFromJSON(JObject jInput, TraceWriter log)
 {
     if (jInput == null)
     {
         return("");
     }
     try
     {
         XNode  tmpNode = JsonConvert.DeserializeXNode(jInput.ToString(), "Root");
         string strXML  = tmpNode.ToString();
         strXML = strXML.Replace("<Root>", null);
         strXML = strXML.Replace("</Root>", null);
         return(strXML);
     } catch (Exception e)
     {
         log.Error("Error", e);
         return("");
     }
 }
        public static async Task <PhotoInfo> Run([HttpTrigger(AuthorizationLevel.Anonymous, "post")] HttpRequestMessage input, TraceWriter log)
        {
            // Will eventually use this when we require the user to be authorized to use the app
            var isAuth = input.GetRequestContext().Principal.Identity.IsAuthenticated;

            log.Info($"Is Auth: {isAuth}", "request context");

            try
            {
                PhotoInfo data = await input.Content.ReadAsAsync <PhotoInfo>();

                return(data);
            }
            catch (Exception ex)
            {
                log.Error($"*** Error: {ex.Message}");
                return(null);
            }
        }
Ejemplo n.º 19
0
        public static async Task <HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequestMessage req, TraceWriter log)
        {
            log.Info("C# HTTP trigger function processed a request.");
            try
            {
                var content = await req.Content.ReadAsStringAsync();

                DeviceInstallation deviceUpdate = await req.Content.ReadAsAsync <DeviceInstallation>();

                await NotificationManager.RegisterDevice(deviceUpdate);

                await NotificationManager.SendBroadcastNotification("Notificación en el webinar");
            }
            catch (Exception ex)
            {
                log.Error(ex.Message);
            }
            return(req.CreateResponse(HttpStatusCode.OK));
        }
    private static async Task <Dictionary <string, int> > GetKeyPhrases(List <dynamic> documents, TraceWriter log)
    {
        Dictionary <string, int> keyPhrases = new Dictionary <string, int>(StringComparer.InvariantCultureIgnoreCase);

        HttpClient httpClient = new HttpClient();

        httpClient.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", TextAnalyticsAPIKey);

        string requestPayload = JsonConvert.SerializeObject(new { documents = documents });
        var    request        = new HttpRequestMessage(HttpMethod.Post, CognitiveServicesUri)
        {
            Content = new StringContent(requestPayload, Encoding.UTF8, "application/json")
        };
        HttpResponseMessage response = await httpClient.SendAsync(request);

        if (!response.IsSuccessStatusCode)
        {
            string error = response.Content?.ReadAsStringAsync().Result;
            log.Error("Request failed: " + error);
            return(keyPhrases);
        }

        string content = await response.Content.ReadAsStringAsync();

        dynamic responsePayload = JsonConvert.DeserializeObject <dynamic>(content);

        foreach (dynamic document in responsePayload.documents)
        {
            foreach (string keyPhrase in document.keyPhrases)
            {
                int count;
                if (keyPhrases.TryGetValue(keyPhrase, out count))
                {
                    keyPhrases[keyPhrase] = count++;
                }
                else
                {
                    keyPhrases[keyPhrase] = 1;
                }
            }
        }
        return(keyPhrases);
    }
Ejemplo n.º 21
0
        // Called for each instance.
        // Can be called by the Trigger codepath
        public Task <IBinding> BindDirect(BindingProviderContext context)
        {
            ParameterInfo parameter = context.Parameter;
            TAttribute    attribute = parameter.GetCustomAttribute <TAttribute>(inherit: false);

            string path = attribute.Path;

            BindingTemplate bindingTemplate = BindingTemplate.FromString(path);

            bindingTemplate.ValidateContractCompatibility(context.BindingDataContract);

            IBinding binding = null;

            if (parameter.IsOut)
            {
                if (parameter.ParameterType.GetElementType() == typeof(string))
                {
                    // Bind to 'out string'
                    binding = new GenericOutStringFileBinding <TAttribute, TFile>(
                        bindingTemplate, attribute, _strategyBuilder, _converterManager);
                }
                else
                {
                    binding = new GenericFileBinding <TAttribute, TFile>(parameter, bindingTemplate, attribute, _strategyBuilder, _converterManager);
                }
            }
            else
            {
                // Native
                // Stream
                // TextReader | TextWriter
                // String, byte[]
                binding = new GenericFileBinding <TAttribute, TFile>(parameter, bindingTemplate, attribute, _strategyBuilder, _converterManager);
            }

            if (binding == null)
            {
                _trace.Error("Binding is not supported: " + path);
                throw new InvalidOperationException("Binding is not supported: " + path);
            }

            return(Task.FromResult(binding));
        }
Ejemplo n.º 22
0
        public static void Run([QueueTrigger("%ProcessPartitionQueue%", Connection = "AzureWebJobsStorage")] string myQueueItem,
                               [Table("%ProcessPartitionStatusTable%", Connection = "AzureWebJobsStorage")] CloudTable statusTable,
                               TraceWriter log)
        {
            log.Info($"Received queue trigger to process partition : {myQueueItem}");

            QueueMessageProcesssTabular queueMessage = null;

            try
            {
                queueMessage = JsonConvert.DeserializeObject <QueueMessageProcesssTabular>(myQueueItem);

                SqlServerAnalysisServerTabular tabularModel = new SqlServerAnalysisServerTabular()
                {
                    ConnectionString = ConfigurationManager.ConnectionStrings["SsasTabularConnection"].ConnectionString,
                    DatabaseName     = queueMessage.Database ?? ConfigurationManager.AppSettings["DatabaseName"]
                };

                queueMessage.Status = "Running";
                queueMessage.ETag   = "*";
                TableOperation updateOperation = TableOperation.InsertOrReplace(queueMessage);
                statusTable.Execute(updateOperation);

                tabularModel.ProcessPartition(queueMessage.Tables, queueMessage.Parition);

                queueMessage.Status = "Complete";
                queueMessage.ETag   = "*";
                updateOperation     = TableOperation.InsertOrReplace(queueMessage);
                statusTable.Execute(updateOperation);
            }
            catch (Exception e)
            {
                log.Error($"Error occured processing partition - " +
                          $"{queueMessage?.Database}/{queueMessage?.Tables}/{queueMessage?.Parition} : {e.ToString()}", e);
                queueMessage.Status       = "Error Processing";
                queueMessage.ErrorDetails = e.ToString();
                queueMessage.ETag         = "*";
                TableOperation updateOperation = TableOperation.InsertOrReplace(queueMessage);
                statusTable.Execute(updateOperation);
            }

            log.Info($"Successfully completed partition processing for  {queueMessage?.Database}/{queueMessage?.Tables}/{queueMessage?.Parition}");
        }
Ejemplo n.º 23
0
        public static async Task Run(
            [OrchestrationTrigger] DurableOrchestrationContext counterContext,
            TraceWriter log)
        {
            int numberOfExecutions = 0;

            try
            {
                numberOfExecutions = counterContext.GetInput <int>();
                log.Info($"********{counterContext.InstanceId}: Current counter state is {numberOfExecutions}. isReplaying: {counterContext.IsReplaying} Waiting for next operation.**************");

                log.Info($"*********{counterContext.InstanceId}: Call activity ExistFile from {numberOfExecutions}*************");
                var existsFile = await counterContext.CallActivityAsync <bool>("ExistFile", numberOfExecutions.ToString());

                if (existsFile)
                {
                    log.Info($"*********{counterContext.InstanceId}: EXISTS FILE {numberOfExecutions}.json *************");

                    log.Info($"*********{counterContext.InstanceId}: Call activity AddCRM from {numberOfExecutions}*************");
                    await counterContext.CallActivityAsync("AddCRM", numberOfExecutions.ToString());

                    log.Info($"*********Add element to queeue *************");
                    await counterContext.CallActivityAsync("AddQueueTrigger", numberOfExecutions.ToString());

                    log.Info($"*********END element to queeue *************");
                }
                else
                {
                    log.Info($"*********{counterContext.InstanceId}: NO EXIST FILE {numberOfExecutions}.json *************");
                }

                log.Info($"*********Return {counterContext.InstanceId}: FINISH from {numberOfExecutions}*************");
            }
            catch (Exception ex)
            {
                log.Error($"**********ERROR General execution: {numberOfExecutions} -  {counterContext.IsReplaying} - {counterContext.InstanceId} *********", ex.InnerException != null ? ex.InnerException : ex);
                if (!counterContext.IsReplaying)
                {
                    log.Info($"**********RETRY execution: {numberOfExecutions} - {counterContext.InstanceId} *********");
                    counterContext.ContinueAsNew(numberOfExecutions);
                }
            }
        }
Ejemplo n.º 24
0
        public static async Task <IActionResult> Check(
            [HttpTrigger(AuthorizationLevel.Anonymous, "post")] HttpRequest request, TraceWriter log)
        {
            log.Info("Processing request");

            try
            {
                string image = await request.ReadAsStringAsync();

                IList <DetectedFace> response = await GetEmotion(image, faceEndpoint, faceKey, log);

                return(response != null ? new OkObjectResult(response) : new NotFoundObjectResult("No faces found") as IActionResult);
            }
            catch (Exception exception)
            {
                log.Error("Failed processing image", exception);
                return(new BadRequestObjectResult(exception));
            }
        }
Ejemplo n.º 25
0
        public static async Task Run([TimerTrigger("0 */10 * * * *", RunOnStartup = true)] TimerInfo myTimer, TraceWriter log)
        {
            log.Info($"C# Timer trigger function executed at: {DateTime.Now}");

            SetSecurityProtocol();

            try
            {
                var config = Config.GetConfig();
                await Timer.Time(() => DataMover.Move(config, log), "Moving data", log);
            }
            catch (Exception ex)
            {
                log.Error($"Top level error handling. Message: {ex.Message}", ex);
                throw;
            }

            log.Info($"C# Timer trigger function completed at: {DateTime.Now}");
        }
Ejemplo n.º 26
0
        public static async Task SendMessagesDownstream(string myMessages, TraceWriter log)
        {
            //
            // myMessages looks like this:
            // {
            //   "records":[
            //     {...},
            //     {...}
            //     ...
            //   ]
            // }
            //
            string outputBinding = Util.GetEnvironmentVariable("outputBinding");

            if (outputBinding.Length == 0)
            {
                log.Error("Value for outputBinding is required. Permitted values are: 'logstash', 'arcsight'.");
                return;
            }

            switch (outputBinding)
            {
            case "logstash":
                await Util.obLogstash(myMessages, log);

                break;

            case "arcsight":
                await Util.obArcsight(myMessages, log);

                break;

            case "splunk":
                await Util.obSplunk(myMessages, log);

                break;

            case "eventhub":
                await Util.obEventHub(myMessages, log);

                break;
            }
        }
 private static void UploadSensorData(DataTable atomicTable, TraceWriter log)
 {
     try
     {
         using (var dbConnection = new SqlConnection(DbConnString))
         {
             dbConnection.Open();
             SqlBulkCopy bcp = new SqlBulkCopy(dbConnection)
             {
                 DestinationTableName = DbTableName
             };
             bcp.WriteToServer(atomicTable);
         }
     }
     catch (Exception ex)
     {
         log.Error($"Critical error '{ex.GetType()}': {ex.Message}");
     }
 }
Ejemplo n.º 28
0
        public static void Run([EventGridTrigger] JObject eventGridEvent, TraceWriter log)
        {
            log.Info("C# EventGrid trigger function processed a request.");
            log.Info(eventGridEvent.ToString(Formatting.Indented));

            try
            {
                // Copy to a static Album instance
                var ehEvent      = eventGridEvent.ToObject <EventGridEHEvent>();
                var uri          = new Uri(ehEvent.data.fileUrl);
                var measurements = Dump(uri);
            }
            catch (Exception e)
            {
                var s = string.Format(CultureInfo.InvariantCulture,
                                      "Error processing request. Exception: {0}, Request: {1}", e, eventGridEvent.ToString());
                log.Error(s);
            }
        }
Ejemplo n.º 29
0
        public async Task <bool> GenerateAndSaveCsv(IEnumerable <LicensePlateDataDocument> licensePlates)
        {
            var successful = false;

            _log.Info("Generating CSV file");
            string blobName = $"{DateTime.UtcNow.ToString("s")}.csv";

            using (var stream = new MemoryStream())
            {
                using (var textWriter = new StreamWriter(stream))
                    using (var csv = new CsvWriter(textWriter))
                    {
                        csv.Configuration.Delimiter = ",";
                        csv.WriteRecords(licensePlates.Select(ToLicensePlateData));
                        await textWriter.FlushAsync();

                        _log.Info($"Beginning file upload: {blobName}");
                        try
                        {
                            var container = _blobClient.GetContainerReference(_containerName);

                            // Retrieve reference to a blob.
                            var blob = container.GetBlockBlobReference(blobName);
                            await container.CreateIfNotExistsAsync();

                            // Upload blob.
                            stream.Position = 0;
                            // TODO 7: Asyncronously upload the blob from the memory stream.
                            // COMPLETE: await blob...;
                            await blob.UploadFromStreamAsync(stream);

                            successful = true;
                        }
                        catch (Exception e)
                        {
                            _log.Error($"Could not upload CSV file: {e.Message}", e);
                            successful = false;
                        }
                    }
            }

            return(successful);
        }
        public static async Task <IActionResult> Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = null)] HttpRequest req, TraceWriter log)
        {
            log.Info("Sentiment started");

            string sentence = req.Query["sentence"];

            if (string.IsNullOrEmpty(sentence))
            {
                log.Error("Sentence is empty");

                return((ActionResult) new BadRequestResult());
            }

            log.Info($"About to analyze: {sentence}");

            var score = await AnalysisService.AnalyzeWords(sentence);

            return((ActionResult) new OkObjectResult(score));
        }