コード例 #1
0
        // private string entityName;
        #endregion Private Fields

        #region Public Constructor stuff
        public MockDataGenCtl()
        {
            InitializeComponent();

            ai = new AppInsights(aiEndpoint, aiKey, Assembly.GetExecutingAssembly());
            ai.WriteEvent("Control Loaded");
        }
コード例 #2
0
        public static async Task Main(string[] args)
        {
            // Read the configuration file
            IConfiguration configuration = new ConfigurationBuilder()
                                           .SetBasePath(Directory.GetCurrentDirectory()) // Directory where the json files are located
                                           .AddJsonFile(APPSETTINGS_FILENAME, optional: false, reloadOnChange: true)
                                           .Build();

            // Create an HttpClient that doesn't validate the server certificate
            HttpClientHandler customHttpClientHandler = new HttpClientHandler
            {
                ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => { return(true); }
            };

            TelemetryConfiguration telemetryConfig = AppInsights.GetTelemetryConfiguration(configuration);

            using (HttpClient _httpClient = new HttpClient(customHttpClientHandler))
            {
                // Abstraction representing the home automation system
                _hub = new Hubitat(configuration, _httpClient, AutomationFactory.ServiceProvider);

                // Class to manage long-running tasks
                _taskManager = new AutomationTaskManager(configuration);

                // Bind a method to handle the events raised
                // by the Hubitat device
                _hub.AutomationEvent += Hub_AutomationEvent;
                var hubTask = _hub.StartAutomationEventWatcher();

                // Wait forever, this is a daemon process
                await hubTask;
            }
        }
コード例 #3
0
        public async void Execute(object parameter)
        {
            if (IsBusy)
            {
                return;
            }
            if (!OverrideEnabled)
            {
                return;
            }

            IsBusy           = true;
            _origOverride    = OverrideEnabled;
            _origLabel       = CurrentLabel;
            CurrentLabel     = $"Running “{_origLabel}”…";
            OverrideEnabled  = false;
            LastExecuteStart = DateTime.Now;

            AppInsights.Post(_origLabel);

            LastExecutedOK = await SafeRun(parameter);

            ConcludeExecute();
            CommandManager.InvalidateRequerySuggested();
        }
コード例 #4
0
        public FetchXmlBuilder()
        {
            InitializeComponent();

            // Tips to handle all errors from
            // https://stackoverflow.com/questions/5762526/how-can-i-make-something-that-catches-all-unhandled-exceptions-in-a-winforms-a
            // Add the event handler for handling non-UI thread exceptions to the event.
            //AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(Error_UnhandledException);

            ai = new AppInsights(aiEndpoint, aiKey, Assembly.GetExecutingAssembly(), "FetchXML Builder");
            var theme = new VS2015LightTheme();

            dockContainer.Theme = theme;
            dockContainer.Theme.Skin.DockPaneStripSkin.TextFont = Font;
            //dockContainer.DockBackColor = SystemColors.Window;
            MetadataExtensions.attributeProperties = MetadataExtensions.attributeProperties.Union(new string[] {
                "DisplayName",
                "AttributeType",
                "IsValidForRead",
                "AttributeOf",
                "IsManaged",
                "IsCustomizable",
                "IsCustomAttribute",
                "IsValidForAdvancedFind",
                "IsPrimaryId",
                "IsPrimaryName",
                "OptionSet",
                "SchemaName",
                "Targets",
                "IsLogical",
                "EntityLogicalName"
            }).ToArray();
            LoadSetting();
        }
コード例 #5
0
        private void HandleWindowClosing(Window win, bool hideOnWindowClose)
        {
            win.Closing += async(s, e) =>
            {
                e.Cancel = true;
                if (hideOnWindowClose)
                {
                    win.Hide();
                    AppInsights.Post($"Hiding “{CaptionPrefix}” instead of closing it");
                    AppInsights.Flush();
                }
                else
                {
                    AppInsights.Post($"Closing “{CaptionPrefix}”");
                    await ExitCmd.RunAsync();
                }
            };

            win.IsVisibleChanged += (s, e) =>
            {
                if (win.Visibility == Visibility.Visible)
                {
                    _onWindowShown.Raise();
                }
                else
                {
                    _onWindowHidden.Raise();
                }
            };
        }
コード例 #6
0
 public void GameOver(GameOverReason gameOverReason)
 {
     GameOverMenu.GameOverReason = gameOverReason;
     GameOverMenu.Score          = Player.Score;
     AppInsights.GameOver(gameOverReason);
     ChangeState(GameState.GameOver);
 }
        public DataExportValidationCheckerPluginControl()
        {
            InitializeComponent();

            ai = new AppInsights(aiEndpoint, aiKey, Assembly.GetExecutingAssembly());
            ai.WriteEvent("Loaded");
        }
コード例 #8
0
        public static void Shutdown(bool errorShutdown = false)
        {
            if (Configuration.SendTelemetry && Telemetry.UseApplicationInsights && AppInsights != null)
            {
                var t = AppRunTelemetry.Telemetry;
                t.Properties.Add("usage", Configuration.ApplicationUpdates.AccessCount.ToString());
                t.Properties.Add("registered", UnlockKey.IsRegistered().ToString());
                t.Properties.Add("version", GetVersion());
                t.Properties.Add("dotnetversion", ComputerInfo.GetDotnetVersion());
                t.Stop();

                try
                {
                    AppInsights.StopOperation(AppRunTelemetry);
                }
                catch (Exception ex)
                {
                    LogToLogfile("Failed to Stop Telemetry Client: " + ex.GetBaseException().Message);
                }
                AppInsights.Flush();
                AppInsights = null;
            }
            else
            {
                SendTelemetry("shutdown");
            }
        }
コード例 #9
0
ファイル: CAT.cs プロジェクト: rappen/CustomActionTester
 public CustomActionTester(ICATTool catinstance)
 {
     catTool = catinstance;
     ai = new AppInsights(aiEndpoint, aiKey, Assembly.GetExecutingAssembly(), catTool.Name);
     InitializeComponent();
     gridInputParams.AutoGenerateColumns = false;
     gridOutputParams.AutoGenerateColumns = false;
     FixFormForTool();
 }
コード例 #10
0
        public HomeAutomationPlatform(IConfiguration configuration)
        {
            this.DeviceMap = JsonDocument
                             .Parse(File.ReadAllText(Path.Combine(Directory.GetCurrentDirectory(), DEVICE_FILENAME)))
                             .RootElement;

            Configuration = configuration;

            TelemetryClient = AppInsights.GetTelemetryClient(configuration);
        }
コード例 #11
0
#pragma warning disable IDE0060 // Remove unused parameter
        public HomeAutomationPlatform(IConfiguration configuration)
#pragma warning restore IDE0060 // Remove unused parameter
        {
            this.DeviceMap = JObject.Parse(
                File.ReadAllText(Path.Combine(Directory.GetCurrentDirectory(), DEVICE_FILENAME)));

            Configuration = configuration;

            TelemetryClient = AppInsights.GetTelemetryClient(configuration);
        }
コード例 #12
0
        public HomeAutomationPlatform(IConfiguration configuration, IServiceProvider serviceProvider)
        {
            this.DeviceMap = JObject.Parse(
                File.ReadAllText(Path.Combine(Directory.GetCurrentDirectory(), DEVICE_FILENAME)));

            Configuration = configuration;

            TelemetryClient = AppInsights.GetTelemetryClient(configuration);

            this.serviceProvider = serviceProvider;
        }
コード例 #13
0
 private void RunOnWindowLoadRoutines()
 {
     Task.Run(async() =>
     {
         try
         {
             AppInsights.PageView(CaptionPrefix);
             OnWindowLoad();
             await OnWindowLoadAsync();
         }
         catch (Exception ex)
         {
             OnError(ex, "Window Initialize");
         }
     });
 }
コード例 #14
0
ファイル: Startup.cs プロジェクト: tofilagman/z.Controller
        public virtual void Configuration(IAppBuilder app)
        {
            if (!Config.IsCloudApp)
            {
                AppInsights.Initiate(Config.Get("APPINSIGHTS_INSTRUMENTATIONKEY").ToString());

                var fileSystem = new PhysicalFileSystem(Config.Get("Microsoft.WindowsAzure.Plugins.Diagnostics.ConnectionString").ToString());
                var options    = new FileServerOptions
                {
                    FileSystem = fileSystem,
                    EnableDirectoryBrowsing = EnableDirectoryBrowsing,
                    RequestPath             = PathString.FromUriComponent(Storage.Storage.RequestPath)
                };

                app.UseFileServer(options);
            }
        }
コード例 #15
0
ファイル: Program.cs プロジェクト: AzureMentor/puppet-1
        public static async Task Main(string[] args)
        {
            // Read the configuration file
            IConfiguration configuration = new ConfigurationBuilder()
                                           .SetBasePath(Directory.GetCurrentDirectory()) // Directory where the json files are located
                                           .AddJsonFile(APPSETTINGS_FILENAME, optional: false, reloadOnChange: true)
                                           .Build();

            // Create an HttpClient that doesn't validate the server certificate
            HttpClientHandler customHttpClientHandler = new HttpClientHandler
            {
                ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => { return(true); }
            };

            TelemetryConfiguration telemetryConfig = AppInsights.GetTelemetryConfiguration(configuration);

            using (AppInsights.InitializeDependencyTracking(telemetryConfig))
                using (AppInsights.InitializePerformanceTracking(telemetryConfig))
                    using (HttpClient _httpClient = new HttpClient(customHttpClientHandler))
                    {
                        _telemetryClient = new TelemetryClient(telemetryConfig);

                        // Abstraction representing the home automation system
                        _hub = new Hubitat(configuration, _httpClient);

                        // Start the MQTT service, if applicable.
                        MqttOptions mqttOptions = configuration.GetSection("MQTT").Get <MqttOptions>();
                        if (mqttOptions?.Enabled ?? false)
                        {
                            _mqtt = new MqttService(await MqttClientFactory.GetClient(mqttOptions), mqttOptions, _hub);
                            await _mqtt.Start();
                        }

                        // Class to manage long-running tasks
                        _taskManager = new AutomationTaskManager(configuration);

                        // Bind a method to handle the events raised
                        // by the Hubitat device
                        _hub.AutomationEvent += Hub_AutomationEvent;
                        var hubTask = _hub.StartAutomationEventWatcher();

                        // Wait forever, this is a daemon process
                        await hubTask;
                    }
        }
コード例 #16
0
ファイル: mmApp.cs プロジェクト: rjshaver/MarkdownMonster
        public static void Shutdown(bool errorShutdown = false)
        {
            if (Configuration.SendTelemetry && Telemetry.UseApplicationInsights && AppInsights != null)
            {
                var t = AppRunTelemetry.Telemetry;

                // multi-instance shutdown - ignore
                if (t.Properties.ContainsKey("usage"))
                {
                    return;
                }

                t.Properties.Add("usage", Configuration.ApplicationUpdates.AccessCount.ToString());
                t.Properties.Add("registered", UnlockKey.IsRegistered().ToString());
                t.Properties.Add("version", GetVersion());
                t.Properties.Add("dotnetversion", WindowsUtils.GetDotnetVersion());
                t.Properties.Add("culture", CultureInfo.CurrentUICulture.IetfLanguageTag);
                t.Stop();

                try
                {
                    AppInsights.StopOperation(AppRunTelemetry);
                }
                catch (Exception ex)
                {
                    LogLocal("Failed to Stop Telemetry Client: " + ex.GetBaseException().Message);
                }

                AppInsights.Flush();
                AppInsights = null;
                AppRunTelemetry.Dispose();
            }
            else
            {
                SendTelemetry("shutdown");
            }

            var tempPath = Path.GetTempPath();

            // Cleanup temp files
            File.Delete(Path.Combine(tempPath, "_MarkdownMonster_Preview.html"));
            FileUtils.DeleteTimedoutFiles(Path.Combine(tempPath, "mm_diff_*.*"), 1);
        }
コード例 #17
0
        /// <summary>
        /// Base Task
        /// </summary>
        /// <param name="action"></param>
        /// <param name="Finally"></param>
        /// <returns></returns>
        protected virtual async Task <Result> TaskResult(Func <Result, Result> action, Action Finally = null)
        {
            StackFrame callingFrame = new StackTrace().GetFrames()[1];
            MethodInfo method       = callingFrame.GetMethod() as MethodInfo;

            return(await Task.Run(() =>
            {
                var r = new Result();

                r.MethodName = method.Name;


                if (Error != null)
                {
                    r.Status = 1;
                    r.ErrorMsg = Error.Message;
                }
                else
                {
                    try
                    {
                        r.Status = 0;
                        r = action(r);
                        r.ResultSet = r.ResultSet.ToJson().CompressUriEncoded(); //for justice
                    }
                    catch (Exception ex)
                    {
                        r.Status = 1;
                        r.ErrorMsg = ex.Message;
                        AppInsights.LogEx(ex);
                        // var msg = Sql.ExecScalar("SELECT dbo.fGetMessage(@Msg)", ex.Message).ToString();
                        //r.ErrorMsg = msg != "" ? msg : ex.Message;
                        // throw ex; //angular intercept this error so its okay to throw
                        // iis wont show the true error, so we might need to intercept it
                    }
                }
                finally
                {
                    Finally?.Invoke();
                }
                return r;
            }));
コード例 #18
0
        private async Task ExitApp(bool relaunchAfter)
        {
            try
            {
                OnWindowClose();
                await OnWindowCloseAsync();

                _scope?.Dispose();
                AppInsights.Flush();
                if (relaunchAfter)
                {
                    CurrentExe.RelaunchApp();
                }
                else
                {
                    CurrentExe.Shutdown();
                }
            }
            catch { }
        }
コード例 #19
0
        /// <summary>
        /// Execute Async Override
        /// </summary>
        /// <param name="controllerContext"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public override Task <HttpResponseMessage> ExecuteAsync(HttpControllerContext controllerContext,
                                                                CancellationToken cancellationToken)
        {
            try
            {
                Q              = QueryString(controllerContext);
                Ctx            = HttpContext.Current;
                RequestContext = controllerContext.RequestContext;

                return(base.ExecuteAsync(controllerContext, cancellationToken));  //;
            }
            catch (Exception ex)
            {
                AppInsights.LogEx(ex);
                throw new Exception("Method Not Found, Add Attribute [httpPost] or [HttpGet] to your Method", ex);
            }
            finally
            {
                // Q?.Dispose();
                GC.Collect();
            }
        }
コード例 #20
0
 public AutomationTaskManager(IConfiguration configuration)
 {
     _telemetryClient = AppInsights.GetTelemetryClient(configuration);
     _taskCountMetric = _telemetryClient.GetMetric("AutomationTaskCount");
     _taskList        = new HashSet <AutomationTaskTokenType>();
 }
コード例 #21
0
        /// <summary>
        /// Request Parameter Wrapper
        /// </summary>
        /// <param name="cntx"></param>
        /// <returns></returns>
        protected virtual Pair QueryString(HttpControllerContext cntx)
        {
            var h = new Pair(StringComparer.OrdinalIgnoreCase);

            try
            {
                if (cntx.Request.Content.IsMimeMultipartContent() || cntx.Request.Content.Headers.ContentLength > 1e+8)
                {
                    return(h);
                }

                string g = default(string);

                if (cntx.Request.Method == HttpMethod.Post)
                {
                    using (var ms = new MemoryStream())
                    {
                        cntx.Request.Content.CopyToAsync(ms).Wait();

                        ms.Seek(0, SeekOrigin.Begin);

                        using (var sr = new StreamReader(ms))
                        {
                            g = sr.ReadToEnd();
                        }
                    }
                }
                else if (cntx.Request.Method == HttpMethod.Get)
                {
                    g = cntx.Request.RequestUri.Query;
                }

                if (g == "")
                {
                    return(h);
                }
                string[] exc = { "_", "callback" };

                if (cntx.Request.Method == HttpMethod.Get)
                {
                    foreach (var j in g.Split('&').Select(i => i.Split('=')))
                    {
                        j[0] = j[0].TrimStart('?');
                        if (exc.Contains(j[0]) || j.Length == 1)
                        {
                            continue;
                        }
                        h.Add(j[0], HttpUtility.UrlDecode(j[1], Encoding.UTF8));
                    }
                }
                else
                {
                    g = g.CompressFromUriEncoded();
                    g.ToObject <Pair>().CopyTo(h);
                }

                return(h);
            }
            catch (OutOfMemoryException ex)
            {
                AppInsights.LogEx(ex);
                throw ex;
            }
            catch (Exception ex)
            {
                AppInsights.LogEx(ex);
                throw ex;
            }
        }
コード例 #22
0
 protected virtual void OnError(Exception ex, string taskDescription = null)
 {
     AppInsights.Post(ex, taskDescription);
     Alert.Show(ex, taskDescription);
     //await Loggly.Post(ex);
 }
コード例 #23
0
 /// <summary>
 /// Initializes a new instance of class <see cref="AccessChecker"/>
 /// </summary>
 public AccessChecker()
 {
     InitializeComponent();
     ai = new AppInsights(aiEndpoint, aiKey, Assembly.GetExecutingAssembly());
     ai.WriteEvent("Control Loaded");
 }
コード例 #24
0
 //protected virtual void OnError(Exception error)
 //    => MessageBox.Show(error.Info(false, true),
 //        $"Error on task :  “{_origLabel}”",
 //        MessageBoxButton.OK, MessageBoxImage.Error);
 protected virtual void OnError(Exception error)
 {
     AppInsights.Post(error, _origLabel);
     Alert.Show(error, _origLabel);
 }