public async virtual Task <HostSecretsInfo> GetHostSecretsAsync()
        {
            if (_hostSecrets == null)
            {
                HostSecrets hostSecrets = await LoadSecretsAsync <HostSecrets>();

                if (hostSecrets == null)
                {
                    _traceWriter.Verbose(Resources.TraceHostSecretGeneration);
                    hostSecrets = GenerateHostSecrets();
                    await PersistSecretsAsync(hostSecrets);
                }

                // Host secrets will be in the original persisted state at this point (e.g. encrypted),
                // so we read the secrets running them through the appropriate readers
                hostSecrets = ReadHostSecrets(hostSecrets);

                // If the persistence state of any of our secrets is stale (e.g. the encryption key has been rotated), update
                // the state and persist the secrets
                if (hostSecrets.HasStaleKeys)
                {
                    _traceWriter.Verbose(Resources.TraceStaleHostSecretRefresh);
                    await RefreshSecretsAsync(hostSecrets);
                }

                _hostSecrets = new HostSecretsInfo
                {
                    MasterKey    = hostSecrets.MasterKey.Value,
                    FunctionKeys = hostSecrets.FunctionKeys.ToDictionary(s => s.Name, s => s.Value)
                };
            }

            return(_hostSecrets);
        }
        public async Task RegisterRoute(Uri route, ParameterInfo triggerParameter, ITriggeredFunctionExecutor executor)
        {
            await EnsureServerOpen();

            string routeKey = route.LocalPath.ToLowerInvariant();

            if (_functions.ContainsKey(routeKey))
            {
                throw new InvalidOperationException(string.Format("Duplicate route detected. There is already a route registered for '{0}'", routeKey));
            }

            _functions.AddOrUpdate(routeKey, executor, (k, v) => { return(executor); });

            WebHookTriggerAttribute attribute = triggerParameter.GetCustomAttribute <WebHookTriggerAttribute>();
            IWebHookReceiver        receiver  = null;
            string receiverId  = string.Empty;
            string receiverLog = string.Empty;

            if (attribute != null && _webHookReceiverManager.TryParseReceiver(route.LocalPath, out receiver, out receiverId))
            {
                receiverLog = string.Format(" (Receiver: '{0}', Id: '{1}')", receiver.Name, receiverId);
            }

            MethodInfo method     = (MethodInfo)triggerParameter.Member;
            string     methodName = string.Format("{0}.{1}", method.DeclaringType, method.Name);

            _trace.Verbose(string.Format("WebHook route '{0}' registered for function '{1}'{2}", route.LocalPath, methodName, receiverLog));
        }
Ejemplo n.º 3
0
        public static async Task <HttpResponseMessage> Run(HttpRequestMessage req, ICollector <string> errormessage, TraceWriter log)
        {
            log.Verbose($"C# HTTP trigger function processed a request. RequestUri={req.RequestUri}");
            try
            {
                JObject data = await req.Content.ReadAsAsync <JObject>();

                log.Verbose($"received data :={data}", "JE.RMS.Services.GetJurisdictionList");

                List <SqlParameter> objprm = new List <SqlParameter>();
                objprm.Add(new SqlParameter("@countryIDs", data.SelectToken("countryID").ToString().TrimStart('{').TrimEnd('}')));
                log.Verbose($"calling sp", "JE.RMS.Services.GetJurisdictionList");

                List <Common.Model.Jurisdiction> obj = MSSQLConnection.ExecuteStoredProcedure <Common.Model.Jurisdiction>(Common.Constants.USPContstants.GetJurisdictionList, objprm);
                log.Verbose($"received response:={obj}", "JE.RMS.Services.GetJurisdictionList");

                return(req.CreateResponse(HttpStatusCode.OK, obj));
            }
            catch (Exception ex)
            {
                log.Error($"Exception ={ex}");
                errormessage.Add(JsonConvert.SerializeObject(ex).ToString());
                return(req.CreateErrorResponse(HttpStatusCode.InternalServerError, ex));
            }
        }
Ejemplo n.º 4
0
        public static void DBinsert(Weather entry, TraceWriter log)
        {
            log.Info($"DBinsert starts");
            try
            {
                var connstr = ConfigurationManager.ConnectionStrings["con_weather2"].ConnectionString;
                using (SqlConnection conn = new SqlConnection(connstr))
                {
                    conn.Open();
                    //log.Info($"Temp: {entry.Temperature}");

                    using (SqlCommand cmd = new SqlCommand(SQLins, conn))
                    {
                        cmd.Parameters.AddWithValue("@Temperature", entry.Temperature);
                        cmd.Parameters.AddWithValue("@TemperatureMax", entry.TemperatureMax);
                        cmd.Parameters.AddWithValue("@TemperatureMin", entry.TemperatureMin);
                        cmd.Parameters.AddWithValue("@Pressure", entry.Pressure);
                        cmd.Parameters.AddWithValue("@Humidity", entry.Humidity);
                        int rows = cmd.ExecuteNonQuery();
                        if (rows > 0)
                        {
                            log.Verbose($"Row Inserted: {rows}");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                log.Verbose($"Error inserting row: {ex.Message} {ex.InnerException}");
            }
        }
        public static void InvokeTerminalCommand(string command, TraceWriter log)
        {
            log.Verbose($"Starting command: {command}");

            var proc = new Process
            {
                StartInfo = new ProcessStartInfo
                {
                    FileName               = "cmd",
                    Arguments              = $"/c \"{command}\"",
                    UseShellExecute        = false,
                    RedirectStandardOutput = true,
                    RedirectStandardError  = true,
                    CreateNoWindow         = true
                }
            };

            proc.Start();
            while (!proc.StandardOutput.EndOfStream)
            {
                string outputLine = proc.StandardOutput.ReadLine();
                log.Info(outputLine);
            }

            //if (!proc.StandardError.EndOfStream)
            {
                string errorOutput = proc.StandardError.ReadToEnd();
                log.Error(errorOutput);
            }

            log.Verbose($"Finished command: {command}");
        }
Ejemplo n.º 6
0
        public static void Run([CosmosDBTrigger(
                                    databaseName: "IoT",
                                    collectionName: "IoT1",
                                    ConnectionStringSetting = "DBConnection",
                                    LeaseCollectionName = "leases")] IReadOnlyList <Document> input, TraceWriter log)
        {
            string connectionString        = ConfigurationSettings.AppSettings["EventHubConnection"];
            var    connectionStringBuilder = new EventHubsConnectionStringBuilder(connectionString)
            {
                EntityPath = "rafat-eventhub1"
            };
            var client = Microsoft.Azure.EventHubs.EventHubClient.CreateFromConnectionString(connectionStringBuilder.ToString());

            foreach (var doc in input)
            {
                string    json = string.Format("{{\"iotid\":\"{0}\",\"temp\":{1}}}", doc.GetPropertyValue <string>("iotid"), doc.GetPropertyValue <string>("temp"));
                EventData data = new Microsoft.Azure.EventHubs.EventData(Encoding.UTF8.GetBytes(json));
                client.SendAsync(data);
            }
            if (input != null && input.Count > 0)
            {
                log.Verbose("Documents modified " + input.Count);
                log.Verbose("First document Id " + input[0].Id);
            }
        }
Ejemplo n.º 7
0
        public static async Task <HttpResponseMessage> Run(HttpRequestMessage req, ICollector <string> errormessage, TraceWriter log)
        {
            log.Verbose($"C# HTTP trigger function processed a request. RequestUri={req.RequestUri}");
            try
            {
                JObject data = await req.Content.ReadAsAsync <JObject>();

                log.Verbose($"received data :={data}", "JE.RMS.Services.AssignUserRoles");

                List <SqlParameter> objprm = new List <SqlParameter>();
                objprm.Add(new SqlParameter("@userID", Convert.ToInt32(data.SelectToken("UserID").ToString().TrimStart('{').TrimEnd('}'))));
                objprm.Add(new SqlParameter("@userName", data.SelectToken("UserName").ToString().TrimStart('{').TrimEnd('}')));
                objprm.Add(new SqlParameter("@firstName", data.SelectToken("FirstName").ToString().TrimStart('{').TrimEnd('}')));
                objprm.Add(new SqlParameter("@lastName", data.SelectToken("LastName").ToString().TrimStart('{').TrimEnd('}')));
                objprm.Add(new SqlParameter("@email", data.SelectToken("Email").ToString().TrimStart('{').TrimEnd('}')));
                objprm.Add(new SqlParameter("@createdBy", Convert.ToInt32(data.SelectToken("CreatedBy").ToString().TrimStart('{').TrimEnd('}'))));
                objprm.Add(new SqlParameter("@updatedBy", Convert.ToInt32(data.SelectToken("UpdatedBy").ToString().TrimStart('{').TrimEnd('}'))));
                objprm.Add(new SqlParameter("@isActive", data.SelectToken("IsActive").ToString().TrimStart('{').TrimEnd('}')));
                objprm.Add(new SqlParameter("@roleID", Convert.ToInt32(data.SelectToken("RoleID").ToString().TrimStart('{').TrimEnd('}'))));

                log.Verbose($"calling sp", "JE.RMS.Services.AssignUserRoles");

                var obj = MSSQLConnection.ExecuteStoredProcedure <string>(Common.Constants.USPContstants.AssignUserRoles, objprm);
                log.Verbose($"received response:={obj}", "JE.RMS.Services.AssignUserRoles");
                return(req.CreateResponse(HttpStatusCode.OK, obj));
            }
            catch (Exception ex)
            {
                log.Error($"Exception ={ex}");
                errormessage.Add(JsonConvert.SerializeObject(ex).ToString());
                return(req.CreateErrorResponse(HttpStatusCode.InternalServerError, ex));
            }
        }
Ejemplo n.º 8
0
        public static async Task <HttpResponseMessage> Run(
            [HttpTrigger(AuthorizationLevel.Function, "post", Route = "tsdb")] HttpRequestMessage req,
            [Table("hostmetrics", Connection = "StorageConnectionString")] ICollector <HostMetric> outTable,
            TraceWriter log)
        {
            dynamic data = await req.Content.ReadAsAsync <object>();

            var metrics = data as IEnumerable <dynamic>;

            if (metrics == null)
            {
                return(req.CreateResponse(HttpStatusCode.BadRequest, "Please pass a host metric collection in the request body"));
            }

            foreach (var metric in metrics)
            {
                var hostMetric = new HostMetric()
                {
                    PartitionKey = metric.hostId,
                    RowKey       = metric.time + "+" + metric.name,
                    hostId       = metric.hostId,
                    name         = metric.name,
                    time         = metric.time,
                    value        = metric.value,
                };
                log.Verbose(JsonConvert.SerializeObject(metric));
                log.Verbose(JsonConvert.SerializeObject(hostMetric));
                outTable.Add(hostMetric);
            }
            return(req.CreateResponse(HttpStatusCode.OK));
        }
Ejemplo n.º 9
0
        public static async Task <IActionResult> RunAsync(
            [HttpTrigger(AuthorizationLevel.Function, "delete", Route = "servers")] HttpRequest req,
            TraceWriter log, ExecutionContext context)
        {
            string configFile = Path.Combine(context.FunctionAppDirectory, configPath);
            var    file       = new FileInfo(configFile);
            var    config     = KubernetesClientConfiguration.BuildConfigFromConfigFile(file);

            client = new Kubernetes(config);

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

            string requestBody = new StreamReader(req.Body).ReadToEnd();

            log.Verbose($"Request\n{requestBody}");
            dynamic data = JsonConvert.DeserializeObject(requestBody);

            name = name ?? data?.name;
            log.Verbose($"name: {name}");
            if (!string.IsNullOrEmpty(name))
            {
                var result = await DeleteServer(log, name);

                if (result)
                {
                    return(new OkObjectResult($"Server {name} delete succeded"));
                }
                return(new OkObjectResult($"Server {name} delete failed"));
            }

            return(new BadRequestObjectResult("Please pass a name of server the query string or in the request body"));
        }
Ejemplo n.º 10
0
        // This function will get triggered/executed when a new message is written to the Message Queue.
        // It's not doing any real work here, but it could do some work like making a request to a service
        // like Microsoft Graph API, or doing sentiment analysis and outputting table storage.
        // To learn more about Queues, go to https://azure.microsoft.com/en-us/documentation/articles/websites-dotnet-webjobs-sdk-storage-queues-how-to/
        public static void ProcessQueueMessage([QueueTrigger("queue")] string message, TraceWriter log)
        {
            log.Verbose("Message Received:");
            log.Verbose(message);

            telemetry.TrackEvent($"Message Received: {message}");
        }
Ejemplo n.º 11
0
        public static async Task <HttpResponseMessage> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "FundingProfilePatterns/OrgFSP")] HttpRequestMessage req
            , [DocumentDB("FundingPolicy", "OrganisationFSPProfilePattern", ConnectionStringSetting = "CosmosDB")] IAsyncCollector <object> outputDocument
            , TraceWriter log)
        {
            log.Info("C# HTTP trigger function processed a request to create funding profile pattern.");

            OrganisationFundingProfilePattern OrgfundingStreamPeriodPatternRequest = await req.Content.ReadAsAsync <OrganisationFundingProfilePattern>();

            log.Verbose("Incoming OrgID and funding stream period code:" + OrgfundingStreamPeriodPatternRequest.AllocationOrganisation.OrganisationID + "" + OrgfundingStreamPeriodPatternRequest.FundingStreamPeriodProfilePattern.FundingStreamPeriodCode);
            var doc = new OrganisationFundingProfilePatternDocument(OrgfundingStreamPeriodPatternRequest);

            log.Verbose("Outgoing funding stream period code and UKPRN: " + doc.AllocationOrganisation.AlternateOrganisation.Identifier + doc.FundingStreamPeriodProfilePattern.FundingStreamPeriodCode);
            await outputDocument.AddAsync(doc);

            if (doc.FundingStreamPeriodProfilePattern.FundingStreamPeriodCode != " ")
            {
                return(req.CreateResponse(HttpStatusCode.OK, $"{doc.FundingStreamPeriodProfilePattern.FundingStreamPeriodCode} for Organisation {doc.AllocationOrganisation.AlternateOrganisation.Identifier} was created"));
            }
            else
            {
                return(req.CreateResponse(HttpStatusCode.BadRequest,
                                          $"The request was incorrectly formatted."));
            }
        }
Ejemplo n.º 12
0
        static async Task <string> GetApiVersion(ResourceItem resource)
        {
            ResourceType matchingItem = _resourceTypes.Where(r => r.Type == resource.Type).FirstOrDefault();

            if (matchingItem != null)
            {
                _log.Verbose("API version found in ResourceTypes table");
                return(matchingItem.ApiVersion);
            }
            else
            {
                string apiVersion = await _resourceManager.GetApiVersion(resource.Type);

                if (!String.IsNullOrEmpty(apiVersion))
                {
                    _log.Verbose("Got API version from resource maanger service");
                    await AddResourceType(resource, apiVersion);

                    return(apiVersion);
                }
                else
                {
                    throw new Exception("Unable to get API version");
                }
            }
        }
Ejemplo n.º 13
0
        public static async Task Run(TraceWriter log)
        {
            var connStr = ConfigurationManager.ConnectionStrings["Updater"].ConnectionString;

            var sw = Stopwatch.StartNew();

            var accessor = new UpdaterAccessor(connStr);

            var stationsData = await GiosClient.DownloadData();

            foreach (var stationData in stationsData)
            {
                log.Verbose($"{stationData.CityName} {stationData.StationName}");

                await accessor.EnsureStation(stationData.CityName, stationData.StationName);

                await accessor.UpdateAqiMeasurement(stationData.CityName, stationData.StationName, stationData.Time, stationData.AirQualityIndex);

                foreach (var measurement in stationData.Measurements)
                {
                    log.Verbose($"\t{measurement.Key}\t{measurement.Value}");

                    await accessor.UpdateMeasurement(stationData.CityName, stationData.StationName, stationData.Time, measurement.Key, measurement.Value);
                }
            }

            sw.Stop();

            log.Info($"Download completed in {sw.Elapsed.TotalMilliseconds} ms");
        }
Ejemplo n.º 14
0
        public static void Run([CosmosDBTrigger(
                                    databaseName: "Messages",
                                    collectionName: "MessagesCollection",
                                    ConnectionStringSetting = "CosmosDBConnectionString",
                                    LeaseCollectionName = "leases")] IReadOnlyList <Document> input, TraceWriter log)
        {
            if (input != null && input.Count > 0)
            {
                log.Verbose("Documents modified " + input.Count);
                log.Verbose("First document Id " + input[0].Id);


                Task.Factory.StartNew(async() =>
                {
                    string azure = "https://jrsimplemessagessignalr.azurewebsites.net/MessageHub";

                    HubConnection connection;
                    connection = new HubConnectionBuilder()
                                 .WithUrl(azure)
                                 .Build();

                    await connection.StartAsync();

                    await connection.SendAsync("SendMessage", input[0].GetPropertyValue <string>("key"), input[0]);
                });
            }
        }
Ejemplo n.º 15
0
        public async Task StartAsync(CancellationToken cancellationToken)
        {
            ThrowIfDisposed();

            if (_timer != null && _timer.Enabled)
            {
                throw new InvalidOperationException("The listener has already been started.");
            }

            // if schedule monitoring is enabled, record (or initialize)
            // the current schedule status
            bool     isPastDue = false;
            DateTime now       = DateTime.Now;

            if (ScheduleMonitor != null)
            {
                // check to see if we've missed an occurrence since we last started.
                // If we have, invoke it immediately.
                _scheduleStatus = await ScheduleMonitor.GetStatusAsync(_timerName);

                TimeSpan pastDueDuration = await ScheduleMonitor.CheckPastDueAsync(_timerName, now, _schedule, _scheduleStatus);

                isPastDue = pastDueDuration != TimeSpan.Zero;

                if (_scheduleStatus == null)
                {
                    // no schedule status has been stored yet, so initialize
                    _scheduleStatus = new ScheduleStatus
                    {
                        Last = default(DateTime),
                        Next = _schedule.GetNextOccurrence(now)
                    };
                }
            }

            if (isPastDue)
            {
                _trace.Verbose(string.Format("Function '{0}' is past due on startup. Executing now.", _timerName));
                await InvokeJobFunction(now, true);
            }
            else if (_attribute.RunOnStartup)
            {
                // The job is configured to run immediately on startup
                _trace.Verbose(string.Format("Function '{0}' is configured to run on startup. Executing now.", _timerName));
                await InvokeJobFunction(now);
            }

            // log the next several occurrences to console for visibility
            string nextOccurrences = TimerInfo.FormatNextOccurrences(_schedule, 5);

            _trace.Verbose(nextOccurrences);

            // start the timer
            now = DateTime.Now;
            DateTime nextOccurrence = _schedule.GetNextOccurrence(now);
            TimeSpan nextInterval   = nextOccurrence - now;

            StartTimer(nextInterval);
        }
        public async Task StartAsync(CancellationToken cancellationToken)
        {
            ThrowIfDisposed();

            if (_timer != null && _timer.Enabled)
            {
                throw new InvalidOperationException("The listener has already been started.");
            }

            // if schedule monitoring is enabled, record (or initialize)
            // the current schedule status
            bool isPastDue = false;

            // we use DateTime.Now rather than DateTime.UtcNow to allow the local machine to set the time zone. In Azure this will be
            // UTC by default, but can be configured to use any time zone if it makes scheduling easier.
            DateTime now = DateTime.Now;

            if (ScheduleMonitor != null)
            {
                // check to see if we've missed an occurrence since we last started.
                // If we have, invoke it immediately.
                ScheduleStatus = await ScheduleMonitor.GetStatusAsync(_timerName);

                _trace.Verbose($"Function '{_timerName}' initial status: Last='{ScheduleStatus?.Last.ToString("o")}', Next='{ScheduleStatus?.Next.ToString("o")}'");
                TimeSpan pastDueDuration = await ScheduleMonitor.CheckPastDueAsync(_timerName, now, _schedule, ScheduleStatus);

                isPastDue = pastDueDuration != TimeSpan.Zero;
            }

            if (ScheduleStatus == null)
            {
                // no schedule status has been stored yet, so initialize
                ScheduleStatus = new ScheduleStatus
                {
                    Last = default(DateTime),
                    Next = _schedule.GetNextOccurrence(now)
                };
            }

            if (isPastDue)
            {
                _trace.Verbose(string.Format("Function '{0}' is past due on startup. Executing now.", _timerName));
                await InvokeJobFunction(now, isPastDue : true);
            }
            else if (_attribute.RunOnStartup)
            {
                // The job is configured to run immediately on startup
                _trace.Verbose(string.Format("Function '{0}' is configured to run on startup. Executing now.", _timerName));
                await InvokeJobFunction(now, runOnStartup : true);
            }

            // log the next several occurrences to console for visibility
            string nextOccurrences = TimerInfo.FormatNextOccurrences(_schedule, 5);

            _trace.Info(nextOccurrences);

            StartTimer(DateTime.Now);
        }
Ejemplo n.º 17
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);
        }
Ejemplo n.º 18
0
        public static async Task <HttpResponseMessage> Run(HttpRequestMessage req, ICollector <string> errormessage, TraceWriter log)
        {
            log.Verbose($"C# HTTP trigger function processed a request. RequestUri={req.RequestUri}", "JE.RMS.Services.DMEEUserToCustomer");

            // Get request body
            try
            {
                using (HttpClient httpClient = new HttpClient())
                {
                    //Add Basic Authentication header
                    httpClient.BaseAddress = new System.Uri(ConfigurationManager.AppSettings["EnergyEarthBaseUrl"].ToString());
                    var auth = Encoding.ASCII.GetBytes(ConfigurationManager.AppSettings["EEUserName"].ToString() + ":" + ConfigurationManager.AppSettings["EEPassword"].ToString());
                    httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(auth));

                    string GetUsersUrl = ConfigurationManager.AppSettings["GetUsersUrl"].ToString();

                    //Get Users from Energy Earth API
                    var response = await httpClient.GetAsync(GetUsersUrl);

                    //Convert Users from Energy earth to Customer List Model
                    var customerList = JsonConvert.DeserializeObject <EECustomerList>(await response.Content.ReadAsStringAsync());

                    log.Verbose("Started migration of EE users to Customer Table", "JE.RMS.Services.DMEEUserToCustomer");

                    foreach (var customer in customerList.Users)
                    {
                        List <SqlParameter> CustomerParams = new List <SqlParameter>();
                        CustomerParams.Add(new SqlParameter("@Email", customer.Email));
                        CustomerParams.Add(new SqlParameter("@FirstName", customer.FirstName));
                        CustomerParams.Add(new SqlParameter("@LastName", customer.LastName));
                        CustomerParams.Add(new SqlParameter("@CompanyName", customer.CompanyName));
                        CustomerParams.Add(new SqlParameter("@UniqueID", customer.UserID));
                        CustomerParams.Add(new SqlParameter("@AccountAcceptanceDate", customer.AccountAcceptanceDate));
                        CustomerParams.Add(new SqlParameter("@StartingPointBalance", customer.StartingPointBalance));
                        CustomerParams.Add(new SqlParameter("@AvailablePointBalance", customer.AvailablePointBalance));
                        CustomerParams.Add(new SqlParameter("@AvailablePointBalanceDollars", customer.AvailablePointBalanceDollars));
                        CustomerParams.Add(new SqlParameter("@NumberofTransactions", customer.NumberofTransactions));
                        CustomerParams.Add(new SqlParameter("@AccountStatus", customer.AccountStatus));
                        CustomerParams.Add(new SqlParameter("@NextRewardDueDate", customer.NextRewardDueDate));
                        CustomerParams.Add(new SqlParameter("@ProgramName", customer.Program));

                        var RMSRewardID = MSSQLConnection.ExecuteStoredProcedure <string>(USPContstants.SaveCustomerFromEnergyEarth, CustomerParams);
                    }

                    log.Verbose("Completed migration of EE users to Customer Table", "JE.RMS.Services.DMEEUserToCustomer");

                    return(response);
                }
            }
            catch (Exception ex)
            {
                log.Error("Something went wrong while DMEEUserToCustomer", ex, "JE.RMS.Services.DMEEUserToCustomer");
                errormessage.Add(JsonConvert.SerializeObject(ex).ToString());
                return(req.CreateErrorResponse(HttpStatusCode.InternalServerError, ex));
            }
        }
Ejemplo n.º 19
0
        protected ScriptHost(ScriptHostConfiguration scriptConfig)
            : base(scriptConfig.HostConfig)
        {
            ScriptConfig = scriptConfig;

            if (scriptConfig.FileLoggingEnabled)
            {
                string hostLogFilePath = Path.Combine(scriptConfig.RootLogPath, "Host");
                _traceWriter = new FileTraceWriter(hostLogFilePath, TraceLevel.Verbose);
                scriptConfig.HostConfig.Tracing.Tracers.Add(_traceWriter);
            }
            else
            {
                _traceWriter = NullTraceWriter.Instance;
            }

            if (scriptConfig.TraceWriter != null)
            {
                scriptConfig.HostConfig.Tracing.Tracers.Add(scriptConfig.TraceWriter);
            }
            else
            {
                scriptConfig.TraceWriter = NullTraceWriter.Instance;
            }

            if (scriptConfig.FileWatchingEnabled)
            {
                _fileWatcher = new FileSystemWatcher(scriptConfig.RootScriptPath)
                {
                    IncludeSubdirectories = true,
                    EnableRaisingEvents   = true
                };
                _fileWatcher.Changed += OnFileChanged;
                _fileWatcher.Created += OnFileChanged;
                _fileWatcher.Deleted += OnFileChanged;
                _fileWatcher.Renamed += OnFileChanged;
            }

            // If a file change should result in a restart, we debounce the event to
            // ensure that only a single restart is triggered within a specific time window.
            // This allows us to deal with a large set of file change events that might
            // result from a bulk copy/unzip operation. In such cases, we only want to
            // restart after ALL the operations are complete and there is a quiet period.
            _restart = (e) =>
            {
                _traceWriter.Verbose(string.Format("File change of type '{0}' detected for '{1}'", e.ChangeType, e.FullPath));
                _traceWriter.Verbose("Host configuration has changed. Signaling restart.");

                // signal host restart
                _restartEvent.Set();
            };
            _restart = _restart.Debounce(500);

            // take a snapshot so we can detect function additions/removals
            _directoryCountSnapshot = Directory.EnumerateDirectories(ScriptConfig.RootScriptPath).Count();
        }
Ejemplo n.º 20
0
        public static async Task Run([CosmosDBTrigger(
                                          databaseName: "Your_database_name",
                                          collectionName: "Review",
                                          ConnectionStringSetting = "CosmosDbConnectionString",
                                          LeaseCollectionName = "leases")] IReadOnlyList <Document> documents,

                                     [DocumentDB(databaseName: "Your_database_name",
                                                 collectionName: "Review",
                                                 ConnectionStringSetting = "CosmosDbConnectionString",
                                                 CreateIfNotExists = false)] IAsyncCollector <dynamic> results,

                                     TraceWriter log)
        {
            if (documents != null && documents.Count > 0)
            {
                log.Verbose($"Documents modified  {documents.Count}");
                log.Verbose($"First document Id { documents[0].Id}");

                ITextAnalyticsAPI client = new TextAnalyticsAPI();

                client.AzureRegion     = AzureRegions.Westcentralus;
                client.SubscriptionKey = "<Your_Subscription_Key>";

                string languageToAnalyze = "en";
                int    cnt = 0;
                foreach (var document in documents)
                {
                    if (!string.IsNullOrEmpty(document.GetPropertyValue <string>("Satisfaction")))
                    {
                        continue;
                    }
                    var content = document.GetPropertyValue <string>("Content");
                    SentimentBatchResult result = client.Sentiment(
                        new MultiLanguageBatchInput(
                            new List <MultiLanguageInput>
                    {
                        new MultiLanguageInput(languageToAnalyze, id: cnt.ToString(), text: content)
                    }
                            )
                        );
                    cnt++;
                    var evaluationResult = result.Documents[0].Score;
                    var newDocument      = new
                    {
                        id           = document.Id,
                        Content      = content,
                        Satisfaction = evaluationResult
                    };

                    await results.AddAsync(newDocument);

                    log.Verbose($"Review evaluated: {content}");
                    log.Verbose($"Evaluation result: {evaluationResult}");
                }
            }
        }
        public override async Task Invoke(object[] parameters)
        {
            object           input       = parameters[0];
            TraceWriter      traceWriter = (TraceWriter)parameters[1];
            IBinder          binder      = (IBinder)parameters[2];
            ExecutionContext functionExecutionContext = (ExecutionContext)parameters[3];

            try
            {
                _fileTraceWriter.Verbose(string.Format("Function started"));

                var scriptExecutionContext = CreateScriptExecutionContext(input, traceWriter, _fileTraceWriter, binder, functionExecutionContext);

                // if there are any binding parameters in the output bindings,
                // parse the input as json to get the binding data
                Dictionary <string, string> bindingData = new Dictionary <string, string>();
                if (_outputBindings.Any(p => p.HasBindingParameters) ||
                    _inputBindings.Any(p => p.HasBindingParameters))
                {
                    bindingData = GetBindingData(input);
                }
                bindingData["InvocationId"] = functionExecutionContext.InvocationId.ToString();

                await ProcessInputBindingsAsync(binder, scriptExecutionContext, bindingData);

                object functionResult = await ScriptFunc(scriptExecutionContext);

                // normalize output binding results
                IDictionary <string, object> functionOutputs = functionResult as IDictionary <string, object>;
                if (functionResult != null && _outputBindings.Count == 1)
                {
                    // if there is only a single output binding allow that binding value
                    // to be specified directly (i.e. normalize output format)
                    var binding = _outputBindings.Single();
                    functionOutputs = functionResult as IDictionary <string, object>;
                    if (functionOutputs == null || !functionOutputs.ContainsKey(binding.Name))
                    {
                        functionOutputs = new Dictionary <string, object>()
                        {
                            { binding.Name, functionResult }
                        };
                    }
                }

                await ProcessOutputBindingsAsync(_outputBindings, input, binder, bindingData, functionOutputs);

                _fileTraceWriter.Verbose(string.Format("Function completed (Success)"));
            }
            catch (Exception ex)
            {
                _fileTraceWriter.Error(ex.Message, ex);
                _fileTraceWriter.Verbose(string.Format("Function completed (Failure)"));
                throw;
            }
        }
        public static async Task Run(TimerInfo getScheduledReadEnergyEarthMessagesTimer, ICollector <string> errormessage, TraceWriter log)
        {
            if (getScheduledReadEnergyEarthMessagesTimer.IsPastDue)
            {
                log.Verbose("Timer is running late!", "JE.RMS.Services.ScheduledReadEnergyEarthMessagesFromQueue");
            }

            try
            {
                var connectionString = ConfigurationManager.AppSettings["MyServiceBusReader"].ToString();

                SubscriptionClient client = SubscriptionClient.CreateFromConnectionString(connectionString, "fulfillmentrequest", "EnergyEarthSubscription");

                int batchSize            = Convert.ToInt32(ConfigurationManager.AppSettings["ReadEnergyEarthMessageBatchSize"].ToString());
                var brokeredMessagesList = client.ReceiveBatch(1);

                List <Guid> messageLockTokenList = new List <System.Guid>();

                if (brokeredMessagesList.Count() > 0)
                {
                    foreach (BrokeredMessage message in brokeredMessagesList)
                    {
                        var raw = message.GetBody <string>();
                        var RewardFulfillmentRequestList = JsonConvert.DeserializeObject <RewardFulfillmentRequestList>(raw);

                        using (HttpClient httpClient = new HttpClient())
                        {
                            //Add Basic Authentication header
                            httpClient.BaseAddress = new Uri(ConfigurationManager.AppSettings["ProcessFulfillmentUrl"].ToString());

                            //log.Verbose($"Calling Update point status API, UserId : {CustomerUniqueId}, with Status : {PointStatus.Status}", "JE.RMS.Services.ProcessFulfillmentForEnergyEarth");
                            var response = await httpClient.PostAsJsonAsync(string.Empty, RewardFulfillmentRequestList);

                            if (response.IsSuccessStatusCode)
                            {
                                log.Verbose($"Success : Process fulfillment for EE", "JE.RMS.Services.ScheduledReadEnergyEarthMessagesFromQueue");
                            }
                            else
                            {
                                log.Error($"Error : Process fulfillment for EE", null, "JE.RMS.Services.ScheduledReadEnergyEarthMessagesFromQueue");
                            }
                        }
                        messageLockTokenList.Add(message.LockToken);
                    }

                    client.CompleteBatch(messageLockTokenList);
                    log.Verbose($"Completed : Process fulfillment for EE batch", "JE.RMS.Services.ScheduledReadEnergyEarthMessagesFromQueue");
                }
            }
            catch (Exception ex)
            {
                log.Error("Something went wrong while ScheduledReadEnergyEarthMessagesFromQueue", ex, "JE.RMS.Services.ScheduledReadEnergyEarthMessagesFromQueue");
                errormessage.Add(JsonConvert.SerializeObject(ex).ToString());
            }
        }
Ejemplo n.º 23
0
        public static async void Run(TimerInfo updateCustomerExtendedTimer, ICollector <string> errormessage, TraceWriter log)
        {
            log.Verbose($"C# Timer trigger function processed a request", "JE.RMS.Services.ScheduledUpdateCustomerExtended");

            try
            {
                log.Verbose($"Update Customer Extended started on : {DateTime.Now.ToString()}", "JE.RMS.Services.ScheduledUpdateCustomerExtended");

                //Get All Customer Unique IDs
                List <string> ListCustomerUniqueIDs = MSSQLConnection.ExecuteStoredProcedure <string>(Common.Constants.USPContstants.GetAllCustomerUniqueID).ToList();

                //Fetch Customers and update customer extended
                foreach (var uniqueId in ListCustomerUniqueIDs)
                {
                    using (HttpClient httpClient = new HttpClient())
                    {
                        //Add Basic Authentication header
                        httpClient.BaseAddress = new Uri(ConfigurationManager.AppSettings["GetUserFunctionUrl"].ToString());

                        string GetUserFunctionUrl = ConfigurationManager.AppSettings["GetUserFunctionCode"].ToString() + uniqueId;
                        var    response           = await httpClient.GetAsync(GetUserFunctionUrl);

                        if (response.IsSuccessStatusCode)
                        {
                            var responseUser = JsonConvert.DeserializeObject <CustomerExtendedList>(await response.Content.ReadAsStringAsync());
                            var userData     = responseUser.Users.FirstOrDefault();

                            List <SqlParameter> CustomerExtendedParams = new List <SqlParameter>();
                            CustomerExtendedParams.Add(new SqlParameter("@CustomerID", string.Empty));
                            CustomerExtendedParams.Add(new SqlParameter("@UniqueID", uniqueId));
                            CustomerExtendedParams.Add(new SqlParameter("@AccountAcceptanceDate", userData.AccountAcceptanceDate));
                            CustomerExtendedParams.Add(new SqlParameter("@StartingPointBalance", userData.StartingPointBalance));
                            CustomerExtendedParams.Add(new SqlParameter("@AvailablePointBalance", userData.AvailablePointBalance));
                            CustomerExtendedParams.Add(new SqlParameter("@AvailablePointBalanceDollars", userData.AvailablePointBalanceDollars));
                            CustomerExtendedParams.Add(new SqlParameter("@NumberofTransactions", userData.NumberofTransactions));
                            CustomerExtendedParams.Add(new SqlParameter("@AccountStatus", userData.AccountStatus));
                            CustomerExtendedParams.Add(new SqlParameter("@NextRewardDueDate", userData.NextRewardDueDate));
                            var customerExtendedID = MSSQLConnection.ExecuteStoredProcedure <long>(USPContstants.SaveCustomerExtended, CustomerExtendedParams);
                        }
                        else
                        {
                            errormessage.Add(response.Content.ReadAsStringAsync().Result);
                        }
                    }
                }

                log.Verbose($"Update Customer Extended completed on : {DateTime.Now.ToString()}", "JE.RMS.Services.ScheduledUpdateCustomerExtended");
            }
            catch (Exception ex)
            {
                log.Error("Something went wrong while UpdateCustomerExtended", ex, "JE.RMS.Services.ScheduledUpdateCustomerExtended");
                errormessage.Add(JsonConvert.SerializeObject(ex).ToString());
            }
        }
Ejemplo n.º 24
0
 public static void Run([CosmosDBTrigger(
                             databaseName: "databaseName",
                             collectionName: "collectionName",
                             ConnectionStringSetting = "",
                             LeaseCollectionName = "leases")] IReadOnlyList <Document> input, TraceWriter log)
 {
     if (input != null && input.Count > 0)
     {
         log.Verbose("Documents modified " + input.Count);
         log.Verbose("First document Id " + input[0].Id);
     }
 }
Ejemplo n.º 25
0
 public static void Run([CosmosDBTrigger(
                             databaseName: "paystra-api-test",
                             collectionName: "paystra-api-test",
                             ConnectionStringSetting = "https://paystra-api.documents.azure.com:443/",
                             LeaseCollectionName = "leases")] IReadOnlyList <Document> documents, TraceWriter log)
 {
     if (documents != null && documents.Count > 0)
     {
         log.Verbose("Documents modified " + documents.Count);
         log.Verbose("First document Id " + documents[0].Id);
     }
 }
Ejemplo n.º 26
0
 public static void Run([CosmosDBTrigger(
                             databaseName: "CosmosDBTaxiApp",
                             collectionName: "CosmosDBTaxiAppDB",
                             ConnectionStringSetting = "CosmosDBConnectionString",
                             LeaseCollectionName = "leases")] IReadOnlyList <Document> documents, TraceWriter log)
 {
     if (documents != null && documents.Count > 0)
     {
         log.Verbose("Documents modified " + documents.Count);
         log.Verbose("First document Id " + documents[0].Id);
     }
 }
 public static void Run([CosmosDBTrigger(
                             databaseName: "TablesDB",
                             collectionName: "PrintList",
                             ConnectionStringSetting = "DefaultEndpointsProtocol=https;AccountName=dbserverlesscosmos;AccountKey=66sGoaHZlOVR4YNqvipbOurp55fINYHlm0r4RtqmGPeDISJXJflmOaYSbPwxNPrM2ELwPE9kowNoFVR7sFUWDA==;TableEndpoint=https://dbserverlesscosmos.table.cosmosdb.azure.com:443/;",
                             LeaseCollectionName = "leases")] IReadOnlyList <Document> documents, TraceWriter log)
 {
     if (documents != null && documents.Count > 0)
     {
         log.Verbose("Documents modified " + documents.Count);
         log.Verbose("First document Id " + documents[0].Id);
     }
 }
        public static async Task <HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequestMessage req, TraceWriter log)
        {
            log.Info("HtmlToPdfConverter processing a request.");

            string html = await req.Content.ReadAsStringAsync();

            if (string.IsNullOrWhiteSpace(html))
            {
                return(req.CreateResponse(HttpStatusCode.BadRequest, "Please pass a document content on the request data"));
            }

            var pageSize = GetPageSize(req.Headers, PageSize.Default, log);

            if (req.Headers.Contains("PageOrientation"))
            {
                string pageOrientationValue = req.Headers.GetValues("PageOrientation").First().ToLowerInvariant();
                log.Info($"PageOrientation header found with value: {pageOrientationValue}");
                pageSize = pageOrientationValue == "landscape" ? pageSize.Rotate() : pageSize;
            }
            else
            {
                log.Verbose($"PageOrientation header NOT found using default value");
            }

            int leftMargin   = GetHeaderValueAsInt(req.Headers, "LeftMargin", 36, log);
            int rightMargin  = GetHeaderValueAsInt(req.Headers, "RightMargin", 36, log);
            int topMargin    = GetHeaderValueAsInt(req.Headers, "TopMargin", 36, log);
            int bottomMargin = GetHeaderValueAsInt(req.Headers, "BottomMargin", 36, log);

            try
            {
                log.Verbose($"Converting HTml into PDF");
                var pdfBytes = Convert(html, pageSize, leftMargin, rightMargin, topMargin, bottomMargin, log);

                log.Verbose($"Creating response");
                var response = req.CreateResponse(HttpStatusCode.OK);
                response.Content = new ByteArrayContent(pdfBytes);
                response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
                {
                    FileName = "Matchreport.pdf"
                };
                response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");

                log.Info("HtmlToPdfConverter process finished.");
                return(response);
            }
            catch (Exception ex)
            {
                log.Warning("Exception during PDF and response creation");
                return(req.CreateResponse(HttpStatusCode.BadRequest, $"Exception during PDF creation, message {ex.Message}"));
            }
        }
Ejemplo n.º 29
0
        public static async void Run(TimerInfo evaluateRewardsTrxTimer, ICollector <string> errormessage, TraceWriter log)
        {
            try
            {
                // Retrieve storage account from connection string
                CloudStorageAccount storageAccount = CloudStorageAccount.Parse(ConfigurationManager.ConnectionStrings["jermsstorage_STORAGE"].ToString());
                // Create the queue client
                CloudQueueClient queueClient = storageAccount.CreateCloudQueueClient();

                // Retrieve a reference to a queue
                CloudQueue queue = queueClient.GetQueueReference("rewardfulfillmentrequestqueue");
                // Get the next message
                IEnumerable <CloudQueueMessage> retrievedMessage = queue.GetMessages(Convert.ToInt32(ConfigurationManager.AppSettings["ReadRewardsTrxReceivedFromQueueBatchSize"]));
                log.Verbose($"After the reading of queue message = {retrievedMessage.Count()}", "JE.RMS.Services.ScheduledReadRewardsTrxReceivedFromQueue");
                string rewardfulfillmentrequest = "[";
                bool   IsQueueEmpty             = true;
                foreach (var item in retrievedMessage)
                {
                    rewardfulfillmentrequest += item.AsString + ",";
                    //Process the message in less than 30 seconds, and then delete the message
                    queue.DeleteMessage(item.Id, item.PopReceipt);
                    IsQueueEmpty = false;
                }
                rewardfulfillmentrequest += "]";


                // Call SaveRewardsTrx to save rewards transaction.
                if (!IsQueueEmpty)
                {
                    using (HttpClient client = new HttpClient())
                    {
                        var SaveRewardsTrxEndpoint = ConfigurationManager.AppSettings["EvaluateRewardsTrx"].ToString();
                        var accept = "application/json";
                        client.DefaultRequestHeaders.Add("Accept", accept);

                        using (var response = await client.PostAsync(SaveRewardsTrxEndpoint, new StringContent(rewardfulfillmentrequest, Encoding.UTF8, "application/x-www-form-urlencoded")))
                        {
                            var result = await response.Content.ReadAsStringAsync();

                            log.Verbose($"Response ={result}", "JE.RMS.Services.ScheduledReadRewardsTrxReceivedFromQueue");
                        }
                    }
                }

                log.Verbose($"C# trigger queue function processed a request. inputmessage= {rewardfulfillmentrequest}", "JE.RMS.Services.ScheduledReadRewardsTrxReceivedFromQueue");
            }
            catch (Exception ex)
            {
                log.Error($"Exception ={ex}", ex, "JE.RMS.Services.ReadGetRewardsTrxReceived");
                errormessage.Add(JsonConvert.SerializeObject(ex).ToString());
            }
        }
        private void ProcessLeaseError(string reason)
        {
            if (HasLease)
            {
                ResetLease();

                _traceWriter.Info($"Failed to renew host lock lease: {reason}");
            }
            else
            {
                _traceWriter.Verbose($"Host instance '{_instanceId}' failed to acquire host lock lease: {reason}");
            }
        }