/// <summary>
 /// Constructs a new instance
 /// </summary>
 /// <param name="queue">The <see cref="CloudQueue"/> the <see cref="QueueProcessor"/> will operate on.</param>
 /// <param name="trace">The <see cref="TraceWriter"/> to write to.</param>
 /// <param name="queueConfiguration">The queue configuration.</param>
 /// <param name="poisonQueue">The queue to move messages to when unable to process a message after the maximum dequeue count has been exceeded. May be null.</param>
 internal QueueProcessorFactoryContext(CloudQueue queue, TraceWriter trace, IQueueConfiguration queueConfiguration, CloudQueue poisonQueue = null)
     : this(queue, trace, poisonQueue)
 {
     BatchSize = queueConfiguration.BatchSize;
     MaxDequeueCount = queueConfiguration.MaxDequeueCount;
     NewBatchThreshold = queueConfiguration.NewBatchThreshold;
 }
Esempio n. 2
0
        public static ITriggerBindingProvider Create(INameResolver nameResolver,
            IStorageAccountProvider storageAccountProvider,
            IExtensionTypeLocator extensionTypeLocator,
            IHostIdProvider hostIdProvider,
            IQueueConfiguration queueConfiguration,
            IBackgroundExceptionDispatcher backgroundExceptionDispatcher,
            IContextSetter<IMessageEnqueuedWatcher> messageEnqueuedWatcherSetter,
            IContextSetter<IBlobWrittenWatcher> blobWrittenWatcherSetter,
            ISharedContextProvider sharedContextProvider,
            IExtensionRegistry extensions,
            SingletonManager singletonManager,
            TraceWriter trace)
        {
            List<ITriggerBindingProvider> innerProviders = new List<ITriggerBindingProvider>();
            innerProviders.Add(new QueueTriggerAttributeBindingProvider(nameResolver, storageAccountProvider,
                queueConfiguration, backgroundExceptionDispatcher, messageEnqueuedWatcherSetter,
                sharedContextProvider, trace));
            innerProviders.Add(new BlobTriggerAttributeBindingProvider(nameResolver, storageAccountProvider,
                extensionTypeLocator, hostIdProvider, queueConfiguration, backgroundExceptionDispatcher,
                blobWrittenWatcherSetter, messageEnqueuedWatcherSetter, sharedContextProvider, singletonManager, trace));

            // add any registered extension binding providers
            foreach (ITriggerBindingProvider provider in extensions.GetExtensions(typeof(ITriggerBindingProvider)))
            {
                innerProviders.Add(provider);
            }

            return new CompositeTriggerBindingProvider(innerProviders);
        }
 /// <summary>
 /// Protected constructor.
 /// </summary>
 /// <param name="config">The config class.</param>
 protected TraceListener(AppConfig config)
 {
     this.config = config;
       if (this.config.LogToFile) {
     this.writer = new DefaultTraceWriter(config);
       }
 }
 public TraceWriterFunctionInstanceLogger(TraceWriter trace)
 {
     if (trace == null)
     {
         throw new ArgumentNullException("trace");
     }
     _trace = trace;
 }
 public HostListenerFactory(IEnumerable<IFunctionDefinition> functionDefinitions, SingletonManager singletonManager, IJobActivator activator, INameResolver nameResolver, TraceWriter trace)
 {
     _functionDefinitions = functionDefinitions;
     _singletonManager = singletonManager;
     _activator = activator;
     _nameResolver = nameResolver;
     _trace = trace;
 }
        public FunctionIndexProvider(ITypeLocator typeLocator,
            ITriggerBindingProvider triggerBindingProvider,
            IBindingProvider bindingProvider,
            IJobActivator activator,
            IFunctionExecutor executor,
            IExtensionRegistry extensions,
            SingletonManager singletonManager,
            TraceWriter trace)
        {
            if (typeLocator == null)
            {
                throw new ArgumentNullException("typeLocator");
            }

            if (triggerBindingProvider == null)
            {
                throw new ArgumentNullException("triggerBindingProvider");
            }

            if (bindingProvider == null)
            {
                throw new ArgumentNullException("bindingProvider");
            }

            if (activator == null)
            {
                throw new ArgumentNullException("activator");
            }

            if (executor == null)
            {
                throw new ArgumentNullException("executor");
            }

            if (extensions == null)
            {
                throw new ArgumentNullException("extensions");
            }

            if (singletonManager == null)
            {
                throw new ArgumentNullException("singletonManager");
            }

            if (trace == null)
            {
                throw new ArgumentNullException("trace");
            }

            _typeLocator = typeLocator;
            _triggerBindingProvider = triggerBindingProvider;
            _bindingProvider = bindingProvider;
            _activator = activator;
            _executor = executor;
            _extensions = extensions;
            _singletonManager = singletonManager;
            _trace = trace;
        }
 public JobHostContext(IFunctionIndexLookup functionLookup,
     IFunctionExecutor executor,
     IListener listener,
     TraceWriter trace)
 {
     _functionLookup = functionLookup;
     _executor = executor;
     _listener = listener;
     _trace = trace;
 }
        public QueueTriggerBinding(string parameterName,
            IStorageQueue queue,
            ITriggerDataArgumentBinding<IStorageQueueMessage> argumentBinding,
            IQueueConfiguration queueConfiguration,
            IBackgroundExceptionDispatcher backgroundExceptionDispatcher,
            IContextSetter<IMessageEnqueuedWatcher> messageEnqueuedWatcherSetter,
            ISharedContextProvider sharedContextProvider,
            TraceWriter trace)
        {
            if (queue == null)
            {
                throw new ArgumentNullException("queue");
            }

            if (argumentBinding == null)
            {
                throw new ArgumentNullException("argumentBinding");
            }

            if (queueConfiguration == null)
            {
                throw new ArgumentNullException("queueConfiguration");
            }

            if (backgroundExceptionDispatcher == null)
            {
                throw new ArgumentNullException("backgroundExceptionDispatcher");
            }

            if (messageEnqueuedWatcherSetter == null)
            {
                throw new ArgumentNullException("messageEnqueuedWatcherSetter");
            }

            if (sharedContextProvider == null)
            {
                throw new ArgumentNullException("sharedContextProvider");
            }

            if (trace == null)
            {
                throw new ArgumentNullException("trace");
            }

            _parameterName = parameterName;
            _queue = queue;
            _argumentBinding = argumentBinding;
            _bindingDataContract = CreateBindingDataContract(argumentBinding);
            _queueConfiguration = queueConfiguration;
            _backgroundExceptionDispatcher = backgroundExceptionDispatcher;
            _messageEnqueuedWatcherSetter = messageEnqueuedWatcherSetter;
            _sharedContextProvider = sharedContextProvider;
            _trace = trace;
            _converter = CreateConverter(queue);
        }
 public JobHostContext(IFunctionIndexLookup functionLookup,
     IFunctionExecutor executor,
     IListener listener,
     TraceWriter trace,
     IAsyncCollector<FunctionInstanceLogEntry> fastLogger = null)
 {
     _functionLookup = functionLookup;
     _executor = executor;
     _listener = listener;
     _trace = trace;
     _fastLogger = fastLogger;
 }
Esempio n. 10
0
        public QueueListenerFactory(IStorageQueue queue,
            IQueueConfiguration queueConfiguration,
            IBackgroundExceptionDispatcher backgroundExceptionDispatcher,
            IContextSetter<IMessageEnqueuedWatcher> messageEnqueuedWatcherSetter,
            ISharedContextProvider sharedContextProvider,
            TraceWriter trace,
            ITriggeredFunctionExecutor executor)
        {
            if (queue == null)
            {
                throw new ArgumentNullException("queue");
            }

            if (queueConfiguration == null)
            {
                throw new ArgumentNullException("queueConfiguration");
            }

            if (backgroundExceptionDispatcher == null)
            {
                throw new ArgumentNullException("backgroundExceptionDispatcher");
            }

            if (messageEnqueuedWatcherSetter == null)
            {
                throw new ArgumentNullException("messageEnqueuedWatcherSetter");
            }

            if (sharedContextProvider == null)
            {
                throw new ArgumentNullException("sharedContextProvider");
            }

            if (trace == null)
            {
                throw new ArgumentNullException("trace");
            }

            if (executor == null)
            {
                throw new ArgumentNullException("executor");
            }

            _queue = queue;
            _poisonQueue = CreatePoisonQueueReference(queue.ServiceClient, queue.Name);
            _queueConfiguration = queueConfiguration;
            _backgroundExceptionDispatcher = backgroundExceptionDispatcher;
            _messageEnqueuedWatcherSetter = messageEnqueuedWatcherSetter;
            _sharedContextProvider = sharedContextProvider;
            _trace = trace;
            _executor = executor;
        }
        public HostMessageListenerFactory(IStorageQueue queue,
            IQueueConfiguration queueConfiguration,
            IBackgroundExceptionDispatcher backgroundExceptionDispatcher,
            TraceWriter trace,
            IFunctionIndexLookup functionLookup,
            IFunctionInstanceLogger functionInstanceLogger,
            IFunctionExecutor executor)
        {
            if (queue == null)
            {
                throw new ArgumentNullException("queue");
            }

            if (queueConfiguration == null)
            {
                throw new ArgumentNullException("queueConfiguration");
            }

            if (backgroundExceptionDispatcher == null)
            {
                throw new ArgumentNullException("backgroundExceptionDispatcher");
            }

            if (trace == null)
            {
                throw new ArgumentNullException("trace");
            }

            if (functionLookup == null)
            {
                throw new ArgumentNullException("functionLookup");
            }

            if (functionInstanceLogger == null)
            {
                throw new ArgumentNullException("functionInstanceLogger");
            }

            if (executor == null)
            {
                throw new ArgumentNullException("executor");
            }

            _queue = queue;
            _queueConfiguration = queueConfiguration;
            _backgroundExceptionDispatcher = backgroundExceptionDispatcher;
            _trace = trace;
            _functionLookup = functionLookup;
            _functionInstanceLogger = functionInstanceLogger;
            _executor = executor;
        }
        /// <summary>
        /// Constructs a new instance
        /// </summary>
        /// <param name="context">The factory context.</param>
        public QueueProcessor(QueueProcessorFactoryContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            _queue = context.Queue;
            _poisonQueue = context.PoisonQueue;
            _trace = context.Trace;
            _maxDequeueCount = context.MaxDequeueCount;
            BatchSize = context.BatchSize;
            NewBatchThreshold = context.NewBatchThreshold;
        }
        public DefaultLoggerProvider(IStorageAccountProvider storageAccountProvider, TraceWriter trace)
        {
            if (storageAccountProvider == null)
            {
                throw new ArgumentNullException("storageAccountProvider");
            }
            if (trace == null)
            {
                throw new ArgumentNullException("trace");
            }

            _storageAccountProvider = storageAccountProvider;
            _trace = trace;
        }
        public QueueListener(IStorageQueue queue,
            IStorageQueue poisonQueue,
            ITriggerExecutor<IStorageQueueMessage> triggerExecutor,
            IDelayStrategy delayStrategy,
            IBackgroundExceptionDispatcher backgroundExceptionDispatcher,
            TraceWriter trace,
            SharedQueueWatcher sharedWatcher,
            IQueueConfiguration queueConfiguration)
        {
            if (trace == null)
            {
                throw new ArgumentNullException("trace");
            }

            if (queueConfiguration == null)
            {
                throw new ArgumentNullException("queueConfiguration");
            }

            if (queueConfiguration.BatchSize <= 0)
            {
                throw new ArgumentException("BatchSize must be greater than zero.");
            }

            if (queueConfiguration.MaxDequeueCount <= 0)
            {
                throw new ArgumentException("MaxDequeueCount must be greater than zero.");
            }

            _timer = new TaskSeriesTimer(this, backgroundExceptionDispatcher, Task.Delay(0));
            _queue = queue;
            _poisonQueue = poisonQueue;
            _triggerExecutor = triggerExecutor;
            _delayStrategy = delayStrategy;
            _backgroundExceptionDispatcher = backgroundExceptionDispatcher;
            _trace = trace;
            _queueConfiguration = queueConfiguration;

            if (sharedWatcher != null)
            {
                // Call Notify whenever a function adds a message to this queue.
                sharedWatcher.Register(queue.Name, this);
                _sharedWatcher = sharedWatcher;
            }

            EventHandler poisonMessageEventHandler = _sharedWatcher != null ? OnMessageAddedToPoisonQueue : (EventHandler)null;
            _queueProcessor = CreateQueueProcessor(
                _queue.SdkObject, _poisonQueue != null ? _poisonQueue.SdkObject : null,
                _trace, _queueConfiguration, poisonMessageEventHandler);
        }
        /// <summary>
        /// Constructs a new instance
        /// </summary>
        /// <param name="queue">The <see cref="CloudQueue"/> the <see cref="QueueProcessor"/> will operate on.</param>
        /// <param name="trace">The <see cref="TraceWriter"/> to write to.</param>
        /// <param name="poisonQueue">The queue to move messages to when unable to process a message after the maximum dequeue count has been exceeded. May be null.</param>
        public QueueProcessorFactoryContext(CloudQueue queue, TraceWriter trace, CloudQueue poisonQueue = null)         
        {
            if (queue == null)
            {
                throw new ArgumentNullException("queue");
            }
            if (trace == null)
            {
                throw new ArgumentNullException("trace");
            }

            Queue = queue;
            PoisonQueue = poisonQueue;
            Trace = trace;
        }
        public QueueTriggerAttributeBindingProvider(INameResolver nameResolver,
            IStorageAccountProvider accountProvider,
            IQueueConfiguration queueConfiguration,
            IBackgroundExceptionDispatcher backgroundExceptionDispatcher,
            IContextSetter<IMessageEnqueuedWatcher> messageEnqueuedWatcherSetter,
            ISharedContextProvider sharedContextProvider,
            TraceWriter trace)
        {
            if (accountProvider == null)
            {
                throw new ArgumentNullException("accountProvider");
            }

            if (queueConfiguration == null)
            {
                throw new ArgumentNullException("queueConfiguration");
            }

            if (backgroundExceptionDispatcher == null)
            {
                throw new ArgumentNullException("backgroundExceptionDispatcher");
            }

            if (messageEnqueuedWatcherSetter == null)
            {
                throw new ArgumentNullException("messageEnqueuedWatcherSetter");
            }

            if (sharedContextProvider == null)
            {
                throw new ArgumentNullException("sharedContextProvider");
            }

            if (trace == null)
            {
                throw new ArgumentNullException("trace");
            }

            _nameResolver = nameResolver;
            _accountProvider = accountProvider;
            _queueConfiguration = queueConfiguration;
            _backgroundExceptionDispatcher = backgroundExceptionDispatcher;
            _messageEnqueuedWatcherSetter = messageEnqueuedWatcherSetter;
            _sharedContextProvider = sharedContextProvider;
            _trace = trace;
        }
        public UpdateParameterLogCommand(IReadOnlyDictionary<string, IWatcher> watches,
            IStorageBlockBlob parameterLogBlob, TraceWriter trace)
        {
            if (parameterLogBlob == null)
            {
                throw new ArgumentNullException("parameterLogBlob");
            }
            else if (trace == null)
            {
                throw new ArgumentNullException("trace");
            }
            else if (watches == null)
            {
                throw new ArgumentNullException("watches");
            }

            _parameterLogBlob = parameterLogBlob;
            _trace = trace;
            _watches = watches;
        }
Esempio n. 18
0
        public static async System.Threading.Tasks.Task <IActionResult> RunAsync([HttpTrigger(AuthorizationLevel.Function, "get", Route = null)] HttpRequest req, TraceWriter log)
        {
            //using (var changelogStream = await _client.GetStreamAsync(Environment.GetEnvironmentVariable(@"ChangeLogUrl")))
            {
                // eg: https://www.phraseexpress.com/update13.php
                XDocument doc = XDocument.Load(Environment.GetEnvironmentVariable(@"VersionCheckUrl"));

                /* sample doc
                 * <xml>
                 * <debug></debug>
                 * <product>PhraseExpress</product>
                 * <interval>3</interval>
                 * <webpage></webpage>
                 * <info>1</info>
                 * <client>
                 * <versions>
                 * <newversion>13.0.0</newversion>
                 * <majorupdate>13.6.7</majorupdate>
                 * <minorupdate>13.0.0</minorupdate>
                 * <experimentalupdate>13.0.0</experimentalupdate>
                 * <betaversion>13.0.0</betaversion>
                 * </versions>
                 * <installationtype>
                 * */
                var clientElement = doc
                                    .Element(@"xml")
                                    .Element(@"client");
                var versions = clientElement
                               .Element(@"versions")
                               .Elements();

                var downloadBaseUrl = Environment.GetEnvironmentVariable(@"DownloadBaseUrl");

                string zipHashString,
                       zipDownloadUrl = $@"{downloadBaseUrl}PhraseExpress_USB.zip",
                       msiHashString,
                       msiDownloadUrl = $@"{downloadBaseUrl}PhraseExpressSetup.msi";

                string targetVersion;
                if (req.GetQueryParameterDictionary().TryGetValue(@"beta", out var betaValue) &&
                    bool.TryParse(betaValue, out var isBeta) &&
                    isBeta)
                {
                    targetVersion  = versions.Single(i => i.Name.LocalName.Equals(@"betaversion", StringComparison.OrdinalIgnoreCase)).Value;
                    zipDownloadUrl = $@"{downloadBaseUrl}PhraseExpressBeta_USB.zip";
                    msiDownloadUrl = $@"{downloadBaseUrl}PhraseExpressBetaSetup.exe";
                }
                else
                {   // assuming the default download URL is always a minor version
                    targetVersion = versions.Single(i => i.Name.LocalName.Equals(@"minorupdate", StringComparison.OrdinalIgnoreCase)).Value;
                }

                using (SHA256 sha = SHA256.Create())
                {
                    using (var versionDownload = await _client.GetStreamAsync(zipDownloadUrl))
                    {
                        var hashBytes = sha.ComputeHash(versionDownload);
                        zipHashString = string.Join(string.Empty, hashBytes.Select(b => b.ToString("X2")));
                        log.Info($@"ZIP computed hash: {zipHashString}");
                    }
                    GC.Collect();

                    using (var versionDownload = await _client.GetStreamAsync(msiDownloadUrl))
                    {
                        var hashBytes = sha.ComputeHash(versionDownload);
                        msiHashString = string.Join(string.Empty, hashBytes.Select(b => b.ToString("X2")));
                        log.Info($@"MSI computed hash: {msiHashString}");
                    }
                    GC.Collect();
                }
                GC.Collect();

                return(new OkObjectResult(new { version = targetVersion, zip = new { download = zipDownloadUrl, hash = zipHashString }, msi = new { download = msiDownloadUrl, hash = msiHashString } }));
            }
        }
 public RichMenuSampleApp(LineMessagingClient lineMessagingClient, TraceWriter log)
 {
     MessagingClient = lineMessagingClient;
     Log             = log;
 }
        public BlobListenerFactory(IHostIdProvider hostIdProvider,
            IQueueConfiguration queueConfiguration,
            IBackgroundExceptionDispatcher backgroundExceptionDispatcher,
            IContextSetter<IBlobWrittenWatcher> blobWrittenWatcherSetter,
            IContextSetter<IMessageEnqueuedWatcher> messageEnqueuedWatcherSetter,
            ISharedContextProvider sharedContextProvider,
            TraceWriter trace,
            string functionId,
            IStorageAccount account,
            IStorageBlobContainer container,
            IBlobPathSource input,
            ITriggeredFunctionExecutor executor)
        {
            if (hostIdProvider == null)
            {
                throw new ArgumentNullException("hostIdProvider");
            }

            if (queueConfiguration == null)
            {
                throw new ArgumentNullException("queueConfiguration");
            }

            if (backgroundExceptionDispatcher == null)
            {
                throw new ArgumentNullException("backgroundExceptionDispatcher");
            }

            if (blobWrittenWatcherSetter == null)
            {
                throw new ArgumentNullException("blobWrittenWatcherSetter");
            }

            if (messageEnqueuedWatcherSetter == null)
            {
                throw new ArgumentNullException("messageEnqueuedWatcherSetter");
            }

            if (sharedContextProvider == null)
            {
                throw new ArgumentNullException("sharedContextProvider");
            }

            if (trace == null)
            {
                throw new ArgumentNullException("trace");
            }

            if (account == null)
            {
                throw new ArgumentNullException("account");
            }

            if (container == null)
            {
                throw new ArgumentNullException("container");
            }

            if (input == null)
            {
                throw new ArgumentNullException("input");
            }

            if (executor == null)
            {
                throw new ArgumentNullException("executor");
            }

            _hostIdProvider = hostIdProvider;
            _queueConfiguration = queueConfiguration;
            _backgroundExceptionDispatcher = backgroundExceptionDispatcher;
            _blobWrittenWatcherSetter = blobWrittenWatcherSetter;
            _messageEnqueuedWatcherSetter = messageEnqueuedWatcherSetter;
            _sharedContextProvider = sharedContextProvider;
            _trace = trace;
            _functionId = functionId;
            _account = account;
            _container = container;
            _input = input;
            _executor = executor;
        }
Esempio n. 21
0
        public static async Task <string> HttpGetSharedAccessSignatureForBlobAsync([ActivityTrigger] string fileName,
                                                                                   [Blob("doneorders", FileAccess.Read, Connection = "StorageConnection")] CloudBlobContainer photosContainer, TraceWriter log)
        {
            if (string.IsNullOrWhiteSpace(fileName))
            {
                return(String.Empty);
            }

            var photoBlob = await photosContainer.GetBlobReferenceFromServerAsync(fileName);

            return(GetBlobSasUri(photoBlob));
        }
Esempio n. 22
0
        protected virtual void Initialize()
        {
            // read host.json and apply to JobHostConfiguration
            string hostConfigFilePath = Path.Combine(ScriptConfig.RootScriptPath, ScriptConstants.HostMetadataFileName);

            // If it doesn't exist, create an empty JSON file
            if (!File.Exists(hostConfigFilePath))
            {
                File.WriteAllText(hostConfigFilePath, "{}");
            }

            if (ScriptConfig.HostConfig.IsDevelopment)
            {
                ScriptConfig.HostConfig.UseDevelopmentSettings();
            }
            else
            {
                // TEMP: Until https://github.com/Azure/azure-webjobs-sdk-script/issues/100 is addressed
                // we're using some presets that are a good middle ground
                ScriptConfig.HostConfig.Queues.MaxPollingInterval    = TimeSpan.FromSeconds(10);
                ScriptConfig.HostConfig.Singleton.ListenerLockPeriod = TimeSpan.FromSeconds(15);
            }

            string json = File.ReadAllText(hostConfigFilePath);

            JObject hostConfig;

            try
            {
                hostConfig = JObject.Parse(json);
            }
            catch (JsonException ex)
            {
                throw new FormatException(string.Format("Unable to parse {0} file.", ScriptConstants.HostMetadataFileName), ex);
            }

            ApplyConfiguration(hostConfig, ScriptConfig);

            // Set up a host level TraceMonitor that will receive notificaition
            // of ALL errors that occur. This allows us to inspect/log errors.
            var traceMonitor = new TraceMonitor()
                               .Filter(p => { return(true); })
                               .Subscribe(HandleHostError);

            ScriptConfig.HostConfig.Tracing.Tracers.Add(traceMonitor);

            TraceWriter = ScriptConfig.TraceWriter;
            if (ScriptConfig.FileLoggingEnabled)
            {
                TraceLevel  hostTraceLevel  = ScriptConfig.HostConfig.Tracing.ConsoleLevel;
                string      hostLogFilePath = Path.Combine(ScriptConfig.RootLogPath, "Host");
                TraceWriter fileTraceWriter = new FileTraceWriter(hostLogFilePath, hostTraceLevel);
                if (TraceWriter != null)
                {
                    // create a composite writer so our host logs are written to both
                    TraceWriter = new CompositeTraceWriter(new[] { TraceWriter, fileTraceWriter });
                }
                else
                {
                    TraceWriter = fileTraceWriter;
                }
            }

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

            TraceWriter.Info(string.Format(CultureInfo.InvariantCulture, "Reading host configuration file '{0}'", hostConfigFilePath));

            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.Info(string.Format(CultureInfo.InvariantCulture, "File change of type '{0}' detected for '{1}'", e.ChangeType, e.FullPath));
                TraceWriter.Info("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();

            IMetricsLogger metricsLogger = ScriptConfig.HostConfig.GetService <IMetricsLogger>();

            if (metricsLogger == null)
            {
                ScriptConfig.HostConfig.AddService <IMetricsLogger>(new MetricsLogger());
            }

            // Bindings may use name resolution, so provide this before reading the bindings.
            var nameResolver = new NameResolver();

            var storageString = AmbientConnectionStringProvider.Instance.GetConnectionString(ConnectionStringNames.Storage);

            if (storageString == null)
            {
                // Disable core storage
                ScriptConfig.HostConfig.StorageConnectionString = null;
            }

            ScriptConfig.HostConfig.NameResolver = nameResolver;

            List <FunctionDescriptorProvider> descriptionProviders = new List <FunctionDescriptorProvider>()
            {
                new ScriptFunctionDescriptorProvider(this, ScriptConfig),
                new NodeFunctionDescriptorProvider(this, ScriptConfig),
                new DotNetFunctionDescriptionProvider(this, ScriptConfig)
            };

            // read all script functions and apply to JobHostConfiguration
            Collection <FunctionDescriptor> functions = ReadFunctions(ScriptConfig, descriptionProviders);
            string defaultNamespace = "Host";
            string typeName         = string.Format(CultureInfo.InvariantCulture, "{0}.{1}", defaultNamespace, "Functions");

            TraceWriter.Info(string.Format(CultureInfo.InvariantCulture, "Generating {0} job function(s)", functions.Count));
            Type        type  = FunctionGenerator.Generate(HostAssemblyName, typeName, functions);
            List <Type> types = new List <Type>();

            types.Add(type);

            ScriptConfig.HostConfig.TypeLocator = new TypeLocator(types);

            ApplyBindingConfiguration(functions, ScriptConfig.HostConfig);

            Functions = functions;

            if (ScriptConfig.FileLoggingEnabled)
            {
                PurgeOldLogDirectories();
            }
        }
        public static bool AddCORSHeaders(HttpRequestMessage req, ref HttpResponseMessage resp, string verbs, TraceWriter log)
        {
            if (req.Headers.Contains("Origin"))
            {
                var origin = req.Headers.GetValues("Origin").FirstOrDefault();
                if (origin != null)
                {
                    List <string> AllowedDomains = ConfigurationManager.AppSettings["AllowedOrigins"].Split(',').ToList();
                    if (AllowedDomains.Contains(origin))
                    {
                        resp.Headers.Add("Access-Control-Allow-Credentials", "true");
                        resp.Headers.Add("Access-Control-Allow-Origin", origin);
                        resp.Headers.Add("Access-Control-Allow-Methods", verbs);
                        resp.Headers.Add("Access-Control-Allow-Headers", "Content-Type");

                        return(true);
                    }
                    else
                    {
                        return(false);
                    }
                }
                else
                {
                    return(false);
                }
            }
            else
            {
                return(true);
            }
        }
 public override void Close() {
     try {
         if (traceWriter != null) {
             traceWriter.Flush();
             traceWriter.Close();
         }
     }
     finally {
         traceWriter = null;
         //fileName = null;  // It is more useful to allow the listener to be reopened upon subsequent write
         base.Close();       // This should be No-op
     }
 }
Esempio n. 25
0
 public SecretManager(ScriptSettingsManager settingsManager, string secretsPath, TraceWriter traceWriter, bool createHostSecretsIfMissing = false)
     : this(secretsPath, new DefaultKeyValueConverterFactory(settingsManager), traceWriter, createHostSecretsIfMissing)
 {
 }
 public static void Run([ActivityTrigger] ApprovalRequestMetadata requestMetadata, [SendGrid] out SendGridMessage message, TraceWriter log)
 {
     message = new SendGridMessage();
     message.AddTo(Environment.GetEnvironmentVariable("SendGrid:To"));
     message.AddContent("text/html", string.Format(Environment.GetEnvironmentVariable("SendGrid:ApprovalEmailTemplate"), requestMetadata.Subject, requestMetadata.Requestor, requestMetadata.ReferenceUrl, requestMetadata.InstanceId, Environment.GetEnvironmentVariable("Function:BasePath")));
     message.SetFrom(Environment.GetEnvironmentVariable("SendGrid:From"));
     message.SetSubject(String.Format(Environment.GetEnvironmentVariable("SendGrid:SubjectTemplate"), requestMetadata.Subject, requestMetadata.Requestor));
     log.Info($"Message '{message.Subject}' sent!");
 }
Esempio n. 27
0
        public static async Task Run([QueueTrigger("imagecomparison-items", Connection = "MainApplicationStorage")] string myQueueItem, TraceWriter log)
        {
            log.Info($"{FunctionName} Queue trigger function processed: {myQueueItem}");

            try
            {
                var onboardingRepository = ServiceLocator.ResolveRepository();
                if (!Guid.TryParse(myQueueItem, out var onboardingId))
                {
                    throw new ArgumentException($"The queue item ({myQueueItem}) could not be parsed as a valid onboarding session identifier");
                }

                var onboarding = await onboardingRepository.Get(onboardingId);

                if (onboarding == null)
                {
                    throw new InvalidOperationException($"No onboarding session could be located for the identifier: {onboardingId}");
                }

                var faceClient   = CreateFaceClient();
                var similarFaces = await faceClient.FindSimilarAsync(
                    Guid.Parse(onboarding.PassportFaceId),
                    new[] { Guid.Parse(onboarding.SelfieFaceId) });

                var validationState = GetValidationState(similarFaces);
                onboarding.SetImageComparisonState(validationState);

                // Persist state change
                await onboardingRepository.Update(onboarding);
            }
            catch (Exception ex)
            {
                log.Error($"Failed processing image comparison", ex);
                throw;
            }
        }
        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
                {
                    IsRunning = false;

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

                    newInstance.StartAsync(cancellationToken).Wait();

                    // write any function initialization errors to the log file
                    LogErrors(newInstance);

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

                    // only after ALL initialization is complete do we set this flag
                    IsRunning = true;
                    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)
                {
                    IsRunning = false;
                    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 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);
                            }
                        });
                    }

                    // 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(5000).Wait();
                }
            }while (!_stopped && !cancellationToken.IsCancellationRequested);
        }
Esempio n. 29
0
        public static async Task <HttpResponseMessage> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, Routes.Get, Route = Routes.GenerateStorageToken)] HttpRequestMessage req,
            [DocumentDB(nameof(Content), "{collectionId}", Id = "{documentId}")] Content content, string collectionId, string documentId, TraceWriter log)
        {
            UserStore userStore = null;

            var userId = Thread.CurrentPrincipal.GetClaimsIdentity()?.UniqueIdentifier();

            if (!string.IsNullOrEmpty(userId))
            {
                log.Info($"User is authenticated and has userId: {userId}");

                userStore = await DocumentClient.GetUserStore(userId, log);
            }


            if (!userStore?.UserRole.CanWrite() ?? false)
            {
                log.Info("Not authenticated");

                return(req.CreateResponse(HttpStatusCode.Unauthorized));
            }


            if (content == null)
            {
                log.Info($"No item in database matching the documentId paramater {documentId}");

                return(req.CreateErrorResponse(HttpStatusCode.NotFound, $"No item in database matching the documentId paramater {documentId}"));
            }

            log.Info($"Successfully found document in database matching the documentId paramater {documentId}");


            // Errors creating the storage container result in a 500 Internal Server Error
            var container = BlobClient.GetContainerReference(GetUploadContainerName(collectionId));

            await container.CreateIfNotExistsAsync();


            // TODO: Check if there's already a blob with a name matching the Id


            var sasUri = GetBlobSasUri(container, content.Name);

            var token = new StorageToken(content.Name, sasUri);

            return(req.CreateResponse(HttpStatusCode.OK, token));
        }
Esempio n. 30
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.");

            // parse query parameter
            string ShipmasterId = req.GetQueryNameValuePairs()
                                  .FirstOrDefault(q => string.Compare(q.Key, "ShipmasterId", true) == 0)
                                  .Value;

            if (string.IsNullOrEmpty(ShipmasterId))
            {
                return(req.CreateErrorResponse(HttpStatusCode.BadRequest, "Input is Null or Empty"));
            }

            List <ShipmentProduct> ShipmentProductlist = new List <ShipmentProduct>();
            var connectionString = Environment.GetEnvironmentVariable("SQLConnectionString");
            var selectQry        = "SELECT [Product] FROM  [dbo].[Shipment_Product] WHERE [ShipMasterID] = @ShipmasterId ";


            SqlConnection conn = new SqlConnection(connectionString);
            SqlCommand    command;

            command = new SqlCommand(selectQry, conn);
            command.Parameters.Add("@ShipmasterId", SqlDbType.NVarChar).Value = ShipmasterId;

            conn.Open();
            SqlDataReader reader = command.ExecuteReader();

            while (reader.Read())
            {
                ShipmentProduct product = new ShipmentProduct();
                product.ProductName = reader["Product"].ToString();
                ShipmentProductlist.Add(product);
            }

            reader.Close();
            conn.Close();

            return(new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent(JsonConvert.SerializeObject(ShipmentProductlist, Formatting.Indented), Encoding.UTF8, "application/json")
            });
        }
Esempio n. 31
0
        public static async Task <HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequestMessage req, TraceWriter log)
        {
            log.Info("C# HTTP trigger function processed a request.");

            // Get request body
            dynamic body = await req.Content.ReadAsAsync <object>();

            var dataStream = new MemoryStream();
            //var cloudStorageAccount = new CloudStorageAccount(new StorageCredentials(System.Environment.GetEnvironmentVariable("StorageAccount", System.EnvironmentVariableTarget.Process), System.Environment.GetEnvironmentVariable("StorageKey", System.EnvironmentVariableTarget.Process)), true);
            var cloudStorageAccount = new CloudStorageAccount(new StorageCredentials(body.storageName.ToString(), body.StorageKey.ToString()), true);
            var container           = cloudStorageAccount.CreateCloudBlobClient().GetContainerReference(body.container.ToString());
            var blobFileNames       = JsonConvert.DeserializeObject <string[]>(body.files.ToString());

            /*var dataStream = new MemoryStream();
             * var blobFileNames = new string[] { "Customer free text invoice.csv","General journal.csv" };
             * var cloudStorageAccount = new CloudStorageAccount(new StorageCredentials(System.Environment.GetEnvironmentVariable("StorageAccount", System.EnvironmentVariableTarget.Process), System.Environment.GetEnvironmentVariable("StorageKey", System.EnvironmentVariableTarget.Process)), true);
             * var container = cloudStorageAccount.CreateCloudBlobClient().GetContainerReference("d365processed");*/


            using (var archive = new ZipArchive(dataStream, ZipArchiveMode.Create, true))
            {
                foreach (var blobFileName in blobFileNames)
                {
                    var blob  = container.GetBlockBlobReference(blobFileName);
                    var entry = archive.CreateEntry(blobFileName);
                    using (var entryStream = entry.Open())
                        blob.DownloadToStream(entryStream);
                }
            }

            dataStream.Seek(0, SeekOrigin.Begin);
            CloudBlockBlob cloudBlockBlob = container.GetBlockBlobReference(body.packageName.ToString());

            cloudBlockBlob.UploadFromStream(dataStream);



            /*var memoryStream = new MemoryStream();
             * using (var archive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true))
             *  {
             *      var demoFile = archive.CreateEntry("foo.txt");
             *
             *      using (var entryStream = demoFile.Open())
             *      using (var streamWriter = new StreamWriter(entryStream))
             *      {
             *          streamWriter.Write("Bar!");
             *      }
             *  }
             *
             *  using (var fileStream = new FileStream(@"C:\Temp\test.zip", FileMode.Create))
             *  {
             *      memoryStream.Seek(0, SeekOrigin.Begin);
             *      memoryStream.CopyTo(fileStream);
             *  }*/

            byte[] zipBytes = dataStream.ToArray();
            return(req.CreateResponse(HttpStatusCode.OK, new { Zipfilename = body.packageName.ToString(), ZipContent = zipBytes }));
        }
 private bool EnsureWriter()
 {
     if (this.traceWriter == null)
     {
         if (string.IsNullOrEmpty(this.fileName))
         {
             return false;
         }
         lock (this.m_lockObject)
         {
             if (this.traceWriter != null)
             {
                 return true;
             }
             string fileName = this.fileName;
             for (int i = 0; i < 2; i++)
             {
                 try
                 {
                     this.Init();
                     this.traceWriter = new TraceWriter(fileName, this._bufferSize, this._retention, this._maxFileSize, this._maxNumberOfFiles);
                     break;
                 }
                 catch (IOException)
                 {
                     string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(this.fileName);
                     string extension = Path.GetExtension(this.fileName);
                     fileName = fileNameWithoutExtension + Guid.NewGuid().ToString() + extension;
                 }
                 catch (UnauthorizedAccessException)
                 {
                     break;
                 }
                 catch (Exception)
                 {
                     break;
                 }
             }
             if (this.traceWriter == null)
             {
                 this.fileName = null;
             }
         }
     }
     return (this.traceWriter != null);
 }
 public CustomMessageProcessor(OnMessageOptions messageOptions, TraceWriter trace)
     : base(messageOptions)
 {
     _trace = trace;
 }
Esempio n. 34
0
        public SecretManager(string secretsPath, IKeyValueConverterFactory keyValueConverterFactory, TraceWriter traceWriter, bool createHostSecretsIfMissing = false)
        {
            _traceWriter              = traceWriter.WithSource(ScriptConstants.TraceSourceSecretManagement);
            _secretsPath              = secretsPath;
            _hostSecretsPath          = Path.Combine(_secretsPath, ScriptConstants.HostMetadataFileName);
            _keyValueConverterFactory = keyValueConverterFactory;

            Directory.CreateDirectory(_secretsPath);

            _fileWatcher = new AutoRecoveringFileSystemWatcher(_secretsPath, "*.json");

            _fileWatcher.Changed += OnChanged;

            if (createHostSecretsIfMissing)
            {
                // The SecretManager implementation of GetHostSecrets will
                // create a host secret if one is not present.
                GetHostSecrets();
            }
        }
 public IRecurrentCommand CreateParameterLogUpdateCommand(IReadOnlyDictionary<string, IWatcher> watches, TraceWriter trace)
 {
     return null;
 }
Esempio n. 36
0
        public static IActionResult Run([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req, TraceWriter log)
        {
            log.Info("C# HTTP trigger function processed a request.");

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

            string  requestBody = new StreamReader(req.Body).ReadToEnd();
            dynamic data        = JsonConvert.DeserializeObject(requestBody);

            name = name ?? data?.name;

            return(name != null
                ? (ActionResult) new OkObjectResult($"Hello {name}!")
                : new BadRequestObjectResult("Please pass a name on the query string or in the request body"));
        }
        public static async Task <int> ProcessLineAsync([ActivityTrigger] LineItem item, TraceWriter log)
        {
            var result = await client.PostAsJsonAsync(item.Args[2], new { test = "value" });

            var contentBinary = await result.Content.ReadAsByteArrayAsync();

            return(item.Index);
        }
 public PubSubReceiver(RedisConfiguration config, string channelName, TraceWriter trace)
 {
     _config  = config;
     _channel = new RedisChannel(channelName, RedisChannel.PatternMode.Auto);
     _trace   = trace;
 }
Esempio n. 39
0
        public static async Task <HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = null)] HttpRequestMessage req, TraceWriter log)
        {
            log.Info("C# HTTP trigger function processed a request.");

            try
            {
                var photoList = await PhotoDatabaseService.GetAllPhotos();

                return(req.CreateResponse(HttpStatusCode.OK, photoList));
            }
            catch (System.Exception e)
            {
                return(req.CreateResponse(HttpStatusCode.InternalServerError, $"Get Photos Failed: {e.GetType().ToString()}: {e.Message}"));
            }
        }
Esempio n. 40
0
 public FastTableLoggerProvider(TraceWriter trace)
 {
     _hostInstanceLogger = new NullHostInstanceLogger();
     _traceWriterFunctionLogger = new TraceWriterFunctionInstanceLogger(trace);
 }
        public BlobTriggerBinding(ParameterInfo parameter,
            IArgumentBinding<IStorageBlob> argumentBinding,
            IStorageAccount hostAccount,
            IStorageAccount dataAccount,
            IBlobPathSource path,
            IHostIdProvider hostIdProvider,
            IQueueConfiguration queueConfiguration,
            IBackgroundExceptionDispatcher backgroundExceptionDispatcher,
            IContextSetter<IBlobWrittenWatcher> blobWrittenWatcherSetter,
            IContextSetter<IMessageEnqueuedWatcher> messageEnqueuedWatcherSetter,
            ISharedContextProvider sharedContextProvider,
            TraceWriter trace)
        {
            if (parameter == null)
            {
                throw new ArgumentNullException("parameter");
            }

            if (argumentBinding == null)
            {
                throw new ArgumentNullException("argumentBinding");
            }

            if (hostAccount == null)
            {
                throw new ArgumentNullException("hostAccount");
            }

            if (dataAccount == null)
            {
                throw new ArgumentNullException("dataAccount");
            }

            if (path == null)
            {
                throw new ArgumentNullException("path");
            }

            if (hostIdProvider == null)
            {
                throw new ArgumentNullException("hostIdProvider");
            }

            if (queueConfiguration == null)
            {
                throw new ArgumentNullException("queueConfiguration");
            }

            if (backgroundExceptionDispatcher == null)
            {
                throw new ArgumentNullException("backgroundExceptionDispatcher");
            }

            if (blobWrittenWatcherSetter == null)
            {
                throw new ArgumentNullException("blobWrittenWatcherSetter");
            }

            if (messageEnqueuedWatcherSetter == null)
            {
                throw new ArgumentNullException("messageEnqueuedWatcherSetter");
            }

            if (sharedContextProvider == null)
            {
                throw new ArgumentNullException("sharedContextProvider");
            }

            if (trace == null)
            {
                throw new ArgumentNullException("trace");
            }

            _parameter = parameter;
            _argumentBinding = argumentBinding;
            _hostAccount = hostAccount;
            _dataAccount = dataAccount;
            StorageClientFactoryContext context = new StorageClientFactoryContext
            {
                Parameter = parameter
            };
            _blobClient = dataAccount.CreateBlobClient(context);
            _accountName = BlobClient.GetAccountName(_blobClient);
            _path = path;
            _hostIdProvider = hostIdProvider;
            _queueConfiguration = queueConfiguration;
            _backgroundExceptionDispatcher = backgroundExceptionDispatcher;
            _blobWrittenWatcherSetter = blobWrittenWatcherSetter;
            _messageEnqueuedWatcherSetter = messageEnqueuedWatcherSetter;
            _sharedContextProvider = sharedContextProvider;
            _trace = trace;
            _converter = CreateConverter(_blobClient);
            _bindingDataContract = CreateBindingDataContract(path);
        }
 /// <summary>
 /// Creates a new instance.
 /// </summary>
 /// <param name="functionInstanceId">The instance ID of the function being bound to.</param>
 /// <param name="functionCancellationToken">The <see cref="CancellationToken"/> to use.</param>
 /// <param name="trace">The trace writer.</param>
 public FunctionBindingContext(Guid functionInstanceId, CancellationToken functionCancellationToken, TraceWriter trace)
 {
     _functionInstanceId = functionInstanceId;
     _functionCancellationToken = functionCancellationToken;
     _trace = trace;
 }
        public static async Task <List <string> > GetLines([ActivityTrigger] BlobItem item, TraceWriter log,
                                                           [Blob("complex/{name}", FileAccess.Read)] Stream blob)
        {
            List <string> lines = new List <string>();

            using (StreamReader streamReader = new StreamReader(blob))
            {
                string line;
                while ((line = await streamReader.ReadLineAsync()) != null)
                {
                    lines.Add(line);
                }
            }
            return(lines);
        }
Esempio n. 44
0
        public static async Task Run([TimerTrigger("10 0 * * * *")] TimerInfo myTimer, TraceWriter log)
        {
            try
            {
                log.Info("Starting processing...");

                // Call the Bittrex Trade manager with the strategy of our choosing.
                var manager = new GenericTradeManager(new BittrexApi(Constants.IsDryRunning), new BigThree(), new PushNotificationManager(), (a) => log.Info(a));

                // Call the process method to start processing the current situation.
                await manager.Process();
            }
            catch (Exception ex)
            {
                // If anything goes wrong log an error to Azure.
                log.Error(ex.Message + ex.StackTrace);
            }
        }
Esempio n. 45
0
        public static async Task <HttpResponseMessage> GetTasks
        (
            [HttpTrigger(AuthorizationLevel.Function, "get", Route = "v1/Tasks")]
            HttpRequestMessage req,
            TraceWriter log
        )
        {
            var auth = await Helpers.Security.ValidateTokenAsync(req.Headers.Authorization);


            // Dummy Data - change out code for a call to your backend data store.

            // Simulate a delay for fetching real data.
            Random r      = new Random();
            int    rDelay = r.Next(50, 800);
            await Task.Delay(rDelay);

            List <TaskItem> _data = new List <TaskItem>
            {
                new TaskItem {
                    Id          = Guid.NewGuid().ToString(),
                    Title       = "2018 Budget Review",
                    Description = "Review 2018 budget proposal",
                    Type        = "Budget",
                    CreatedOn   = DateTime.Now,
                    CompletedOn = null,
                    CreatorId   = Guid.NewGuid().ToString(),
                    CreatorName = "Sue Smith"
                },
                new TaskItem {
                    Id          = Guid.NewGuid().ToString(),
                    Title       = "PTO Approval",
                    Description = "Review/Approve PTO schedule",
                    Type        = "Approval",
                    CreatedOn   = DateTime.Now,
                    CompletedOn = null,
                    CreatorId   = Guid.NewGuid().ToString(),
                    CreatorName = "John Williams"
                },
                new TaskItem {
                    Id          = Guid.NewGuid().ToString(),
                    Title       = "PTO Approval",
                    Description = "Review Jason's PTO",
                    Type        = "Approval",
                    CreatedOn   = DateTime.Now,
                    CompletedOn = null,
                    CreatorId   = Guid.NewGuid().ToString(),
                    CreatorName = "Jason Shorts"
                },
                new TaskItem {
                    Id          = Guid.NewGuid().ToString(),
                    Title       = "Remove Legacy Server Rack",
                    Description = "Remove DB2 Server Rack",
                    Type        = "Infrastructure",
                    CreatedOn   = DateTime.Now,
                    CompletedOn = null,
                    CreatorId   = Guid.NewGuid().ToString(),
                    CreatorName = "Jason Shorts"
                }
                ,
                new TaskItem {
                    Id          = Guid.NewGuid().ToString(),
                    Title       = "Replace Legacy Laptops",
                    Description = "Provision new laptops for users with laptops older than 4 years.",
                    Type        = "Infrastructure",
                    CreatedOn   = DateTime.Now,
                    CompletedOn = null,
                    CreatorId   = Guid.NewGuid().ToString(),
                    CreatorName = "Laura Holdenly"
                }
            };

            return(req.CreateResponse <List <TaskItem> >(HttpStatusCode.OK, _data));
        }
Esempio n. 46
0
        public static async Task <HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequestMessage req, TraceWriter log)
        {
            log.Info($"C# HTTP trigger function for EventGrid begun");
            var response = string.Empty;

            var requestContent = await req.Content.ReadAsStringAsync();

            var eventGridEvents = JsonConvert.DeserializeObject <EventGridEvent[]>(requestContent);

            foreach (var eventGridEvent in eventGridEvents)
            {
                var dataObject = eventGridEvent.Data as JObject;

                // Deserialize the event data into the appropriate type based on event type
                if (string.Equals(eventGridEvent.EventType, SubscriptionValidationEvent, StringComparison.OrdinalIgnoreCase))
                {
                    var eventData = dataObject.ToObject <SubscriptionValidationEventData>();
                    log.Info($"Got SubscriptionValidation event data, validation code: {eventData.ValidationCode}, topic: {eventGridEvent.Topic}");

                    // Do any additional validation (as required) and then return back the below response
                    var responseData = new SubscriptionValidationResponse();
                    responseData.ValidationResponse = eventData.ValidationCode;
                    return(req.CreateResponse(HttpStatusCode.OK, responseData));
                }
                else if (string.Equals(eventGridEvent.EventType, StorageBlobCreatedEvent, StringComparison.OrdinalIgnoreCase))
                {
                    var eventData = dataObject.ToObject <StorageBlobCreatedEventData>();
                    log.Info($"Got BlobCreated event data, blob URI {eventData.Url}");

                    // Notify to slack
                    var payload = new
                    {
                        channel  = notifySlackChannel,
                        username = "******",
                        text     = $"New Blob Item was uploaded. Please access from {eventData.Url}",
                    };
                    var json = JsonConvert.SerializeObject(payload);
                    var res  = await notify.SendAsync(json);

                    response = $"Send to Slack for following. text : {payload.text}";
                }

                log.Info($"=====Debug Message=====");
                log.Info($"Subject: {eventGridEvent.Subject}");
                log.Info($"Time: {eventGridEvent.EventTime}");
                log.Info($"Event data: {eventGridEvent.Data.ToString()}");
            }

            return(req.CreateResponse(HttpStatusCode.OK, response));
        }
 public TextWriterTraceAdapter(TraceWriter traceWriter)
     : base(CultureInfo.InvariantCulture)
 {
     _text = new StringBuilder();
     _traceWriter = traceWriter;
 }
Esempio n. 48
0
 public static void Run([TimerTrigger("0 */5 * * * *")]TimerInfo myTimer, TraceWriter log)
 {
     log.Info($"C# Timer trigger function executed at: {DateTime.Now}");
 }
Esempio n. 49
0
        public static async Task <HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "Diversity/{diversityId:guid}")] HttpRequestMessage req, TraceWriter log, string diversityId)
        {
            log.Info("C# HTTP trigger function processed a request.");

            if (!Guid.TryParse(diversityId, out var diversityGuid))
            {
                return(new HttpResponseMessage(HttpStatusCode.BadRequest)
                {
                    Content = new StringContent(JsonConvert.SerializeObject(diversityId),
                                                System.Text.Encoding.UTF8, "application/json")
                });
            }
            var service = new GetDiversityByIdHttpTriggerService();
            var values  = await service.GetDiversity(diversityGuid);

            return(new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent(JsonConvert.SerializeObject(values),
                                            System.Text.Encoding.UTF8, "application/json")
            });
        }
        internal static QueueProcessor CreateQueueProcessor(CloudQueue queue, CloudQueue poisonQueue, TraceWriter trace, IQueueConfiguration queueConfig, EventHandler poisonQueueMessageAddedHandler)
        {
            QueueProcessorFactoryContext context = new QueueProcessorFactoryContext(queue, trace, queueConfig, poisonQueue);

            QueueProcessor queueProcessor = null;
            if (HostQueueNames.IsHostQueue(queue.Name) && 
                string.Compare(queue.Uri.Host, "localhost", StringComparison.OrdinalIgnoreCase) != 0)
            {
                // We only delegate to the processor factory for application queues,
                // not our built in control queues
                // We bypass this check for local testing though
                queueProcessor = new QueueProcessor(context);
            }
            else
            {
                queueProcessor = queueConfig.QueueProcessorFactory.Create(context);
            }

            if (poisonQueueMessageAddedHandler != null)
            {
                queueProcessor.MessageAddedToPoisonQueue += poisonQueueMessageAddedHandler;
            }

            return queueProcessor;
        }
 public override void Close()
 {
     try
     {
         if (this.traceWriter != null)
         {
             this.traceWriter.Flush();
             this.traceWriter.Close();
         }
     }
     finally
     {
         this.traceWriter = null;
         base.Close();
     }
 }
Esempio n. 52
0
        public static async Task Run([TimerTrigger("0 */1 * * * *")] TimerInfo myTimer, TraceWriter log)
        {
            log.Info($"C# Timer trigger function executed at: {DateTime.Now}");

            var accountSid = "";
            var authToken  = "";

            TwilioClient.Init(accountSid, authToken);
            try
            {
                await MessageResource.CreateAsync(
                    to : new PhoneNumber(""),
                    from : new PhoneNumber(""),
                    body : "Test");

                log.Info($"Ok at: {DateTime.Now}");
            }
            catch (ApiException)
            {
                log.Info($"Exception at: {DateTime.Now}");
            }
        }
 public CustomMessagingProvider(ServiceBusConfiguration config, TraceWriter trace)
     : base(config)
 {
     _config = config;
     _trace = trace;
 }
Esempio n. 54
0
        public static async Task <HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequestMessage req, TraceWriter log)
        {
            int exportedCount = 0;

            log.Info("Finding license plate data to export");

            var databaseMethods = new DatabaseMethods(log);
            var licensePlates   = databaseMethods.GetLicensePlatesToExport();

            if (licensePlates.Any())
            {
                log.Info($"Retrieved {licensePlates.Count} license plates");
                var fileMethods = new FileMethods(log);
                var uploaded    = await fileMethods.GenerateAndSaveCsv(licensePlates);

                if (uploaded)
                {
                    await databaseMethods.MarkLicensePlatesAsExported(licensePlates);

                    exportedCount = licensePlates.Count;
                    log.Info("Finished updating the license plates");
                }
                else
                {
                    log.Info(
                        "Export file could not be uploaded. Skipping database update that marks the documents as exported.");
                }

                log.Info($"Exported {exportedCount} license plates");
            }
            else
            {
                log.Info("No license plates to export");
            }

            return(exportedCount == 0
                ? req.CreateResponse(HttpStatusCode.NoContent)
                : req.CreateResponse(HttpStatusCode.OK, $"Exported {exportedCount} license plates"));
        }
Esempio n. 55
0
 public static async Task <IActionResult> Run([HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "query/{queryName}")] HttpRequest req, TraceWriter log, string queryName)
 {
     return(await Func.Handle(queryName, req, log));
 }
        public static async Task Run([TimerTrigger("0 30 5 * * *")] TimerInfo myTimer, TraceWriter log, ExecutionContext context)
        {
            try
            {
                log.Info($"C# Timer trigger function executed at: {DateTime.Now}");
                Helpers.HelperMethods helperMethods   = new Helpers.HelperMethods(context);
                AnalyticsService      analyticService = helperMethods.GetAnalyticsService();
                bool status = await analyticService.UpdateAnalytics();
            }
            catch (Exception ex)
            {
                string message = ex.InnerException != null?ex.InnerException.ToString() : ex.Message;

                log.Info(message + " occurred in UpdateAnalyticsFunction : " + DateTime.Now);
            }
        }
    private bool EnsureWriter() {
        if (traceWriter == null) {
            if (String.IsNullOrEmpty(fileName)) 
                return false;

            // We could use Interlocked but this one time overhead is probably not a concern
            lock (m_lockObject) {
                if (traceWriter != null)
                    return true;

                // To support multiple appdomains/instances tracing to the same file,
                // we will try to open the given file for append but if we encounter 
                // IO errors, we will suffix the file name with a unique GUID value 
                // and try one more time
                string path = fileName;

                for (int i=0; i<_retryThreshold; i++) {
                    try {
                        Init();
                        traceWriter = new TraceWriter(path, _bufferSize, _retention, _maxFileSize, _maxNumberOfFiles);
                        break;
                    }
                    catch (IOException ) { 
                        // Should we do this only for ERROR_SHARING_VIOLATION?
                        //if (UnsafeNativeMethods.MakeErrorCodeFromHR(Marshal.GetHRForException(ioexc)) != InternalResources.ERROR_SHARING_VIOLATION) break;

                        string fileNameWithoutExt = Path.GetFileNameWithoutExtension(fileName);
                        string fileExt = Path.GetExtension(fileName);

                        path = fileNameWithoutExt + Guid.NewGuid().ToString() + fileExt;
                        continue;
                    }
                    catch (UnauthorizedAccessException ) { 
                        //ERROR_ACCESS_DENIED, mostly ACL issues
                        break;
                    }
                    catch (Exception ) {
                        break;
                    }
                }

                // Disable tracing to this listener. Every Write will be nop.
                // We need to think of a central way to deal with the listener
                // init errors in the future. The default should be that we eat 
                // up any errors from listener and optionally notify the user
                if (traceWriter == null) 
                    fileName = null;
            }
        }
        return traceWriter != null;
    }
Esempio n. 58
0
        public static async Task <HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequestMessage req, TraceWriter log)
        {
            log.Info("C# HTTP trigger function processed a request.");

            // Parse query parameter.
            var name = req.GetQueryNameValuePairs()
                       .FirstOrDefault(q => string.Compare(q.Key, "name", true) == 0)
                       .Value;

            log.Info("Start read json file.");

            try
            {
                // Return dummy json.
                //var file = System.IO.File.ReadAllText(@".\Models\Resource.json");
                var jsonStr =
                    "{\r\n  \"Resources\": [\r\n    {\r\n      \"id\": \"5c951c0a-3e91-436a-81ae-59ede453672c\",\r\n      \"createdDateTimeUTC\": \"2018-12-08T09:00:00.000Z\",\r\n      \"lastModifiedDateTimeUTC\": \"2018-12-08T09:00:05.000Z\",\r\n      \"title\": \"Hour of Code\",\r\n      \"subtitle\": \"Growing digitally in the garden\",\r\n      \"description\": \"The annual global 'Hour of Code' campaign and Computer Science Education Week is kicking off on in December and we want as many kids in New Zealand to get to take part as possible.\",\r\n      \"headerImageBase64Bytes\": \"\",\r\n      \"duration\": \"1 day\",\r\n      \"provider\": \"OMGTech\",\r\n      \"status\": \"draft\",\r\n      \"contentUrls\": [\r\n        \"url\",\r\n        \"url\"\r\n      ],\r\n      \"categoryTags\": {\r\n        \"resourceTypes\": [\r\n          \"people\",\r\n          \"resource\"\r\n        ],\r\n        \"languages\": [\r\n          \"TeReoMaori\",\r\n          \"English\"\r\n        ],\r\n        \"locations\": [\r\n          \"Auckland\"\r\n        ],\r\n        \"topics\": [\r\n          \"garden\",\r\n          \"robots\",\r\n          \"coding\"\r\n        ],\r\n        \"ages\": [\r\n          \"year12\",\r\n          \"year13\"\r\n        ]\r\n      },\r\n      \"qualityRatingPoints\": 150,\r\n      \"topicRatingPoints\": 45\r\n    }\r\n  ]\r\n}";
                var json = JsonConvert.DeserializeObject(jsonStr);
                return(req.CreateResponse(HttpStatusCode.OK, json));
            }
            catch (Exception e)
            {
                log.Info("{0}", e.Message);
                return(req.CreateResponse(HttpStatusCode.BadRequest, e.Message));
            }
        }
Esempio n. 59
0
 public static void Run([ServiceBusTrigger("CosmosDBAddUpdate", "mysubscription", AccessRights.Manage, Connection = "AzureServiceBusTopic")] string mySbMsg, TraceWriter log)
 {
     log.Info($"C# ServiceBus topic trigger function processed message: {mySbMsg}");
 }
Esempio n. 60
0
        private bool CheckForCircularReference(JsonWriter writer, object value, JsonProperty property, JsonContract contract, JsonContainerContract containerContract, JsonProperty containerProperty)
        {
            if (value == null || contract.ContractType == JsonContractType.Primitive || contract.ContractType == JsonContractType.String)
            {
                return(true);
            }

            ReferenceLoopHandling?referenceLoopHandling = null;

            if (property != null)
            {
                referenceLoopHandling = property.ReferenceLoopHandling;
            }

            if (referenceLoopHandling == null && containerProperty != null)
            {
                referenceLoopHandling = containerProperty.ItemReferenceLoopHandling;
            }

            if (referenceLoopHandling == null && containerContract != null)
            {
                referenceLoopHandling = containerContract.ItemReferenceLoopHandling;
            }

            bool exists = (Serializer._equalityComparer != null)
                ? _serializeStack.Contains(value, Serializer._equalityComparer)
                : _serializeStack.Contains(value);

            if (exists)
            {
                string message = "Self referencing loop detected";
                if (property != null)
                {
                    message += " for property '{0}'".FormatWith(CultureInfo.InvariantCulture, property.PropertyName);
                }
                message += " with type '{0}'.".FormatWith(CultureInfo.InvariantCulture, value.GetType());

                switch (referenceLoopHandling.GetValueOrDefault(Serializer._referenceLoopHandling))
                {
                case ReferenceLoopHandling.Error:
                    throw JsonSerializationException.Create(null, writer.ContainerPath, message, null);

                case ReferenceLoopHandling.Ignore:
                    if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose)
                    {
                        TraceWriter.Trace(TraceLevel.Verbose, JsonPosition.FormatMessage(null, writer.Path, message + ". Skipping serializing self referenced value."), null);
                    }

                    return(false);

                case ReferenceLoopHandling.Serialize:
                    if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose)
                    {
                        TraceWriter.Trace(TraceLevel.Verbose, JsonPosition.FormatMessage(null, writer.Path, message + ". Serializing self referenced value."), null);
                    }

                    return(true);
                }
            }

            return(true);
        }