public static async Task Listener([WebHookTrigger] WebHookContext context, TraceWriter trace)
        {
            trace.Info("Route: /LogicApp/Listener received data");
            JObject dataEvent = JObject.Parse(await context.Request.Content.ReadAsStringAsync());

            trace.Info("Data: \n" + dataEvent.ToString());

            context.Response = new HttpResponseMessage(HttpStatusCode.Accepted)
            {
                Content = new StringContent((JObject.FromObject(new { 
                    message = "The bot says: " + dataEvent["message"]
                })).ToString())
            };
        }
 /// <summary>
 /// This WebHook declares its route, and is invoked by POST requests
 /// to http://localhost:{port}/Sample/HookB.
 /// </summary>
 public static async Task HookB(
     [WebHookTrigger("Sample/HookB")] HttpRequestMessage request, 
     TraceWriter trace)
 {
     string body = await request.Content.ReadAsStringAsync();
     trace.Info(string.Format("HookB invoked! Body: {0}", body));
 }
        public static async Task WebHookTrigger(HttpRequestMessage request, TraceWriter traceWriter)
        {
            string body = await request.Content.ReadAsStringAsync();

            InvokeData = body;

            traceWriter.Info(string.Format("C# WebHookTrigger function received message '{0}'", body));
        }
        public static void SendSimplePubSubMessage([Redis("simpleMessages", Mode.PubSub)] out string message, TextWriter log, TraceWriter trace)
        {
            message = "this is a test";

            log.WriteLine("sending message: " + message);

            trace.Info(string.Format("New message sent: {0}", message));
        }
 /// <summary>
 /// Demonstrates binding to a custom POCO Type, including model binding in other
 /// binders to values from that POCO.
 /// </summary>
 public static void HookC(
     [WebHookTrigger] Order order,
     [File(@"{OrderId}_{CustomerName}.txt", FileAccess.Write)] out string output,
     TraceWriter trace)
 {
     output = "Order Received!";
     trace.Info(string.Format("HookC invoked! OrderId: {0}", order.OrderId));
 }
        public static async Task SingletonJob([QueueTrigger("singleton-test")] WorkItem workItem, TraceWriter trace)
        {
            trace.Info("Singleton method started");

            await Task.Delay(10 * 1000);

            trace.Info("Singleton method completed");
        }
        /// <summary>
        /// GitHub WebHook example, showing integration with the ASP.NET WebHooks SDK.
        /// The route uses the format {receiver}/{id} where the receiver "github" corresponds
        /// to the <see cref="GitHubWebHookReceiver"/> that was registered on startup via
        /// <see cref="WebHooksConfiguration.UseReceiver{T}"/>, and the "issues" Id component
        /// corresponds to the "Issues" secret configured in app.config.
        /// Incoming requests will be authenticated by <see cref="GitHubWebHookReceiver"/> prior
        /// to invoking this job function.
        /// </summary>
        public static void GitHub(
            [WebHookTrigger("github/issues")] string body,
            TraceWriter trace)
        {
            dynamic issueEvent = JObject.Parse(body);

            trace.Info(string.Format("GitHub Issues WebHook invoked - Issue: '{0}', Action: '{1}', ",
                issueEvent.issue.title, issueEvent.action));
        }
Ejemplo n.º 8
0
        private async Task<bool> SendJSONtoURL(JObject json, string url, TraceWriter trace)
        {
            var client = new HttpClient();
            var response = await client.PostAsJsonAsync(url, json);

            if (response.StatusCode != HttpStatusCode.OK) {
                trace.Error(String.Format("Status Code: {0} - Content: {1}", response.StatusCode, response.Content));
                return false;
            }

            trace.Info("Finished sending message to Slack");
            return true;
        }
Ejemplo n.º 9
0
        // Private Functions

        private async Task SendSlackMessage(Message m, TraceWriter trace)
        {
            JObject slackMessage = new JObject();
            slackMessage["username"] = "******";
            slackMessage["text"] = m.contents;
            slackMessage["icon_emoji"] = ":zumo:";

            if (m.to != null) {
                slackMessage["channel"] = m.to;
            }

            trace.Info("Data: \n" + slackMessage.ToString());
            await SendJSONtoURL(slackMessage, ConfigurationManager.AppSettings["SLACK_CustomerNotificationsHook"], trace);
        }
 /// <summary>
 /// Event handler for the output stream.
 /// </summary>
 private static void OutputCollectionDataAdded(object sender, DataAddedEventArgs e, TraceWriter traceWriter)
 {
     // trace objects written to the output stream
     var source = (PSDataCollection<PSObject>)sender;
     var data = source[e.Index];
     if (data != null)
     {
         var msg = data.ToString();
         traceWriter.Info(msg);
     }
 }
 public void Information(string message)
 {
     _logger.Info(message);
 }
        public void RunAndBlock(CancellationToken cancellationToken = default(CancellationToken))
        {
            // Start the host and restart it if requested. Host Restarts will happen when
            // host level configuration files change
            do
            {
                ScriptHost newInstance = null;
                try
                {
                    // if we were in an error state retain that,
                    // otherwise move to default
                    if (State != ScriptHostState.Error)
                    {
                        State = ScriptHostState.Default;
                    }

                    // Create a new host config, but keep the host id from existing one
                    _config.HostConfig = new JobHostConfiguration
                    {
                        HostId = _config.HostConfig.HostId
                    };
                    OnInitializeConfig(_config);
                    newInstance = _scriptHostFactory.Create(_settingsManager, _config);
                    _traceWriter = newInstance.TraceWriter;

                    _currentInstance = newInstance;
                    lock (_liveInstances)
                    {
                        _liveInstances.Add(newInstance);
                    }

                    OnHostCreated();

                    if (_traceWriter != null)
                    {
                        string message = string.Format("Starting Host (HostId={0}, Version={1}, ProcessId={2}, Debug={3})",
                            newInstance.ScriptConfig.HostConfig.HostId, ScriptHost.Version, Process.GetCurrentProcess().Id, newInstance.InDebugMode.ToString());
                        _traceWriter.Info(message);
                    }
                    newInstance.StartAsync(cancellationToken).GetAwaiter().GetResult();

                    // log any function initialization errors
                    LogErrors(newInstance);

                    OnHostStarted();

                    // only after ALL initialization is complete do we set the
                    // state to Running
                    State = ScriptHostState.Running;
                    LastError = null;

                    // Wait for a restart signal. This event will automatically reset.
                    // While we're restarting, it is possible for another restart to be
                    // signaled. That is fine - the restart will be processed immediately
                    // once we get to this line again. The important thing is that these
                    // restarts are only happening on a single thread.
                    WaitHandle.WaitAny(new WaitHandle[]
                    {
                        cancellationToken.WaitHandle,
                        newInstance.RestartEvent,
                        _stopEvent
                    });

                    // Orphan the current host instance. We're stopping it, so it won't listen for any new functions
                    // it will finish any currently executing functions and then clean itself up.
                    // Spin around and create a new host instance.
                    Task taskIgnore = Orphan(newInstance);
                }
                catch (Exception ex)
                {
                    State = ScriptHostState.Error;
                    LastError = ex;

                    // We need to keep the host running, so we catch and log any errors
                    // then restart the host
                    if (_traceWriter != null)
                    {
                        _traceWriter.Error("A ScriptHost error has occurred", ex);
                    }

                    // If a ScriptHost instance was created before the exception was thrown
                    // Orphan and cleanup that instance.
                    if (newInstance != null)
                    {
                        Orphan(newInstance, forceStop: true)
                            .ContinueWith(t =>
                            {
                                if (t.IsFaulted)
                                {
                                    t.Exception.Handle(e => true);
                                }
                            }, TaskContinuationOptions.ExecuteSynchronously);
                    }

                    // Wait for a short period of time before restarting to
                    // avoid cases where a host level config error might cause
                    // a rapid restart cycle
                    Task.Delay(_config.RestartInterval).GetAwaiter().GetResult();
                }
            }
            while (!_stopped && !cancellationToken.IsCancellationRequested);
        }
 /// <summary>
 /// This WebHook uses the default convention based routing, and is invoked
 /// by POST requests to http://localhost:{port}/WebHookSamples/HookA.
 /// </summary>
 public static void HookA([WebHookTrigger] string body, TraceWriter trace)
 {
     trace.Info(string.Format("HookA invoked! Body: {0}", body));
 }
Ejemplo n.º 14
0
        internal static bool TryParseFunctionMetadata(string functionName, JObject functionConfig, Dictionary<string, HttpTriggerBindingMetadata> mappedHttpFunctions, TraceWriter traceWriter, Lazy<string[]> functionFilesProvider, out FunctionMetadata functionMetadata, out string error)
        {
            error = null;
            functionMetadata = ParseFunctionMetadata(functionName, functionConfig);

            if (functionMetadata.IsExcluded)
            {
                traceWriter.Info(string.Format("Function '{0}' is marked as excluded", functionName));
                functionMetadata = null;
                return true;
            }

            if (functionMetadata.IsDisabled)
            {
                traceWriter.Info(string.Format("Function '{0}' is disabled", functionName));
            }

            // determine the primary script
            string[] functionFiles = functionFilesProvider.Value;
            if (functionFiles.Length == 0)
            {
                error = "No function script files present.";
                return false;
            }
            string scriptFile = DeterminePrimaryScriptFile(functionConfig, functionFiles);
            if (string.IsNullOrEmpty(scriptFile))
            {
                error =
                    "Unable to determine the primary function script. Try renaming your entry point script to 'run' (or 'index' in the case of Node), " +
                    "or alternatively you can specify the name of the entry point script explicitly by adding a 'scriptFile' property to your function metadata.";
                return false;
            }
            functionMetadata.ScriptFile = scriptFile;

            // determine the script type based on the primary script file extension
            functionMetadata.ScriptType = ParseScriptType(functionMetadata.ScriptFile);

            functionMetadata.EntryPoint = (string)functionConfig["entryPoint"];

            var httpTriggerBindingMetadata = functionMetadata.InputBindings.OfType<HttpTriggerBindingMetadata>().SingleOrDefault();
            if (httpTriggerBindingMetadata != null)
            {
                if (string.IsNullOrWhiteSpace(httpTriggerBindingMetadata.Route))
                {
                    // if no explicit route is provided, default to the function name
                    httpTriggerBindingMetadata.Route = functionName;
                }

                // disallow custom routes in our own reserved route space
                string httpRoute = httpTriggerBindingMetadata.Route.Trim('/').ToLowerInvariant();
                if (httpRoute.StartsWith("admin"))
                {
                    error = "The specified route conflicts with one or more built in routes.";
                    return false;
                }

                // prevent duplicate/conflicting routes
                foreach (var pair in mappedHttpFunctions)
                {
                    if (HttpRoutesConflict(httpTriggerBindingMetadata, pair.Value))
                    {
                        error = $"The route specified conflicts with the route defined by function '{pair.Key}'.";
                        return false;
                    }
                }

                mappedHttpFunctions.Add(functionName, httpTriggerBindingMetadata);
            }

            return true;
        }
Ejemplo n.º 15
0
        // WebJob Functions (This are loaded by the SDK, which looks for functions with various attributes defined by the WebJobs SDK

        /// <summary>
        /// Grabs messages from the "SlackMessage" Queue and posts them to the Slack Webhook specified in App Settings under "SLACK_CustomerNotificationsHook"
        /// </summary>
        /// <param name="m">Message from the Queue to be posted to Slack</param>
        /// <param name="trace">This is used to log from the application to the Azure WebJobs Dashboard</param>
        /// <returns></returns>
        public async Task ProcessSlackMessage([QueueTrigger("SlackMessage")] Message m, TraceWriter trace)
        {
            trace.Info(String.Format("Dequeued message for {0}: {1}", m.to, m.contents));
            await SendSlackMessage(m, trace);
        }
Ejemplo n.º 16
0
 public static void TimerTrigger(TimerInfo timerInfo, TraceWriter traceWriter)
 {
     traceWriter.Info(string.Format("C# TimerTrigger function invoked at ", DateTime.Now));
 }