Beispiel #1
0
 private void TaskScheduler_UnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs e)
 {
     var client = new Microsoft.ApplicationInsights.TelemetryClient();
     client.TrackException(e.Exception);
     _logger.Error(e.Exception);
     e.SetObserved();
 }
        /// <summary>
        /// Initializes the singleton application object.  This is the first line of authored code
        /// executed, and as such is the logical equivalent of main() or WinMain().
        /// </summary>
        public App()
        {
            TelemetryClient = new Microsoft.ApplicationInsights.TelemetryClient();

            this.InitializeComponent();
            this.Suspending += OnSuspending;
        }
        //
        // GET: /ShoppingCart/

        public ActionResult Index()
        {
            var telemetryClient = new Microsoft.ApplicationInsights.TelemetryClient();

            var cart = ShoppingCart.GetCart(storeDB, this.HttpContext);

            // Set up our ViewModel
            var viewModel = new ShoppingCartViewModel
            {
                CartItems = cart.GetCartItems(),
                CartTotal = cart.GetTotal()
            };

            foreach (var item in viewModel.CartItems)
            {
                Trace.Write("Cart item: " + item.AlbumId);
            }
            
            //Sample Trace Telemetry
            TraceTelemetry sampleTelemetry = new TraceTelemetry();
            sampleTelemetry.Message = "Normal response- Database";
            sampleTelemetry.SeverityLevel = SeverityLevel.Information;
            telemetryClient.TrackTrace(sampleTelemetry);

            // Return the view
            return View(viewModel);
        }
        public ActionResult Login(LoginModel model, string returnUrl)
        {
            var telemetryClient = new Microsoft.ApplicationInsights.TelemetryClient();
            TraceTelemetry traceSample = new TraceTelemetry();

            if (ModelState.IsValid && WebSecurity.Login(
                model.UserName, model.Password, persistCookie: model.RememberMe))
            {
                // Migrate the user's shopping cart
                MigrateShoppingCart(model.UserName);
                
                //Sample Trace telemetry
                traceSample.Message = "Login succesfull";
                traceSample.SeverityLevel = SeverityLevel.Information;
                telemetryClient.TrackTrace(traceSample);

                return RedirectToLocal(returnUrl);
            }

            //Sample Trace telemetry
            traceSample.Message = "Login failed";
            traceSample.SeverityLevel = SeverityLevel.Information;
            telemetryClient.TrackTrace(traceSample);

            // If we got this far, something failed, redisplay form
            ModelState.AddModelError("", "The user name or password provided is incorrect.");
            return View(model);
        }
 private void updateWith10DayData(string response)
 {
     var json = JObject.Parse(response);
     JToken forecastToken;
     if (!json.TryGetValue("forecast", out forecastToken))
     {
         var tc = new Microsoft.ApplicationInsights.TelemetryClient();
         var properties = new Dictionary<String, string> { { "response", response } };
         tc.TrackEvent($"Unexpected response in {nameof(updateWith10DayData)}", properties);
         return;
     }
     var allDaily = forecastToken["simpleforecast"]["forecastday"].Children();
     var dailyForecast = new List<WeatherDetailsModel>();
     foreach (var daily in allDaily.Take(10))
     {
         var rawEpoch = Int64.Parse(daily["date"]["epoch"].ToString());
         var epoch = DateTimeOffset.FromUnixTimeSeconds(rawEpoch);
         var forecast = new WeatherDetailsModel()
         {
             Conditions = daily["conditions"].ToString(),
             TemperatureHigh = Int32.Parse(daily["high"]["celsius"].ToString()),
             TemperatureLow = Int32.Parse(daily["low"]["celsius"].ToString()),
             Rainfall = Int32.Parse(daily["qpf_allday"]["mm"].ToString()),
             Snowfall = Int32.Parse(daily["snow_allday"]["cm"].ToString()),
             Time = epoch.DateTime,
         };
         dailyForecast.Add(forecast);
     }
     DailyForecast = dailyForecast;
 }
Beispiel #6
0
 private void App_UnhandledException(object sender, Windows.UI.Xaml.UnhandledExceptionEventArgs e)
 {
     var client = new Microsoft.ApplicationInsights.TelemetryClient();
     client.TrackException(e.Exception);
     _logger.Error(e.Exception);
     e.Handled = true;
 }
        /// <summary>
        /// Initializes the singleton application object.  This is the first line of authored code
        /// executed, and as such is the logical equivalent of main() or WinMain().
        /// </summary>
        public App()
        {
            TelemetryClient = new Microsoft.ApplicationInsights.TelemetryClient();

            this.InitializeComponent();
            BaseViewModel.NavigationService = new NavigationHelper();
            this.Suspending += OnSuspending;
        }
Beispiel #8
0
        /// <summary>
        /// Initializes the singleton application object.  This is the first line of authored code
        /// executed, and as such is the logical equivalent of main() or WinMain().
        /// </summary>
        public App()
        {
            TelemetryClient = new Microsoft.ApplicationInsights.TelemetryClient();
            MapService.ServiceToken = "Your token here";

            this.InitializeComponent();
            this.Suspending += OnSuspending;
        }
Beispiel #9
0
        /// <summary>
        /// Initializes the singleton application object.  This is the first line of authored code
        /// executed, and as such is the logical equivalent of main() or WinMain().
        /// </summary>
        public App()
        {
            TelemetryClient = new Microsoft.ApplicationInsights.TelemetryClient();
            TelemetryClient.Context.Properties.Add("Alias", "");

            this.InitializeComponent();
            this.Suspending += OnSuspending;
        }
Beispiel #10
0
        /// <summary>
        /// Initializes the singleton application object.  This is the first line of authored code
        /// executed, and as such is the logical equivalent of main() or WinMain().
        /// </summary>
        public App()
        {
            TelemetryClient = new Microsoft.ApplicationInsights.TelemetryClient();

            this.InitializeComponent();
            this.Suspending += OnSuspending;
            this.UnhandledException += this.App_UnhandledException;
        }
Beispiel #11
0
        /// <summary>
        /// Initializes the singleton application object.  This is the first line of authored code
        /// executed, and as such is the logical equivalent of main() or WinMain().
        /// </summary>
        public App()
        {
            TelemetryClient = new Microsoft.ApplicationInsights.TelemetryClient();
            ParseObject.RegisterSubclass<Toilet>();
            ParseClient.Initialize("xSi6lznksibSQE8LXWhEYLNghkZNVA3yCPATXPJ2", "wdorZjmU5SRAiHElPRBilEBzICmcAoepvpEoTrO7");

            this.InitializeComponent();
            this.Suspending += OnSuspending;
        }
Beispiel #12
0
        /// <summary>
        /// Initializes the singleton application object.  This is the first line of authored code
        /// executed, and as such is the logical equivalent of main() or WinMain().
        /// </summary>
        public App()
        {
            TelemetryClient = new Microsoft.ApplicationInsights.TelemetryClient();

            this.InitializeComponent();
            this.Suspending += OnSuspending;

            if (ApiInformation.IsTypePresent("Windows.Phone.UI.Input.HardwareButtons"))
                HardwareButtons.BackPressed += HardwareButtons_BackPressed;
        }
        public App()
        {
            TelemetryClient = new Microsoft.ApplicationInsights.TelemetryClient();

            this.InitializeComponent();
            this.Suspending += OnSuspending;

            Router.Current.Scheme = "solidnavigation://";
            Router.Current.AddRoute("tasks/{taskid}/comments", typeof(TaskDetailsPage), typeof(CommentTarget));
            Router.Current.AddRoute("tasks/{taskid}", typeof(TaskDetailsPage), typeof(TaskDetailsTarget));
            Router.Current.AddRoute("lists/{listid}", typeof(TasksPage), typeof(TaskListTarget));
            Router.Current.AddRoute("", typeof(ListsPage), typeof(HomeTarget));
        }
        //
        // GET: /Home/

        public async Task<ActionResult> Index()
        {
            // Get most popular albums
            var albums = await GetTopSellingAlbums(6);
            //var albums = GetTopSellingAlbums(6);

            // Trigger some good old ADO code 
            var albumCount = GetTotalAlbumns(); 
            Trace.Write(string.Format("Total number of Albums = {0} and Albums with 'The' = {1}", albumCount.Item1, albumCount.Item2));

            var telemetryClient = new Microsoft.ApplicationInsights.TelemetryClient();

            //Sample Trace telemetry
            TraceTelemetry traceSample = new TraceTelemetry();
            traceSample.Message = "Slow response - database";
            traceSample.SeverityLevel = SeverityLevel.Warning;
            telemetryClient.TrackTrace(traceSample);

            //Sample event telemetry
            var properties = new Dictionary<string, string> { { "Property 1",string.Format("Album Count {0}" ,albumCount.Item1) } };
            var measurements = new Dictionary<string, double> { { "Sample Meassurement", albumCount.Item1 } };
            telemetryClient.TrackEvent("Top Selling Albums", properties, measurements);

            //Sample exception telemetry
            try
            {
                albumCount = null;
                int count=albumCount.Item1;
            }
            catch (Exception ex)
            {
                telemetryClient.TrackException(ex, properties, measurements);
            }

            //Obtains the ip address from the request
            var request = new RequestTelemetry();
            request.Url = HttpContext.Request.Url;
            request.Duration = System.TimeSpan.FromMilliseconds(100);
            request.Success = false;
            request.Name = "TEST REQUEST " + request.Name;
            telemetryClient.TrackRequest(request);

            return View(albums);
        }
Beispiel #15
0
 internal void GlobalKeyDown(CoreWindow sender, KeyEventArgs args)
 {
     try
     {
         if (args.VirtualKey == Windows.System.VirtualKey.Right)
         {
             NavigateNext();
         }
         else if (args.VirtualKey == Windows.System.VirtualKey.Left)
         {
             NavigatePrevious();
         }
     }
     catch (Exception ex)
     {
         var tc = new Microsoft.ApplicationInsights.TelemetryClient();
         var properties = new Dictionary<String, string> { { "Module", "Navigation" } };
         tc.TrackException(ex, properties);
         System.Diagnostics.Debugger.Break();
     }
 }
Beispiel #16
0
        private static void CurrentDomain_FirstChanceException(object sender, System.Runtime.ExceptionServices.FirstChanceExceptionEventArgs e)
        {
            try
            {
                if (_preventOverflow)
                {
                    return;
                }
                _preventOverflow = true;
                string msg = e.Exception.ToString() + Environment.NewLine + Environment.NewLine;

                if (!e.Exception.Message.Contains("Non-static method requires a target."))
                {
                    Console.WriteLine(msg);
                    //System.Diagnostics.Trace.TraceError(msg, e.Exception);
                    System.Diagnostics.Debug.WriteLine(msg);
                    var tc = new Microsoft.ApplicationInsights.TelemetryClient();
                    ExceptionTelemetry et = new ExceptionTelemetry(e.Exception);
                    tc.TrackException(et);
                }
                else
                {
                    Console.WriteLine(msg);
                }
            }
            catch (Exception ex)
            {
                string msg = ex.ToString() + Environment.NewLine + Environment.NewLine;
                Console.WriteLine(msg);
                System.Diagnostics.Debug.WriteLine(msg);
                //AggregateException ae = new AggregateException(new List<Exception>() { e.Exception, ex });
                //throw ae;
            }
            finally
            {
                _preventOverflow = false;
            }
        }
Beispiel #17
0
 internal void GlobalKeyDown(CoreWindow sender, KeyEventArgs args)
 {
     try
     {
         if (args.VirtualKey == Windows.System.VirtualKey.Right)
         {
             NavigateNext();
         }
         else if (args.VirtualKey == Windows.System.VirtualKey.Left)
         {
             NavigatePrevious();
         }
     }
     catch (Exception ex)
     {
         var tc         = new Microsoft.ApplicationInsights.TelemetryClient();
         var properties = new Dictionary <String, string> {
             { "Module", "Navigation" }
         };
         tc.TrackException(ex, properties);
         System.Diagnostics.Debugger.Break();
     }
 }
Beispiel #18
0
 public async Task SearchDataAsync(string searchTerm)
 {
     if (!string.IsNullOrEmpty(searchTerm))
     {
         try
         {
             HasLoadDataErrors = false;
             IsBusy            = true;
             LastUpdated       = await LoadDataInternal(true, i => i.ContainsString(searchTerm));
         }
         catch (Exception ex)
         {
             Microsoft.ApplicationInsights.TelemetryClient telemetry = new Microsoft.ApplicationInsights.TelemetryClient();
             telemetry.TrackException(ex);
             HasLoadDataErrors = true;
             Debug.WriteLine(ex.ToString());
         }
         finally
         {
             IsBusy = false;
         }
     }
 }
Beispiel #19
0
 public async Task FilterDataAsync(List <string> itemsId)
 {
     if (itemsId != null && itemsId.Any())
     {
         try
         {
             HasLoadDataErrors = false;
             IsBusy            = true;
             LastUpdated       = await LoadDataInternal(true, i => itemsId.Contains(i.Id));
         }
         catch (Exception ex)
         {
             Microsoft.ApplicationInsights.TelemetryClient telemetry = new Microsoft.ApplicationInsights.TelemetryClient();
             telemetry.TrackException(ex);
             HasLoadDataErrors = true;
             Debug.WriteLine(ex.ToString());
         }
         finally
         {
             IsBusy = false;
         }
     }
 }
        /// <summary>
        /// Records the system exceptions and does nothing for the rest.
        /// </summary>
        public void OnException(ExceptionContext actionExecutedContext)
        {
            var exception = actionExecutedContext.Exception;

            switch (exception)
            {
            case ActionException actionException:
            case AccessDeniedException accessDeniedException:
            case IntegrityViolationException integrityConstraintExceptinon:
            case UserException userException:
            case InvalidOperationException invalidOperationException:
                // These exceptions are intended to communicate errors to the user,
                // thus do not record them as system errors.
                break;

            default:
                var telemetry = new Microsoft.ApplicationInsights.TelemetryClient();

                telemetry.TrackException(exception);

                break;
            }
        }
Beispiel #21
0
        public void SharedTestOpenActiveLead()
        {
            using (var xrmBrowser = new Api.Browser(TestSettings.Options))
            {
                xrmBrowser.LoginPage.Login(_xrmUri, _username, _password);
                xrmBrowser.GuidedHelp.CloseGuidedHelp();

                xrmBrowser.Navigation.OpenSubArea("Sales", "Leads");

                xrmBrowser.Grid.SwitchView("All Leads");

                xrmBrowser.Grid.OpenRecord(0);


                var telemetry = new Microsoft.ApplicationInsights.TelemetryClient();
                telemetry.InstrumentationKey = _azureKey;


                foreach (ICommandResult result in xrmBrowser.CommandResults)
                {
                    var properties = new Dictionary <string, string>();
                    var metrics    = new Dictionary <string, double>();

                    properties.Add("StartTime", result.StartTime.Value.ToLongDateString());
                    properties.Add("EndTime", result.StopTime.Value.ToLongDateString());

                    metrics.Add("ThinkTime", result.ThinkTime);
                    metrics.Add("TransitionTime", result.TransitionTime);
                    metrics.Add("ExecutionTime", result.ExecutionTime);
                    metrics.Add("ExecutionAttempts", result.ExecutionAttempts);

                    telemetry.TrackEvent(result.CommandName, properties, metrics);
                }

                telemetry.Flush();
            }
        }
        public async Task <ActionResult <bool> > Logout()
        {
            try
            {
                //var user = _userManager.FindByEmailAsync(email).Result;
                //var user = await _signInManager.UserManager.GetUserAsync(User);
                await _signInManager.SignOutAsync();

                return(Ok(true));
            }
            catch (Exception e)
            {
                try
                {
                    var user = await _signInManager.UserManager.GetUserAsync(User);

                    var tc = new Microsoft.ApplicationInsights.TelemetryClient();
                    ExceptionTelemetry et = new ExceptionTelemetry(e);
                    et.Properties.Add("user", User.Identity.Name);
                    tc.TrackException(et);
                }
                catch (Exception ex)
                {
                    if (_logger != null)
                    {
                        _logger.LogError(ex.ToString());
                    }
                }
                if (e is HubException)
                {
                    return(BadRequest(e));
                }
                HubException hue = new HubException(e.Message, e);
                return(BadRequest(hue));
            }
        }
        public string GetSasToken(string deviceId)
        {

            string ns = WebApiApplication.ehWebConsumerGroup.eventHubNamespace;
            string hubName = WebApiApplication.ehWebConsumerGroup.eventHubPath;
            string keyName = WebApiApplication.ehWebConsumerGroup.SendKeyName;
            string key = WebApiApplication.ehWebConsumerGroup.SendKeyValue;

            int TTLmins = 60 * 24;

            if (deviceId == "")
                return "";


             TimeSpan ttl = new TimeSpan(0, TTLmins, 0);

            var sas = CreateForHttpSender(keyName, key, ns, hubName, deviceId, ttl);

            // add app insight
            var tc = new Microsoft.ApplicationInsights.TelemetryClient();
            tc.TrackEvent("SasToken dispensed");
            
            return sas;
        }
        public ActionResult Index(int?teamId, string teamName = "")
        {
            var tc = new Microsoft.ApplicationInsights.TelemetryClient();

            tc.TrackEvent("Issue list view");

            try
            {
                var teamIdToUse = _userSessionHelper.TeamId;


                var bugListVm = new IssueListVM();

                if (teamId != null)
                {
                    teamIdToUse = teamId.Value;
                    // a publicily visible Issue board
                    var team = this._teamManager.GetTeam(teamId.Value);
                    if (team != null && team.IsPublic)
                    {
                        bugListVm.TeamID         = team.Id;
                        bugListVm.IsPublicTeam   = true;
                        bugListVm.ProjectsExist  = true;
                        bugListVm.IsReadonlyView = true;
                    }
                    else
                    {
                        teamIdToUse = 0;
                    }
                }



                bugListVm.TeamID = teamIdToUse;



                if (!bugListVm.IsReadonlyView)
                {
                    var projectExists = _projectManager.DoesProjectsExist();

                    if (!projectExists)
                    {
                        return(RedirectToAction("Index", "Projects"));
                    }
                }
                bugListVm.ProjectsExist = true;



                bool defaultProjectExist = _projectManager.GetDefaultProjectForCurrentTeam() != null;
                if (!defaultProjectExist)
                {
                    var tt = new Dictionary <string, string>
                    {
                        {
                            "warning",
                            "Hey!, You need to set a default project for the current team. Go to your profile settings and set a project as default project."
                        }
                    };
                    TempData["AlertMessages"] = tt;
                }



                return(View("Index", bugListVm));
            }
            catch (Exception ex)
            {
                tc.TrackException(ex);
                return(View("Error"));
            }
        }
 /// <summary>
 /// Initializes the singleton application object.  This is the first line of authored code
 /// executed, and as such is the logical equivalent of main() or WinMain().
 /// </summary>
 public App()
 {
     TelemetryClient = new Microsoft.ApplicationInsights.TelemetryClient();
     this.InitializeComponent();
     this.Suspending += OnSuspending;
 }
        public async Task <FileResult> GetDownloadFile([FromRoute] Guid sinnerid)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    throw new ArgumentException("ModelState is invalid!");
                }

                var sinnerseq = await(from a in _context.SINners
                                      .Include(a => a.MyGroup)
                                      .Include(a => a.SINnerMetaData.Visibility.UserRights)
                                      where a.Id == sinnerid select a).ToListAsync();
                if (!sinnerseq.Any())
                {
                    throw new ArgumentException("Could not find id " + sinnerid.ToString());
                }
                ApplicationUser user = null;
                if (!String.IsNullOrEmpty(User?.Identity?.Name))
                {
                    user = await _signInManager.UserManager.FindByNameAsync(User.Identity.Name);
                }
                var chummerFile = sinnerseq.FirstOrDefault();
                if (chummerFile == null)
                {
                    throw new ArgumentException("Could not find id " + sinnerid.ToString());
                }
                if (String.IsNullOrEmpty(chummerFile.DownloadUrl))
                {
                    string msg = "Chummer " + chummerFile.Id + " does not have a valid DownloadUrl!";
                    throw new ArgumentException(msg);
                }
                bool oktoDownload = false;
                if ((!oktoDownload) && (chummerFile.SINnerMetaData.Visibility.IsPublic == true))
                {
                    oktoDownload = true;
                }
                if ((!oktoDownload) && (chummerFile.MyGroup != null && chummerFile.MyGroup.IsPublic == true))
                {
                    oktoDownload = true;
                }
                if ((!oktoDownload) && (user != null && chummerFile.SINnerMetaData.Visibility.UserRights.Any(a => a.EMail.ToLowerInvariant() == user.Email.ToLowerInvariant())))
                {
                    oktoDownload = true;
                }
                if (!oktoDownload)
                {
                    throw new ArgumentException("User " + user?.UserName + " or public is not allowed to download " + sinnerid.ToString());
                }
                //string path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.InternetCache), chummerFile.Id.ToString() + ".chum5z");
                var stream = await MyHttpClient.GetStreamAsync(new Uri(chummerFile.DownloadUrl));

                string downloadname = chummerFile.Id.ToString() + ".chum5z";

                if (user == null)
                {
                    throw new NoUserRightException("User not found!");
                }
                try
                {
                    var tc = new Microsoft.ApplicationInsights.TelemetryClient();
                    Microsoft.ApplicationInsights.DataContracts.EventTelemetry telemetry = new Microsoft.ApplicationInsights.DataContracts.EventTelemetry("GetDownloadFile");
                    telemetry.Properties.Add("User", user?.Email);
                    telemetry.Properties.Add("SINnerId", sinnerid.ToString());
                    telemetry.Metrics.Add("FileSize", stream.Length);
                    tc.TrackEvent(telemetry);
                }
                catch (Exception e)
                {
                    _logger.LogError(e.ToString());
                }
                return(new FileStreamResult(stream, new Microsoft.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream"))
                {
                    FileDownloadName = downloadname
                });
            }
            catch (Exception e)
            {
                if (e is HubException)
                {
                    throw;
                }
                HubException hue = new HubException("Exception in GetDownloadFile: " + e.Message, e);
                throw hue;
            }
        }
Beispiel #27
0
        private async Task <IActionResult> PostSINnerInternal(UploadInfoObject uploadInfo)
        {
            _logger.LogTrace("Post SINnerInternalt: " + uploadInfo + ".");
            ApplicationUser user   = null;
            SINner          sinner = null;

            try
            {
                if (!ModelState.IsValid)
                {
                    var errors = ModelState.Select(x => x.Value.Errors)
                                 .Where(y => y.Count > 0)
                                 .ToList();
                    string msg = "ModelState is invalid: ";
                    foreach (var err in errors)
                    {
                        foreach (var singleerr in err)
                        {
                            msg += Environment.NewLine + "\t" + singleerr.ToString();
                        }
                    }
                    return(BadRequest(new HubException(msg)));
                }
                if (uploadInfo.UploadDateTime == null)
                {
                    uploadInfo.UploadDateTime = DateTime.Now;
                }
                if (uploadInfo.Client != null)
                {
                    if (!UploadClientExists(uploadInfo.Client.Id))
                    {
                        _context.UploadClients.Add(uploadInfo.Client);
                    }
                    else
                    {
                        _context.UploadClients.Attach(uploadInfo.Client);
                        _context.Entry(uploadInfo.Client).State = EntityState.Modified;
                        _context.Entry(uploadInfo.Client).CurrentValues.SetValues(uploadInfo.Client);
                    }
                }
                var returncode = HttpStatusCode.OK;
                user = await _signInManager.UserManager.FindByNameAsync(User.Identity.Name);

                foreach (var tempsinner in uploadInfo.SINners)
                {
                    sinner = tempsinner;
                    if (sinner.Id.ToString() == "string")
                    {
                        sinner.Id = Guid.Empty;
                    }

                    if (String.IsNullOrEmpty(sinner.MyExtendedAttributes.JsonSummary))
                    {
                        return(BadRequest("sinner " + sinner.Id + ": JsonSummary == null"));
                    }

                    if (sinner.SINnerMetaData.Visibility.UserRights.Any() == false)
                    {
                        return(BadRequest("Sinner  " + sinner.Id + ": Visibility contains no entries!"));
                    }

                    if (sinner.LastChange == null)
                    {
                        return(BadRequest("Sinner  " + sinner.Id + ": LastChange not set!"));
                    }
                    if ((sinner.SINnerMetaData.Visibility.Id == null) ||
                        (sinner.SINnerMetaData.Visibility.Id == Guid.Empty))
                    {
                        sinner.SINnerMetaData.Visibility.Id = Guid.NewGuid();
                    }
                    var oldsinner = (from a in _context.SINners.Include(a => a.SINnerMetaData.Visibility.UserRights)
                                     .Include(b => b.MyGroup)
                                     where a.Id == sinner.Id
                                     select a).FirstOrDefault();
                    if (oldsinner != null)
                    {
                        var  olduserrights = oldsinner.SINnerMetaData.Visibility.UserRights.ToList();
                        bool canedit       = false;
                        foreach (var oldright in olduserrights)
                        {
                            if ((oldright.EMail.ToLowerInvariant() == user.Email.ToLowerInvariant() &&
                                 (oldright.CanEdit == true)))
                            {
                                canedit = true;
                                break;
                            }
                        }
                        if (!canedit)
                        {
                            string msg = "SINner " + sinner.Id + " is not editable for user " + user.Email + ".";
                            throw new NoUserRightException(msg);
                        }
                        _context.UserRights.RemoveRange(olduserrights);
                        bool userfound = false;
                        foreach (var ur in sinner.SINnerMetaData.Visibility.UserRights)
                        {
                            if (ur.EMail.ToLowerInvariant() == user.Email.ToLowerInvariant())
                            {
                                ur.CanEdit = true;
                                userfound  = true;
                            }
                            ur.Id       = Guid.NewGuid();
                            ur.SINnerId = sinner.Id;
                            _context.UserRights.Add(ur);
                        }
                        if (!userfound)
                        {
                            SINerUserRight ownUser = new SINerUserRight();
                            ownUser.Id       = Guid.NewGuid();
                            ownUser.SINnerId = sinner.Id;
                            ownUser.CanEdit  = true;
                            ownUser.EMail    = user.Email;
                            sinner.SINnerMetaData.Visibility.UserRights.Add(ownUser);
                            _context.UserRights.Add(ownUser);
                        }
                    }
                    else
                    {
                        var ownuserfound = false;
                        var list         = sinner.SINnerMetaData.Visibility.UserRights.ToList();
                        foreach (var ur in list)
                        {
                            ur.SINnerId = sinner.Id;
                            if (ur.EMail.ToLowerInvariant() == "*****@*****.**".ToLowerInvariant())
                            {
                                sinner.SINnerMetaData.Visibility.UserRights.Remove(ur);
                            }
                            if (ur.EMail.ToLowerInvariant() == user.Email.ToLowerInvariant())
                            {
                                ownuserfound = true;
                            }
                        }
                        if (!ownuserfound)
                        {
                            SINerUserRight ownright = new SINerUserRight();
                            ownright.CanEdit  = true;
                            ownright.EMail    = user.Email;
                            ownright.SINnerId = sinner.Id;
                            ownright.Id       = Guid.NewGuid();
                            sinner.SINnerMetaData.Visibility.UserRights.Add(ownright);
                        }
                    }

                    foreach (var tag in sinner.SINnerMetaData.Tags)
                    {
                        tag.SetSinnerIdRecursive(sinner.Id);
                    }

                    sinner.UploadClientId = uploadInfo.Client.Id;
                    SINner dbsinner = await CheckIfUpdateSINnerFile(sinner.Id.Value, user);

                    SINnerGroup oldgroup = null;
                    if (dbsinner != null)
                    {
                        oldgroup = dbsinner.MyGroup;
                        _context.SINners.Attach(dbsinner);
                        if (String.IsNullOrEmpty(sinner.GoogleDriveFileId))
                        {
                            sinner.GoogleDriveFileId = dbsinner.GoogleDriveFileId;
                        }
                        if (String.IsNullOrEmpty(sinner.DownloadUrl))
                        {
                            sinner.DownloadUrl = dbsinner.DownloadUrl;
                        }

                        _context.UserRights.RemoveRange(dbsinner.SINnerMetaData.Visibility.UserRights);
                        _context.SINnerVisibility.Remove(dbsinner.SINnerMetaData.Visibility);
                        var alltags = await dbsinner.GetTagsForSinnerFlat(_context);

                        _context.Tags.RemoveRange(alltags);
                        _context.SINnerMetaData.Remove(dbsinner.SINnerMetaData);
                        _context.SINners.Remove(dbsinner);
                        dbsinner.SINnerMetaData.Visibility.UserRights.Clear();
                        dbsinner.SINnerMetaData.Visibility = null;
                        dbsinner.SINnerMetaData.Tags       = null;
                        dbsinner.SINnerMetaData            = null;

                        await _context.SaveChangesAsync();

                        await _context.SINners.AddAsync(sinner);

                        string msg = "Sinner " + sinner.Id + " updated: " + _context.Entry(dbsinner).State.ToString();
                        msg += Environment.NewLine + Environment.NewLine + "LastChange: " + dbsinner.LastChange;
                        _logger.LogError(msg);
                        List <Tag> taglist = sinner.SINnerMetaData.Tags;
                        UpdateEntityEntries(taglist);
                    }
                    else
                    {
                        returncode     = HttpStatusCode.Created;
                        sinner.MyGroup = null;
                        _context.SINners.Add(sinner);
                    }

                    try
                    {
                        await _context.SaveChangesAsync();

                        if (oldgroup != null)
                        {
                            var roles = await _userManager.GetRolesAsync(user);

                            await SINnerGroupController.PutSiNerInGroupInternal(oldgroup.Id.Value, sinner.Id.Value, user, _context,
                                                                                _logger, oldgroup.PasswordHash, roles);
                        }
                    }
                    catch (DbUpdateConcurrencyException ex)
                    {
                        foreach (var entry in ex.Entries)
                        {
                            if (entry.Entity is SINner)
                            {
                                Utils.DbUpdateConcurrencyExceptionHandler(entry, _logger);
                            }
                            else if (entry.Entity is Tag)
                            {
                                Utils.DbUpdateConcurrencyExceptionHandler(entry, _logger);
                            }
                            else
                            {
                                throw new NotSupportedException(
                                          "Don't know how to handle concurrency conflicts for "
                                          + entry.Metadata.Name);
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        try
                        {
                            var tc = new Microsoft.ApplicationInsights.TelemetryClient();
                            Microsoft.ApplicationInsights.DataContracts.ExceptionTelemetry telemetry = new Microsoft.ApplicationInsights.DataContracts.ExceptionTelemetry(e);
                            telemetry.Properties.Add("User", user?.Email);
                            telemetry.Properties.Add("SINnerId", sinner?.Id?.ToString());
                            tc.TrackException(telemetry);
                        }
                        catch (Exception ex)
                        {
                            _logger.LogError(ex.ToString());
                        }
                        if (e is HubException)
                        {
                            return(Conflict(e));
                        }

                        HubException hue = new HubException("Exception in PostSINnerFile: " + e.ToString(), e);
                        //var msg = new System.Net.Http.HttpResponseMessage(HttpStatusCode.Conflict) { ReasonPhrase = e.Message };
                        return(Conflict(hue));
                    }
                }

                List <Guid> myids = (from a in uploadInfo.SINners select a.Id.Value).ToList();
                switch (returncode)
                {
                case HttpStatusCode.OK:
                    return(Accepted("PostSIN", myids));

                case HttpStatusCode.Created:
                    return(CreatedAtAction("PostSIN", myids));

                default:
                    break;
                }
                return(BadRequest());
            }
            catch (Exception e)
            {
                try
                {
                    var tc = new Microsoft.ApplicationInsights.TelemetryClient();
                    Microsoft.ApplicationInsights.DataContracts.ExceptionTelemetry telemetry = new Microsoft.ApplicationInsights.DataContracts.ExceptionTelemetry(e);
                    telemetry.Properties.Add("User", user?.Email);
                    telemetry.Properties.Add("SINnerId", sinner?.Id?.ToString());
                    tc.TrackException(telemetry);
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex.ToString());
                }
                if (e is HubException)
                {
                    return(BadRequest(e));
                }

                HubException hue = new HubException("Exception in PostSINnerFile: " + e.Message, e);
                return(BadRequest(hue));
            }
        }
        public async Task <ActionResult <ResultGroupGetSearchGroups> > GetSinnerAsAdmin()
        {
            ResultAccountGetSinnersByAuthorization res;

            SINSearchGroupResult ret = new SINSearchGroupResult();

            res = new ResultAccountGetSinnersByAuthorization(ret);
            SINnerGroup       sg  = new SINnerGroup();
            SINnerSearchGroup ssg = new SINnerSearchGroup(sg)
            {
                MyMembers = new List <SINnerSearchGroupMember>()
            };

            try
            {
                var user = await _signInManager.UserManager.GetUserAsync(User);

                if (user == null)
                {
                    var e = new AuthenticationException("User is not authenticated.");
                    res = new ResultAccountGetSinnersByAuthorization(e)
                    {
                        ErrorText = "Unauthorized"
                    };
                    return(BadRequest(res));
                }
                var roles = await _userManager.GetRolesAsync(user);

                ret.Roles     = roles.ToList();
                ssg.Groupname = user.Email;
                ssg.Id        = Guid.Empty;
                //get all from visibility
                List <SINner> mySinners = await _context.SINners.Include(a => a.MyGroup)
                                          .Include(a => a.SINnerMetaData.Visibility.UserRights)
                                          .OrderByDescending(a => a.UploadDateTime)
                                          .Take(200)
                                          .ToListAsync();

                foreach (var sin in mySinners)
                {
                    SINnerSearchGroupMember ssgm = new SINnerSearchGroupMember
                    {
                        MySINner = sin,
                        Username = user.UserName
                    };
                    ssg.MyMembers.Add(ssgm);
                    if (sin.MyGroup != null)
                    {
                        SINnerSearchGroup ssgFromSIN;
                        if (ssg.MySINSearchGroups.Any(a => a.Id == sin.MyGroup.Id))
                        {
                            ssgFromSIN = ssg.MySINSearchGroups.FirstOrDefault(a => a.Id == sin.MyGroup.Id);
                        }
                        else
                        {
                            ssgFromSIN = new SINnerSearchGroup(sin.MyGroup);
                            ssg.MySINSearchGroups.Add(ssgFromSIN);
                        }
                        //add all members of his group
                        var members = await sin.MyGroup.GetGroupMembers(_context, false);

                        foreach (var member in members)
                        {
                            member.MyGroup          = sin.MyGroup;
                            member.MyGroup.MyGroups = new List <SINnerGroup>();
                            SINnerSearchGroupMember sinssgGroupMember = new SINnerSearchGroupMember
                            {
                                MySINner = member
                            };
                            ssgFromSIN.MyMembers.Add(sinssgGroupMember);
                        }
                        sin.MyGroup.PasswordHash = "";
                        sin.MyGroup.MyGroups     = new List <SINnerGroup>();
                    }
                }

                ret.SINGroups.Add(ssg);
                res = new ResultAccountGetSinnersByAuthorization(ret);
                return(Ok(res));
            }
            catch (Exception e)
            {
                try
                {
                    var user = await _signInManager.UserManager.GetUserAsync(User);

                    var tc = new Microsoft.ApplicationInsights.TelemetryClient();
                    ExceptionTelemetry et = new ExceptionTelemetry(e);
                    et.Properties.Add("user", User.Identity.Name);
                    tc.TrackException(et);
                }
                catch (Exception ex)
                {
                    if (_logger != null)
                    {
                        _logger.LogError(ex.ToString());
                    }
                }
                res = new ResultAccountGetSinnersByAuthorization(e);
                return(BadRequest(res));
            }
        }
        public static bool Execute(string[] args, Stream outputStream)
        {
            var sessionId = Guid.NewGuid().ToString();
            var machineId = getMachineId();
            // Create AppInsights telemetry client to track app usage
            TelemetryClient = new Microsoft.ApplicationInsights.TelemetryClient();
            TelemetryClient.Context.User.Id = machineId;
            TelemetryClient.Context.Session.Id = sessionId;

            Assembly assembly = Assembly.GetAssembly(typeof(DeploymentWorker));
            FileVersionInfo fileVersionInfo = FileVersionInfo.GetVersionInfo(assembly.Location);
            var version = fileVersionInfo.ProductVersion;
            TelemetryClient.TrackEvent("DeployStart", new Dictionary<string, string>()
            {
                { "AppVersion", version }
            });

            var worker = new DeploymentWorker(outputStream);
            if (!worker.argsHandler.HandleCommandLineArgs(args))
            {
                TelemetryClient.TrackEvent("DeployFailed_IncorrectArgs", new Dictionary<string, string>() { });
                TelemetryClient.Flush();
                return false;
            }

            worker.OutputMessage(Resource.DeploymentWorker_Starting);
            var taskResult = worker.CreateAndDeployApp();
            if (taskResult)
            {
                TelemetryClient.TrackEvent("DeploySucceeded", new Dictionary<string, string>() { });
            }
            else
            {
                TelemetryClient.TrackEvent("DeployFailed", new Dictionary<string, string>() { });
            }

            TelemetryClient.Flush();
            return taskResult;
        }
Beispiel #30
0
        /// <summary>
        /// Invoked when the application is launched normally by the end user.  Other entry points
        /// will be used such as when the application is launched to open a specific file.
        /// </summary>
        /// <param name="e">Details about the launch request and process.</param>
        protected override async void OnLaunched(LaunchActivatedEventArgs e)
        {
#if DEBUG
            if (System.Diagnostics.Debugger.IsAttached)
            {
                this.DebugSettings.EnableFrameRateCounter = true;
            }
#endif
            var tc = new Microsoft.ApplicationInsights.TelemetryClient();

            var navigation = new NavigationController(launchScreenCallback);
            CoreWindow.GetForCurrentThread().KeyDown += navigation.GlobalKeyDown;

            await SettingsController.LoadSettings();

            try
            {
                var clockModel = new ClockModel();
                Task.Run(() => clockModel.Update());
                (Resources["clockViewModel"] as ClockViewModel).Initialize(clockModel);
                TimerController.RegisterModel(clockModel);
                navigation.RegisterView(typeof(ClockView));
                clockModel.NightFallDelegate += TimeOfDayChangedHandler;
            }
            catch (Exception ex)
            {
                var properties = new Dictionary <String, string> {
                    { "Module", "Clock" }
                };
                tc.TrackException(ex, properties);
                System.Diagnostics.Debugger.Break();
            }

            try
            {
                var weatherModel = new WeatherModel_wunderground();
                Task.Run(() => weatherModel.Update());
                TimerController.RegisterModel(weatherModel);
                (Resources["weatherThisWeekViewModel"] as WeatherThisWeekViewModel).Initialize(weatherModel);
                (Resources["weatherTodayViewModel"] as WeatherTodayViewModel).Initialize(weatherModel);
                navigation.RegisterView(typeof(WeatherThisWeekView));
                navigation.RegisterView(typeof(WeatherTodayView));
            }
            catch (Exception ex)
            {
                var properties = new Dictionary <String, string> {
                    { "Module", "Weather" }
                };
                tc.TrackException(ex, properties);
                System.Diagnostics.Debugger.Break();
            }

            try
            {
                var transitModel = new TransitModel_translink();
                Task.Run(() => transitModel.Update());
                TimerController.RegisterModel(transitModel);
                (Resources["transitViewModel"] as TransitViewModel).Initialize(transitModel);
                TimerController.RegisterViewModel((Resources["transitViewModel"] as TransitViewModel));
                navigation.RegisterView(typeof(TransitView));
            }
            catch (Exception ex)
            {
                var properties = new Dictionary <String, string> {
                    { "Module", "Transit" }
                };
                tc.TrackException(ex, properties);
                System.Diagnostics.Debugger.Break();
            }

            Frame rootFrame = Window.Current.Content as Frame;

            // Do not repeat app initialization when the Window already has content,
            // just ensure that the window is active
            if (rootFrame == null)
            {
                // Create a Frame to act as the navigation context and navigate to the first page
                rootFrame = new ThemeAwareFrame(ElementTheme.Light);

                rootFrame.NavigationFailed += OnNavigationFailed;

                if (e.PreviousExecutionState == ApplicationExecutionState.Terminated)
                {
                    //TODO: Load state from previously suspended application
                }

                // Place the frame in the current Window
                Window.Current.Content = rootFrame;
            }

            if (rootFrame.Content == null)
            {
                // When the navigation stack isn't restored navigate to the first page,
                // configuring the new page by passing required information as a navigation
                // parameter
                rootFrame.Navigate(typeof(ClockView), e.Arguments);
            }
            // Ensure the current window is active
            Window.Current.Activate();
            tc.TrackEvent("Smart Mirror has loaded.");

            setupAutoScroll(navigation);
        }
Beispiel #31
0
        public async Task <ResponseModel> LoadSystemDataAsync(bool force = false)
        {
            _systemLogs.Clear();
            _systemLogs.Add($"LoadSystemDataAsync (force = {force})");

            var status = _dataTypes[DataManagerDataType.System].WaitOne(0);

            if (status && !force)
            {
                return(ResponseModel.Error(ResponseCode.Ok));
            }
            _dataTypes[DataManagerDataType.System].Reset();

            DateTime started = DateTime.UtcNow;

            _systemLogs.Add($"Fetching System Settings");

            var data = await GetSystem();

            if (data != null)
            {
                _metadata = data.Metadata;
                data.EmailTemplates.ForEach(c => _emailTemplates.AddOrUpdate(c.TemplateId, c, (k, v) => c));
                data.SMSTemplates.ForEach(c => _smsTemplates.AddOrUpdate(c.TemplateId, c, (k, v) => c));
            }

            _dataTypes[DataManagerDataType.System].Set();

            if (_metadata != null)
            {
                double dur = DateTime.UtcNow.Subtract(started).TotalSeconds;

                #region Printout
                _systemLogs.Add($"{Metadata.Config.Count()} Config Loaded");
                _systemLogs.Add($"{Metadata.Events.Count()} Events Loaded");
                _systemLogs.Add($"{Metadata.Languages.Count()} Languages Loaded");
                _systemLogs.Add($"{Metadata.ResponseCodes.Count()} ResponseCodes Loaded");
                _systemLogs.Add($"{Metadata.UserStatus.Count()} UserStatus Loaded");

                if (this.AppSettings.Environment != EnvironmentId.Development)
                {
                    Microsoft.ApplicationInsights.TelemetryClient client = new Microsoft.ApplicationInsights.TelemetryClient();
                    try
                    {
                        _systemLogs.Add("DataManager.LoadSystemDataAsync -> Startup Duration (metadata): " + dur.ToString());
                        client.TrackEvent("DataManager.LoadSystemDataAsync", new Dictionary <string, string> {
                            { "duration-metadata", dur.ToString() }
                        }, new Dictionary <string, double> {
                            { "duration-metadata", dur }
                        });
                    }
                    catch { }
                }
                #endregion

                _systemLogs.ForEach(c => Console.WriteLine(c));

                return(ResponseModel.Success());
            }

            return(ResponseModel.Error(ResponseCode.NoData, "Metadata not loaded from cache. World ends now"));
        }
        internal static async Task <ActionResult <SINner> > PutSiNerInGroupInternal(Guid GroupId, Guid SinnerId, ApplicationUser user, ApplicationDbContext context, ILogger logger, string pwhash, IList <string> userroles)
        {
            try
            {
                if (GroupId == Guid.Empty)
                {
                    throw new ArgumentNullException(nameof(GroupId), "GroupId may not be empty.");
                }

                if (SinnerId == Guid.Empty)
                {
                    throw new ArgumentNullException(nameof(SinnerId), "SinnerId may not be empty.");
                }

                var groupset = await(from a in context.SINnerGroups.Include(a => a.MySettings)
                                     where a.Id == GroupId
                                     select a).ToListAsync();
                if (!groupset.Any())
                {
                    throw new ArgumentException("GroupId not found", nameof(GroupId));
                }

                var group = groupset.FirstOrDefault();

                if ((!String.IsNullOrEmpty(group.PasswordHash)) &&
                    (group.PasswordHash != pwhash))
                {
                    throw new NoUserRightException("PW is wrong!");
                }

                if (!String.IsNullOrEmpty(group.MyAdminIdentityRole))
                {
                    if (!userroles.Contains(group.MyAdminIdentityRole))
                    {
                        throw new NoUserRightException("User " + user.UserName + " has not the role " + group.MyAdminIdentityRole + ".");
                    }
                }

                var sinnerseq = await(from a in context.SINners
                                      .Include(a => a.MyGroup)
                                      .Include(a => a.SINnerMetaData)
                                      .Include(a => a.SINnerMetaData.Visibility)
                                      .Include(a => a.SINnerMetaData.Visibility.UserRights)
                                      where a.Id == SinnerId
                                      select a).ToListAsync();
                SINner sin = null;
                if (!sinnerseq.Any())
                {
                    throw new ArgumentException("SinnerId not found", nameof(SinnerId));
                }
                else
                {
                    sin = sinnerseq.FirstOrDefault();
                    if (sin != null)
                    {
                        sin.MyGroup = group;
                    }
                }

                await context.SaveChangesAsync();

                return(sin);
            }
            catch (Exception e)
            {
                try
                {
                    var tc = new Microsoft.ApplicationInsights.TelemetryClient();
                    Microsoft.ApplicationInsights.DataContracts.ExceptionTelemetry telemetry =
                        new Microsoft.ApplicationInsights.DataContracts.ExceptionTelemetry(e);
                    telemetry.Properties.Add("User", user?.Email);
                    telemetry.Properties.Add("GroupId", GroupId.ToString());
                    tc.TrackException(telemetry);
                }
                catch (Exception ex)
                {
                    logger?.LogError(ex.ToString());
                }

                HubException hue = new HubException("Exception in PutSiNerInGroupInternal: " + e.Message, e);
                throw hue;
            }
        }
        public async Task <IActionResult> PostGroup([FromBody] SINnerGroup mygroup, Guid SinnerId)
        {
            _logger.LogTrace("Post SINnerGroupInternal: " + mygroup?.Groupname + " (" + SinnerId + ").");
            ApplicationUser user = null;

            //SINner sinner = null;
            try
            {
                if (!ModelState.IsValid)
                {
                    var errors = ModelState.Select(x => x.Value.Errors)
                                 .Where(y => y.Count > 0)
                                 .ToList();
                    string msg = "ModelState is invalid: ";
                    foreach (var err in errors)
                    {
                        foreach (var singleerr in err)
                        {
                            msg += Environment.NewLine + "\t" + singleerr.ToString();
                        }
                    }
                    return(BadRequest(new HubException(msg)));
                }

                if (mygroup == null)
                {
                    return(BadRequest("group == null."));
                }
                if (String.IsNullOrEmpty(mygroup?.Groupname))
                {
                    return(BadRequest("Groupname may not be empty."));
                }

                if (SinnerId == Guid.Empty)
                {
                    return(BadRequest("SinnerId may not be empty."));
                }

                SINnerGroup parentGroup = null;

                var returncode = HttpStatusCode.OK;
                user = await _signInManager.UserManager.FindByNameAsync(User.Identity.Name);

                var sinnerseq = await(from a in _context.SINners.Include(b => b.SINnerMetaData.Visibility.UserRights) where a.Id == SinnerId select a).ToListAsync();
                if (!sinnerseq.Any())
                {
                    string msg = "Please upload SINner prior to adding him/her to a group!";
                    return(BadRequest(new HubException(msg)));
                }
                foreach (var sinner in sinnerseq)
                {
                    if (sinner.SINnerMetaData.Visibility.UserRights.Any() == false)
                    {
                        return(BadRequest("Sinner  " + sinner.Id + ": Visibility contains no entries!"));
                    }

                    if (sinner.LastChange == null)
                    {
                        return(BadRequest("Sinner  " + sinner.Id + ": LastChange not set!"));
                    }
                    if (sinner.SINnerMetaData.Visibility.Id == null)
                    {
                        sinner.SINnerMetaData.Visibility.Id = Guid.NewGuid();
                    }
                    bool found = false;
                    foreach (var sinur in sinner.SINnerMetaData.Visibility.UserRights)
                    {
                        if (sinur.EMail.ToLowerInvariant() == user.Email.ToLowerInvariant())
                        {
                            if (sinur.CanEdit == true)
                            {
                                found = true;
                            }
                            break;
                        }
                    }
                    if (!found)
                    {
                        string msg = "Sinner " + sinner.Id + " is not editable for user " + user.UserName + ".";
                        return(BadRequest(new HubException(msg)));
                    }

                    var groupfoundseq = await(from a in _context.SINnerGroups where a.Groupname == mygroup.Groupname select a).ToListAsync();
                    if (groupfoundseq.Any())
                    {
                        string msg = "A group with the name " + mygroup.Groupname + " already exists!";
                        return(BadRequest(new HubException(msg)));
                    }

                    if (mygroup.Id == null || mygroup.Id == Guid.Empty)
                    {
                        mygroup.Id = Guid.NewGuid();
                    }
                    mygroup.MyParentGroup = parentGroup;
                    parentGroup?.MyGroups.Add(mygroup);
                    _context.SINnerGroups.Add(mygroup);
                    returncode = HttpStatusCode.Created;

                    try
                    {
                        await _context.SaveChangesAsync();
                    }

                    catch (DbUpdateConcurrencyException ex)
                    {
                        foreach (var entry in ex.Entries)
                        {
                            if (entry.Entity is SINner)
                            {
                                Utils.DbUpdateConcurrencyExceptionHandler(entry, _logger);
                            }
                            else if (entry.Entity is Tag)
                            {
                                Utils.DbUpdateConcurrencyExceptionHandler(entry, _logger);
                            }
                            else if (entry.Entity is SINnerGroup)
                            {
                                Utils.DbUpdateConcurrencyExceptionHandler(entry, _logger);
                            }
                            else
                            {
                                throw new NotSupportedException(
                                          "Don't know how to handle concurrency conflicts for "
                                          + entry.Metadata.Name);
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        try
                        {
                            var tc = new Microsoft.ApplicationInsights.TelemetryClient();
                            Microsoft.ApplicationInsights.DataContracts.ExceptionTelemetry telemetry = new Microsoft.ApplicationInsights.DataContracts.ExceptionTelemetry(e);
                            telemetry.Properties.Add("User", user?.Email);
                            telemetry.Properties.Add("SINnerId", sinner?.Id?.ToString());


                            tc.TrackException(telemetry);
                        }
                        catch (Exception ex)
                        {
                            _logger.LogError(ex.ToString());
                        }
                        HubException hue = new HubException("Exception in PostGroup: " + e.ToString(), e);
                        var          msg = new System.Net.Http.HttpResponseMessage(HttpStatusCode.Conflict)
                        {
                            ReasonPhrase = e.Message
                        };
                        return(Conflict(hue));
                    }
                }
                switch (returncode)
                {
                case HttpStatusCode.OK:
                    return(Accepted("PostGroup", mygroup.Id));

                case HttpStatusCode.Created:
                    return(CreatedAtAction("PostGroup", mygroup.Id));

                default:
                    break;
                }
                return(BadRequest());
            }
            catch (Exception e)
            {
                try
                {
                    var tc = new Microsoft.ApplicationInsights.TelemetryClient();
                    Microsoft.ApplicationInsights.DataContracts.ExceptionTelemetry telemetry = new Microsoft.ApplicationInsights.DataContracts.ExceptionTelemetry(e);
                    telemetry.Properties.Add("User", user?.Email);
                    telemetry.Properties.Add("Groupname", mygroup?.Groupname?.ToString());
                    tc.TrackException(telemetry);
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex.ToString());
                }
                HubException hue = new HubException("Exception in PostGroup: " + e.Message, e);
                return(BadRequest(hue));
            }
        }
 private void updateWithHourlyData(string response)
 {
     var json = JObject.Parse(response);
     JToken allHourly;
     if (!json.TryGetValue("hourly_forecast", out allHourly))
     {
         var tc = new Microsoft.ApplicationInsights.TelemetryClient();
         var properties = new Dictionary<String, string> { { "response", response } };
         tc.TrackEvent($"Unexpected response in {nameof(updateWithHourlyData)}", properties);
         return;
     }
     var hourlyForecast = new List<WeatherDetailsModel>();
     foreach (var hourly in allHourly.Take(24))
     {
         var rawEpoch = Int64.Parse(hourly["FCTTIME"]["epoch"].ToString());
         var epoch = DateTimeOffset.FromUnixTimeSeconds(rawEpoch);
         var forecast = new WeatherDetailsModel()
         {
             Conditions = hourly["condition"].ToString(),
             Temperature = Int32.Parse(hourly["temp"]["metric"].ToString()),
             Rainfall = Int32.Parse(hourly["qpf"]["metric"].ToString()),
             Snowfall = Int32.Parse(hourly["snow"]["metric"].ToString()),
             Time = epoch.DateTime,
         };
         hourlyForecast.Add(forecast);
     }
     HourlyForecast = hourlyForecast;
 }
        public async Task <ActionResult <SINner> > PutGroupInGroup(Guid GroupId, string groupname, Guid?parentGroupId, string adminIdentityRole, bool isPublicVisible)
        {
            _logger.LogTrace("PutGroupInGroup: " + GroupId + " (" + parentGroupId + ", " + adminIdentityRole + ").");
            ApplicationUser user = null;

            try
            {
                user = await _signInManager.UserManager.GetUserAsync(User);

                if (!ModelState.IsValid)
                {
                    var errors = ModelState.Select(x => x.Value.Errors)
                                 .Where(y => y.Count > 0)
                                 .ToList();
                    string msg = "ModelState is invalid: ";
                    foreach (var err in errors)
                    {
                        foreach (var singleerr in err)
                        {
                            msg += Environment.NewLine + "\t" + singleerr.ToString();
                        }
                    }

                    return(BadRequest(new HubException(msg)));
                }

                SINnerGroup parentGroup = null;
                if (parentGroupId != null)
                {
                    var getParentseq = (from a in _context.SINnerGroups.Include(a => a.MyGroups)
                                        where a.Id == parentGroupId
                                        select a).Take(1);
                    if (!getParentseq.Any())
                    {
                        return(NotFound("Parentgroup with Id " + parentGroupId.ToString() + " not found."));
                    }
                    parentGroup = getParentseq.FirstOrDefault();
                }

                SINnerGroup myGroup     = null;
                var         getGroupseq = (from a in _context.SINnerGroups
                                           where a.Id == GroupId
                                           select a).Take(1);
                if (!getGroupseq.Any())
                {
                    return(NotFound("Group with Id " + parentGroupId.ToString() + " not found."));
                }
                myGroup                     = getGroupseq.FirstOrDefault();
                myGroup.Groupname           = groupname;
                myGroup.IsPublic            = isPublicVisible;
                myGroup.MyAdminIdentityRole = adminIdentityRole;
                myGroup.MyParentGroup       = parentGroup;
                if (parentGroup != null)
                {
                    if (parentGroup.MyGroups == null)
                    {
                        parentGroup.MyGroups = new List <SINnerGroup>();
                    }
                    if (!parentGroup.MyGroups.Contains(myGroup))
                    {
                        parentGroup.MyGroups.Add(myGroup);
                    }
                }

                await _context.SaveChangesAsync();

                return(Ok(myGroup));
            }
            catch (Exception e)
            {
                try
                {
                    var tc = new Microsoft.ApplicationInsights.TelemetryClient();
                    Microsoft.ApplicationInsights.DataContracts.ExceptionTelemetry telemetry = new Microsoft.ApplicationInsights.DataContracts.ExceptionTelemetry(e);
                    telemetry.Properties.Add("User", user?.Email);
                    telemetry.Properties.Add("GroupId", GroupId.ToString());
                    tc.TrackException(telemetry);
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex.ToString());
                }
                HubException hue = new HubException("Exception in PutSINerInGroup: " + e.Message, e);
                return(BadRequest(hue));
            }
        }
        public async Task <ActionResult <string> > GetAddSqlDbUser(string username, string password, string start_ip_address, string end_ip_address)
        {
            string result = "";

            try
            {
                if (String.IsNullOrEmpty(username))
                {
                    throw new ArgumentNullException(nameof(username));
                }
                if (String.IsNullOrEmpty(password))
                {
                    throw new ArgumentNullException(nameof(password));
                }

                IPAddress startaddress = null;
                if (!String.IsNullOrEmpty(start_ip_address))
                {
                    startaddress = IPAddress.Parse(start_ip_address);
                }
                IPAddress endaddress = null;
                if (!String.IsNullOrEmpty(end_ip_address))
                {
                    endaddress = IPAddress.Parse(end_ip_address);
                }
                if (String.IsNullOrEmpty(Startup.ConnectionStringToMasterSqlDb))
                {
                    throw new ArgumentNullException("Startup.ConnectionStringToMasterSqlDB");
                }


                try
                {
                    string cmd = "CREATE LOGIN " + username + " WITH password = '******';";
                    using (SqlConnection masterConnection = new SqlConnection(Startup.ConnectionStringToMasterSqlDb))
                    {
                        await masterConnection.OpenAsync();

                        using (SqlCommand dbcmd = new SqlCommand(cmd, masterConnection))
                        {
                            dbcmd.ExecuteNonQuery();
                        }
                    }
                }
                catch (SqlException e)
                {
                    result += e.Message + Environment.NewLine + Environment.NewLine;
                }
                //create the user in the master DB
                try
                {
                    string cmd = "CREATE USER " + username + " FROM LOGIN " + username + ";";
                    using (SqlConnection masterConnection = new SqlConnection(Startup.ConnectionStringToMasterSqlDb))
                    {
                        await masterConnection.OpenAsync();

                        using (SqlCommand dbcmd = new SqlCommand(cmd, masterConnection))
                        {
                            dbcmd.ExecuteNonQuery();
                        }
                    }
                }
                catch (SqlException e)
                {
                    result += e.Message + Environment.NewLine + Environment.NewLine;
                }
                //create the user in the sinner_db as well!
                try
                {
                    string cmd = "CREATE USER " + username + " FROM LOGIN " + username + ";";
                    using (SqlConnection masterConnection = new SqlConnection(Startup.ConnectionStringSinnersDb))
                    {
                        await masterConnection.OpenAsync();

                        using (SqlCommand dbcmd = new SqlCommand(cmd, masterConnection))
                        {
                            dbcmd.ExecuteNonQuery();
                        }
                    }
                }
                catch (Exception e)
                {
                    result += e.Message + Environment.NewLine + Environment.NewLine;
                }
                try
                {
                    string cmd = "ALTER ROLE dbmanager ADD MEMBER " + username + ";";
                    using (SqlConnection masterConnection = new SqlConnection(Startup.ConnectionStringSinnersDb))
                    {
                        await masterConnection.OpenAsync();

                        using (SqlCommand dbcmd = new SqlCommand(cmd, masterConnection))
                        {
                            dbcmd.ExecuteNonQuery();
                        }
                    }
                }
                catch (Exception e)
                {
                    bool worked = false;
                    try
                    {
                        string cmd = "EXEC sp_addrolemember 'db_owner', '" + username + "';";
                        using (SqlConnection masterConnection = new SqlConnection(Startup.ConnectionStringSinnersDb))
                        {
                            await masterConnection.OpenAsync();

                            using (SqlCommand dbcmd = new SqlCommand(cmd, masterConnection))
                            {
                                dbcmd.ExecuteNonQuery();
                            }
                        }
                        worked = true;
                    }
                    catch (Exception e1)
                    {
                        result += e1.ToString() + Environment.NewLine + Environment.NewLine;
                    }
                    if (worked)
                    {
                        result += "User added!" + Environment.NewLine + Environment.NewLine;
                    }
                    else
                    {
                        result += e.Message + Environment.NewLine + Environment.NewLine;
                    }
                }
                try
                {
                    string cmd = "EXEC sp_set_database_firewall_rule N'Allow " +
                                 username + "', '" + startaddress + "', '" + endaddress + "';";
                    using (SqlConnection masterConnection = new SqlConnection(Startup.ConnectionStringSinnersDb))
                    {
                        await masterConnection.OpenAsync();

                        using (SqlCommand dbcmd = new SqlCommand(cmd, masterConnection))
                        {
                            dbcmd.ExecuteNonQuery();
                        }

                        result += "Firewallrule added: " + startaddress + " - " + endaddress + Environment.NewLine +
                                  Environment.NewLine;
                    }
                }
                catch (Exception e)
                {
                    result += e.Message + Environment.NewLine + Environment.NewLine;
                }
                return(Ok(result));
            }
            catch (Exception e)
            {
                try
                {
                    var user = await _signInManager.UserManager.GetUserAsync(User);

                    var tc = new Microsoft.ApplicationInsights.TelemetryClient();
                    ExceptionTelemetry et = new ExceptionTelemetry(e);
                    et.Properties.Add("user", User.Identity.Name);
                    tc.TrackException(et);
                }
                catch (Exception ex)
                {
                    if (_logger != null)
                    {
                        _logger.LogError(ex.ToString());
                    }
                }
                result += Environment.NewLine + e;
                if (e is HubException)
                {
                    return(BadRequest(e));
                }
                HubException hue = new HubException(result, e);
                return(BadRequest(hue));
            }
        }
        private async Task <ActionResult <SINSearchGroupResult> > GetSearchGroupsInternal(string Groupname, string UsernameOrEmail, string sINnerName, string language)
        {
            ApplicationUser user = null;

            try
            {
                if (!ModelState.IsValid)
                {
                    var errors = ModelState.Select(x => x.Value.Errors)
                                 .Where(y => y.Count > 0)
                                 .ToList();
                    string msg = "ModelState is invalid: ";
                    foreach (var err in errors)
                    {
                        foreach (var singleerr in err)
                        {
                            msg += Environment.NewLine + "\t" + singleerr.ToString();
                        }
                    }

                    return(BadRequest(new HubException(msg)));
                }

                SINSearchGroupResult result = new SINSearchGroupResult();
                var groupfoundseq           = await(from a in _context.SINnerGroups
                                                    where a.Groupname.ToLowerInvariant().Contains(Groupname.ToLowerInvariant()) &&
                                                    (a.Language == language || String.IsNullOrEmpty(language))
                                                    select a.Id).ToListAsync();
                if (!groupfoundseq.Any())
                {
                    return(NotFound(Groupname));
                }

                foreach (var groupid in groupfoundseq)
                {
                    var ssg = await GetSinSearchGroupResultById(groupid);

                    result.SINGroups.Add(ssg);
                }

                if (!String.IsNullOrEmpty(UsernameOrEmail))
                {
                    List <SINner>   byUser     = new List <SINner>();
                    ApplicationUser bynameuser = await _userManager.FindByNameAsync(UsernameOrEmail);

                    if (bynameuser != null)
                    {
                        var usersinners = await SINner.GetSINnersFromUser(bynameuser, _context, true);

                        byUser.AddRange(usersinners);
                    }

                    ApplicationUser byemailuser = await _userManager.FindByEmailAsync(UsernameOrEmail);

                    if ((byemailuser != null) && (byemailuser != bynameuser))
                    {
                        var usersinners = await SINner.GetSINnersFromUser(byemailuser, _context, true);

                        byUser.AddRange(usersinners);
                    }


                    foreach (var sin in byUser)
                    {
                        if (sin.MyGroup != null)
                        {
                            SINnerSearchGroup ssg = null;
                            var foundseq          = (from a in result.SINGroups
                                                     where a.Groupname?.ToLowerInvariant() == sin.MyGroup?.Groupname.ToLowerInvariant()
                                                     select a).ToList();
                            if (foundseq.Any())
                            {
                                ssg = foundseq.FirstOrDefault();
                            }

                            if (ssg == null)
                            {
                                ssg = new SINnerSearchGroup(sin.MyGroup);
                            }
                            ssg.Id = sin.MyGroup?.Id;
                            SINnerSearchGroupMember ssgm = new SINnerSearchGroupMember();
                            ssgm.MySINner = sin;
                            if (byemailuser != null)
                            {
                                ssgm.Username = byemailuser?.UserName;
                            }
                            if (bynameuser != null)
                            {
                                ssgm.Username = bynameuser?.UserName;
                            }
                            ssg.MyMembers.Add(ssgm);
                        }
                    }
                }
                result.SINGroups = RemovePWHashRecursive(result.SINGroups);

                return(Ok(result));
            }
            catch (Exception e)
            {
                try
                {
                    var tc = new Microsoft.ApplicationInsights.TelemetryClient();
                    Microsoft.ApplicationInsights.DataContracts.ExceptionTelemetry telemetry = new Microsoft.ApplicationInsights.DataContracts.ExceptionTelemetry(e);
                    telemetry.Properties.Add("User", user?.Email);
                    telemetry.Properties.Add("Groupname", Groupname?.ToString());
                    tc.TrackException(telemetry);
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex.ToString());
                }
                if (e is HubException)
                {
                    return(BadRequest(e));
                }
                HubException hue = new HubException("Exception in GetSearchGroups: " + e.Message, e);
                return(BadRequest(hue));
            }
        }
        public async Task <ActionResult> AckGetsResponse(AckGetsReponse getsResponse)
        {
            var telemetry = new Microsoft.ApplicationInsights.TelemetryClient();

            if (getsResponse == null)
            {
                var message = "Invalid gets response object, ackgetsresponse payload shoud not be null";
                telemetry.TrackTrace(message);
                return(BadRequest(message));
            }

            if (getsResponse.Ack == null)
            {
                var message = "Invalid gets response object, getsResponse.Ack is missing in ackgetsresponse payload";
                telemetry.TrackTrace(message);
                return(BadRequest(message));
            }
            if (getsResponse.Senderappcode == null)
            {
                var message = "Invalid gets response object, getsResponse.Senderappcode is missing in ackgetsresponse";
                telemetry.TrackTrace(message);
                return(BadRequest(message));
            }
            if (getsResponse.Ack.Aes == null)
            {
                var message = "Invalid gets response object, getsResponse.Ack.Aes is missing in ackgetsresponse";
                telemetry.TrackTrace(message);
                return(BadRequest(message));
            }
            if (string.IsNullOrEmpty(getsResponse.Ack.Aes.ShipmentRefNo))
            {
                var message = "Invalid gets response object, ACK->AES->ShipmentReferenceNumber is missing in ackgetsresponse";
                telemetry.TrackTrace(message);
                return(BadRequest(message));
            }

            var item = aesDbRepository.GetItemsAsync <Model.Aes>(obj => obj.ShipmentHeader.ShipmentReferenceNumber == getsResponse.Ack.Aes.ShipmentRefNo && obj.Header.Senderappcode == getsResponse.Senderappcode)
                       .Result
                       .FirstOrDefault();

            if (item == null)
            {
                telemetry.TrackTrace($"Invalid shipment reference no ${getsResponse.Ack.Aes.ShipmentRefNo} and sender App code ${getsResponse.Senderappcode}");
                return(Ok());
            }

            if (getsResponse.Ack.Aes.Status == GetsStatus.SUCCESS)
            {
                if (item.SubmissionStatus == AesStatus.SUBMITTED)
                {
                    item.SubmissionStatus            = AesStatus.GETSAPPROVED;
                    item.SubmissionStatusDescription = getsResponse.Ack.Aes.StatusDescription;
                }
                var getsRes = getsResponse;
                item.GetsResponse = getsRes;
                await aesDbRepository.UpdateItemAsync(item.Id, item);
            }
            else if (getsResponse.Ack.Aes.Status == GetsStatus.FAIL)
            {
                if (item.SubmissionStatus == AesStatus.SUBMITTED)
                {
                    item.SubmissionStatus = AesStatus.GETSREJECTED;
                    if (getsResponse.Ack.Aes.Error != null && getsResponse.Ack.Aes.Error.Count > 0)
                    {
                        item.SubmissionStatusDescription = getsResponse.Ack.Aes.Error.First().ErrorDescription;
                    }
                }
                item.GetsResponse = getsResponse;
                await aesDbRepository.UpdateItemAsync(item.Id, item);
            }
            else if (getsResponse.Ack.Aes.Status == GetsStatus.SUBMITTED)
            {
                // ignore in AES, submition response intended for GF
                return(Ok(true));
            }
            else
            {
                return(BadRequest("Invalid status value"));
            }

            if (item.SubmissionStatus == AesStatus.SUBMITTED)
            {
                await hubContext.Clients.All.SendAsync("getscallback", getsResponse);
            }

            return(Ok(true));
        }
Beispiel #39
0
        /// <summary>
        /// Invoked when the application is launched normally by the end user.  Other entry points
        /// will be used such as when the application is launched to open a specific file.
        /// </summary>
        /// <param name="e">Details about the launch request and process.</param>
        protected override async void OnLaunched(LaunchActivatedEventArgs e)
        {

#if DEBUG
            if (System.Diagnostics.Debugger.IsAttached)
            {
                this.DebugSettings.EnableFrameRateCounter = true;
            }
#endif
            var tc = new Microsoft.ApplicationInsights.TelemetryClient();

            var navigation = new NavigationController(launchScreenCallback);
            CoreWindow.GetForCurrentThread().KeyDown += navigation.GlobalKeyDown;

            await SettingsController.LoadSettings();

            try
            {
                var clockModel = new ClockModel();
                Task.Run(() => clockModel.Update());
                (Resources["clockViewModel"] as ClockViewModel).Initialize(clockModel);
                TimerController.RegisterModel(clockModel);
                navigation.RegisterView(typeof(ClockView));
                clockModel.NightFallDelegate += TimeOfDayChangedHandler;
            }
            catch (Exception ex)
            {
                var properties = new Dictionary<String, string> { { "Module", "Clock" } };
                tc.TrackException(ex, properties);
                System.Diagnostics.Debugger.Break();
            }

            try
            { 
                var weatherModel = new WeatherModel_wunderground();
                Task.Run(() => weatherModel.Update());
                TimerController.RegisterModel(weatherModel);
                (Resources["weatherThisWeekViewModel"] as WeatherThisWeekViewModel).Initialize(weatherModel);
                (Resources["weatherTodayViewModel"] as WeatherTodayViewModel).Initialize(weatherModel);
                navigation.RegisterView(typeof(WeatherThisWeekView));
                navigation.RegisterView(typeof(WeatherTodayView));
            }
            catch (Exception ex)
            {
                var properties = new Dictionary<String, string> { { "Module", "Weather" } };
                tc.TrackException(ex, properties);
                System.Diagnostics.Debugger.Break();
            }

            try
            { 
                var transitModel = new TransitModel_translink();
                Task.Run(() => transitModel.Update());
                TimerController.RegisterModel(transitModel);
                (Resources["transitViewModel"] as TransitViewModel).Initialize(transitModel);
                TimerController.RegisterViewModel((Resources["transitViewModel"] as TransitViewModel));
                navigation.RegisterView(typeof(TransitView));
            }
            catch (Exception ex)
            {
                var properties = new Dictionary<String, string> { { "Module", "Transit" } };
                tc.TrackException(ex, properties);
                System.Diagnostics.Debugger.Break();
            }

            Frame rootFrame = Window.Current.Content as Frame;

            // Do not repeat app initialization when the Window already has content,
            // just ensure that the window is active
            if (rootFrame == null)
            {
                // Create a Frame to act as the navigation context and navigate to the first page
                rootFrame = new ThemeAwareFrame(ElementTheme.Light);

                rootFrame.NavigationFailed += OnNavigationFailed;

                if (e.PreviousExecutionState == ApplicationExecutionState.Terminated)
                {
                    //TODO: Load state from previously suspended application
                }

                // Place the frame in the current Window
                Window.Current.Content = rootFrame;
            }

            if (rootFrame.Content == null)
            {
                // When the navigation stack isn't restored navigate to the first page,
                // configuring the new page by passing required information as a navigation
                // parameter
                rootFrame.Navigate(typeof(ClockView), e.Arguments);
            }
            // Ensure the current window is active
            Window.Current.Activate();
            tc.TrackEvent("Smart Mirror has loaded.");

            setupAutoScroll(navigation);
        }
        public ActionResult Register()
        {
            var telemetryClient = new Microsoft.ApplicationInsights.TelemetryClient();

            //Sample Trace telemetry
            TraceTelemetry traceSample = new TraceTelemetry();
            traceSample.Message = "Database response - normal";
            traceSample.SeverityLevel = SeverityLevel.Information;
            telemetryClient.TrackTrace(traceSample);

            return View();
        }
Beispiel #41
0
        static void Main(string[] args)
        {
            string msg = string.Empty;

            if (args.Length > 0)
            {
                msg = String.Join(" ", args);
                Console.WriteLine(msg);

            }


            tc = new Microsoft.ApplicationInsights.TelemetryClient();
            tc.InstrumentationKey = " -b03d-431b-a82d-f3ab8b9c929d";// 
                                                                           // Set session data:
            tc.Context.User.Id = Environment.UserName;
            tc.Context.Session.Id = Guid.NewGuid().ToString();
            tc.Context.Device.OperatingSystem = Environment.OSVersion.ToString();
            tc.Context.Location.Ip = Class1.GetLocalIPAddress();

            string input = string.Empty;
            Console.WriteLine("Enter one or more lines of text (press CTRL+Z to exit):");
            Console.WriteLine();
            do
            {
                //Console.Write("   ");
                input = Console.ReadLine();
                
                if (input != null)
                {
                    //input = input.Trim();
                    
                    if (String.IsNullOrWhiteSpace(input))
                    {
                        ;//continue;
                    }

                    Console.WriteLine("\tData read was " + input);
                }


                //Console.SetIn(new StreamReader(Console.OpenStandardInput(8192))); // This will allow input >256 chars

                //while (Console.In.Peek() != -1)
                //while (true)
                //{
                //    input = Console.In.ReadLine();
                //    Console.WriteLine("\tData read was " + input);
                //    if (0 == string.Compare(input, "quit", true))
                //        break;
                //}
                {

                // Log a page view:
                tc.TrackPageView("Form1");

            Dictionary<string, string> li = new Dictionary<string, string>();
            li.Add("LEVEL", "ERROR");

            string temp = (args.Length > 0) ? args[0] : "";
            string right = string.Format("{0}-{1}", "tbd.exe", msg);
            li.Add("NAME", right);

            temp = (args.Length > 1) ? args[1] : "n/a";
            right = string.Format("{0}", input);
            li.Add("TEXT", right);

            //tc.TrackEvent("hithere", null);
            tc.TrackEvent("log", li);

            //.TelemetryClient();
            Console.WriteLine("\tDid it go.(" + input + ")");

            }   // end of read input

            } while (input != null); // end of input do!
            OnClosing();

        }
        public ActionResult Register(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                // Attempt to register the user
                try
                {
                    WebSecurity.CreateUserAndAccount(model.UserName, model.Password);
                    WebSecurity.Login(model.UserName, model.Password);

                    // Migrate the newly registered user's shopping cart
                    MigrateShoppingCart(model.UserName);

                    var telemetryClient = new Microsoft.ApplicationInsights.TelemetryClient();

                    //Sample Trace telemetry
                    TraceTelemetry traceSample = new TraceTelemetry();
                    traceSample.Message = "Registered succesfully";
                    traceSample.SeverityLevel = SeverityLevel.Information;
                    telemetryClient.TrackTrace(traceSample);

                    return RedirectToAction("Index", "Home");
                }
                catch (MembershipCreateUserException e)
                {
                    var telemetryClient = new Microsoft.ApplicationInsights.TelemetryClient();

                    //Sample Trace telemetry
                    TraceTelemetry traceSample = new TraceTelemetry();
                    traceSample.Message = "Registration failed";
                    traceSample.SeverityLevel = SeverityLevel.Error;
                    telemetryClient.TrackTrace(traceSample);

                    ModelState.AddModelError("", ErrorCodeToString(e.StatusCode));
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }
        public async Task <ActionResult <ResultAccountGetSinnersByAuthorization> > GetSINnersByAuthorization()
        {
            Stopwatch sw = new Stopwatch();

            sw.Start();
            var tc = new Microsoft.ApplicationInsights.TelemetryClient();
            ResultAccountGetSinnersByAuthorization res = null;

            SINSearchGroupResult ret = new SINSearchGroupResult();

            res = new ResultAccountGetSinnersByAuthorization(ret);
            SINnerGroup       sg  = new SINnerGroup();
            SINnerSearchGroup ssg = new SINnerSearchGroup(sg)
            {
                MyMembers = new List <SINnerSearchGroupMember>()
            };

            using (var t = new TransactionScope(TransactionScopeOption.Required,
                                                new TransactionOptions
            {
                IsolationLevel = System.Transactions.IsolationLevel.ReadUncommitted
            }, TransactionScopeAsyncFlowOption.Enabled))
            {
                try
                {
                    var user = await _signInManager.UserManager.GetUserAsync(User);

                    if (user == null)
                    {
                        var e = new AuthenticationException("User is not authenticated.");
                        res = new ResultAccountGetSinnersByAuthorization(e)
                        {
                            ErrorText = "Unauthorized"
                        };
                        return(BadRequest(res));
                    }

                    var roles = await _userManager.GetRolesAsync(user);

                    ret.Roles     = roles.ToList();
                    ssg.Groupname = user.Email;
                    ssg.Id        = Guid.Empty;
                    //get all from visibility
                    List <SINner> mySinners = await SINner.GetSINnersFromUser(user, _context, true);

                    MetricTelemetry mt = new MetricTelemetry("GetSINersByAuthorization", "SINners found",
                                                             mySinners.Count, 0, 0, 0, 0);
                    tc.TrackMetric(mt);
                    foreach (var sin in mySinners)
                    {
                        //check if that char is already added:
                        var foundseq = (from a in ssg.MyMembers where a.MySINner.Id == sin.Id select a);
                        if (foundseq.Any())
                        {
                            continue;
                        }
                        SINnerSearchGroupMember ssgm = new SINnerSearchGroupMember
                        {
                            MySINner = sin,
                            Username = user.UserName
                        };
                        if (sin.MyGroup != null)
                        {
                            SINnerSearchGroup ssgFromSIN;
                            if (ssg.MySINSearchGroups.Any(a => a.Id == sin.MyGroup.Id))
                            {
                                ssgFromSIN = ssg.MySINSearchGroups.FirstOrDefault(a => a.Id == sin.MyGroup.Id);
                            }
                            else
                            {
                                ssgFromSIN = new SINnerSearchGroup(sin.MyGroup);
                                ssg.MySINSearchGroups.Add(ssgFromSIN);
                            }
                            //add all members of his group
                            var members = await sin.MyGroup.GetGroupMembers(_context, false);

                            foreach (var member in members)
                            {
                                //if ((member.SINnerMetaData.Visibility.IsGroupVisible == true)
                                //    || (member.SINnerMetaData.Visibility.IsPublic)
                                //)
                                //{
                                member.MyGroup          = sin.MyGroup;
                                member.MyGroup.MyGroups = new List <SINnerGroup>();
                                SINnerSearchGroupMember sinssgGroupMember = new SINnerSearchGroupMember
                                {
                                    MySINner = member
                                };
                                //check if it is already added:
                                var groupseq = from a in ssgFromSIN.MyMembers where a.MySINner == member select a;
                                if (groupseq.Any())
                                {
                                    continue;
                                }
                                ssgFromSIN.MyMembers.Add(sinssgGroupMember);
                                //}
                            }
                            sin.MyGroup.PasswordHash = "";
                            sin.MyGroup.MyGroups     = new List <SINnerGroup>();
                        }
                        else
                        {
                            ssg.MyMembers.Add(ssgm);
                        }
                    }

                    ret.SINGroups.Add(ssg);
                    res = new ResultAccountGetSinnersByAuthorization(ret);

                    return(Ok(res));
                }
                catch (Exception e)
                {
                    try
                    {
                        var user = await _signInManager.UserManager.GetUserAsync(User);

                        ExceptionTelemetry et = new ExceptionTelemetry(e);
                        et.Properties.Add("user", User.Identity.Name);
                        tc.TrackException(et);
                    }
                    catch (Exception ex)
                    {
                        _logger?.LogError(ex.ToString());
                    }
                    res = new ResultAccountGetSinnersByAuthorization(e);
                    return(BadRequest(res));
                }
                finally
                {
                    Microsoft.ApplicationInsights.DataContracts.AvailabilityTelemetry telemetry =
                        new Microsoft.ApplicationInsights.DataContracts.AvailabilityTelemetry("GetSINnersByAuthorization",
                                                                                              DateTimeOffset.Now, sw.Elapsed, "Azure", res?.CallSuccess ?? false, res?.ErrorText);
                    tc.TrackAvailability(telemetry);
                }
                t.Complete();
            }
        }
Beispiel #44
0
        public async Task <FileResult> GetDownloadFile([FromRoute] Guid sinnerid)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    throw new ArgumentException("ModelState is invalid!");
                }

                var chummerFile = await _context.SINners.FindAsync(sinnerid);

                if (chummerFile == null)
                {
                    throw new ArgumentException("Could not find id " + sinnerid.ToString());
                }
                if (String.IsNullOrEmpty(chummerFile.DownloadUrl))
                {
                    string msg = "Chummer " + chummerFile.Id + " does not have a valid DownloadUrl!";
                    throw new ArgumentException(msg);
                }
                //string path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.InternetCache), chummerFile.Id.ToString() + ".chum5z");
                var stream = await MyHttpClient.GetStreamAsync(new Uri(chummerFile.DownloadUrl));

                string downloadname = chummerFile.Id.ToString() + ".chum5z";
                var    user         = await _signInManager.UserManager.FindByNameAsync(User.Identity.Name);

                if (user == null)
                {
                    throw new NoUserRightException("User not found!");
                }
                try
                {
                    var tc = new Microsoft.ApplicationInsights.TelemetryClient();
                    Microsoft.ApplicationInsights.DataContracts.EventTelemetry telemetry = new Microsoft.ApplicationInsights.DataContracts.EventTelemetry("GetDownloadFile");
                    telemetry.Properties.Add("User", user.Email);
                    telemetry.Properties.Add("SINnerId", sinnerid.ToString());
                    telemetry.Metrics.Add("FileSize", stream.Length);
                    tc.TrackEvent(telemetry);
                }
                catch (Exception e)
                {
                    _logger.LogError(e.ToString());
                }
                return(new FileStreamResult(stream, new Microsoft.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream"))
                {
                    FileDownloadName = downloadname
                });


                //using (var client = new WebClient())
                //{
                //    client.DownloadFile(new Uri(chummerFile.DownloadUrl), path);
                //}
                //if (!System.IO.File.Exists(path))
                //{
                //    string msg = "No file downloaded from " + chummerFile.DownloadUrl;
                //    return BadRequest(msg);
                //}

                ////var res = new FileStreamResult(new MemoryStream(path), "application/octet-stream");
                ////var res = new FileResult(downloadname, path, "application/octet-stream");
                ////var stream = new FileStream(path, FileMode.Open, FileAccess.Read);
                ////var reader = new StreamReader(stream, true);
                //return PhysicalFile(path, "application/octet-stream", downloadname);
                ////return File(path, "application/octet-stream");
                ////return new ObjectResult(reader.BaseStream);
            }
            catch (Exception e)
            {
                HubException hue = new HubException("Exception in GetDownloadFile: " + e.Message, e);
                throw hue;
            }
        }
        public async Task <ActionResult <string> > GetDeleteAllSINnersDb()
        {
            try
            {
                var user = await _signInManager.UserManager.GetUserAsync(User);

                if (user == null)
                {
                    return(Unauthorized());
                }
                var roles = await _userManager.GetRolesAsync(user);

                if (!roles.Contains("Administrator"))
                {
                    return(Unauthorized());
                }
                var count = await _context.SINners.CountAsync();

                using (var transaction = _context.Database.BeginTransaction())
                {
                    _context.UserRights.RemoveRange(_context.UserRights.ToList());
                    _context.SINnerComments.RemoveRange(_context.SINnerComments.ToList());
                    _context.Tags.RemoveRange(_context.Tags.ToList());
                    _context.SINnerVisibility.RemoveRange(_context.SINnerVisibility.ToList());
                    _context.SINnerMetaData.RemoveRange(_context.SINnerMetaData.ToList());
                    _context.SINners.RemoveRange(_context.SINners.ToList());
                    _context.UploadClients.RemoveRange(_context.UploadClients.ToList());

                    await _context.SaveChangesAsync();

                    // Commit transaction if all commands succeed, transaction will auto-rollback
                    // when disposed if either commands fails
                    transaction.Commit();
                }
                return(Ok("Reseted " + count + " SINners"));
            }
            catch (Exception e)
            {
                try
                {
                    var user = await _signInManager.UserManager.GetUserAsync(User);

                    var tc = new Microsoft.ApplicationInsights.TelemetryClient();
                    ExceptionTelemetry et = new ExceptionTelemetry(e);
                    et.Properties.Add("user", User.Identity.Name);
                    tc.TrackException(et);
                }
                catch (Exception ex)
                {
                    if (_logger != null)
                    {
                        _logger.LogError(ex.ToString());
                    }
                }
                if (e is HubException)
                {
                    return(BadRequest(e));
                }
                HubException hue = new HubException(e.Message, e);
                return(BadRequest(hue));
            }
        }
        public ActionResult LogOff()
        {
            WebSecurity.Logout();

            var telemetryClient = new Microsoft.ApplicationInsights.TelemetryClient();

            //Sample Trace telemetry
            TraceTelemetry traceSample = new TraceTelemetry();
            traceSample.Message = "Logged off";
            traceSample.SeverityLevel = SeverityLevel.Information;
            telemetryClient.TrackTrace(traceSample);

            return RedirectToAction("Index", "Home");
        }
Beispiel #47
0
        public async Task <IActionResult> PutSIN([FromRoute] Guid id, IFormFile uploadedFile)
        {
            ApplicationUser user     = null;
            SINner          dbsinner = null;

            try
            {
                var sin = await _context.SINners.Include(a => a.SINnerMetaData.Visibility.UserRights).FirstOrDefaultAsync(a => a.Id == id);

                if (sin == null)
                {
                    return(NotFound("Sinner with Id " + id + " not found!"));
                }
                user = await _signInManager.UserManager.FindByNameAsync(User.Identity.Name);

                dbsinner = await CheckIfUpdateSINnerFile(id, user);

                if (dbsinner == null)
                {
                    return(Conflict("CheckIfUpdateSINnerFile"));
                }
                sin.GoogleDriveFileId = dbsinner.GoogleDriveFileId;
                if (user == null)
                {
                    throw new NoUserRightException("User not found!");
                }

                sin.DownloadUrl = Startup.GDrive.StoreXmlInCloud(sin, uploadedFile);
                _context.Entry(dbsinner).CurrentValues.SetValues(sin);
                try
                {
                    var tc = new Microsoft.ApplicationInsights.TelemetryClient();
                    Microsoft.ApplicationInsights.DataContracts.EventTelemetry telemetry = new Microsoft.ApplicationInsights.DataContracts.EventTelemetry("PutStoreXmlInCloud");
                    telemetry.Properties.Add("User", user.Email);
                    telemetry.Properties.Add("SINnerId", sin.Id.ToString());
                    telemetry.Properties.Add("FileName", uploadedFile.FileName?.ToString());
                    telemetry.Metrics.Add("FileSize", uploadedFile.Length);
                    tc.TrackEvent(telemetry);
                }
                catch (Exception e)
                {
                    _logger.LogError(e.ToString());
                }
                try
                {
                    int x = await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException e)
                {
                    return(Conflict(e));
                }

                return(Ok(sin.DownloadUrl));
            }
            catch (NoUserRightException e)
            {
                return(BadRequest(e));
            }
            catch (Exception e)
            {
                try
                {
                    var tc = new Microsoft.ApplicationInsights.TelemetryClient();
                    Microsoft.ApplicationInsights.DataContracts.ExceptionTelemetry telemetry = new Microsoft.ApplicationInsights.DataContracts.ExceptionTelemetry(e);
                    telemetry.Properties.Add("User", user?.Email);
                    telemetry.Properties.Add("SINnerId", dbsinner?.Id?.ToString());
                    telemetry.Properties.Add("FileName", uploadedFile.FileName?.ToString());
                    telemetry.Metrics.Add("FileSize", uploadedFile.Length);
                    tc.TrackException(telemetry);
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex.ToString());
                }
                if (e is HubException)
                {
                    return(BadRequest(e));
                }
                HubException hue = new HubException("Exception in PutSINnerFile: " + e.Message, e);
                return(BadRequest(hue));
            }
        }
Beispiel #48
0
        private const int deleteInterval = 1;  //Value in hours

        public AppController()
        {
            TelemetryClient = new Microsoft.ApplicationInsights.TelemetryClient();
            Server          = new WebServer();
            XmlSettings     = new AppSettings();
        }
Beispiel #49
0
        static async Task RunAsFunction()
        {
            InitializeConfiguration();

            //Event hub settings
            string EventHubName             = Configuration["EventHubName"];
            string EventHubConnectionString = Configuration["ConnectionStrings:TestEventHubConnection"];

            //Storage settings
            string StorageContainerName    = Configuration["StorageContainerName"];
            string StorageConnectionString = Configuration["ConnectionStrings:AzureWebJobsStorage"];


            string globalAppInsightsKey = String.Empty;
            var    builder = new HostBuilder()
                             .UseEnvironment("Development")
                             .ConfigureWebJobs(b =>
            {
                EventProcessorHost eventProcessorHost = new EventProcessorHost(
                    EventHubName,
                    PartitionReceiver.DefaultConsumerGroupName,
                    EventHubConnectionString,
                    StorageConnectionString,
                    StorageContainerName);
                eventProcessorHost.PartitionManagerOptions = new PartitionManagerOptions()
                {
                    LeaseDuration = new TimeSpan(0, 0, 15),
                    RenewInterval = new TimeSpan(0, 0, 4)
                };

                b.AddAzureStorageCoreServices();
                b.AddEventHubs(a => a.AddEventProcessorHost(EventHubName, eventProcessorHost));
                //b.AddAzureStorageCoreServices();
                //b.AddEventHubs();
            })
                             .ConfigureAppConfiguration(b =>
            {
                b.AddJsonFile("appsettings.development.json");
            })
                             .ConfigureLogging((context, b) =>
            {
                b.SetMinimumLevel(LogLevel.Trace);

                b.AddAzureWebAppDiagnostics();
                b.AddConsole();

                string appInsightsKey = context.Configuration["APPINSIGHTS_INSTRUMENTATIONKEY"];
                globalAppInsightsKey  = appInsightsKey;
                // If this key exists in any config, use it to enable App Insights
                if (!string.IsNullOrEmpty(appInsightsKey))
                {
                    b.AddApplicationInsights(o => o.InstrumentationKey = appInsightsKey);
                }
            })
                             .UseConsoleLifetime();

            var host = builder.Build();

            using (host)
            {
                var options = host.Services.GetService <IOptions <EventHubOptions> >().Value;

                var assemblies = AppDomain.CurrentDomain.GetAssemblies();
                var config     = new Microsoft.ApplicationInsights.Extensibility.TelemetryConfiguration(globalAppInsightsKey);
                var telemetry  = new Microsoft.ApplicationInsights.TelemetryClient(config);
                telemetry.TrackTrace("WebJob host initialized and starting...");

                foreach (var item in assemblies)
                {
                    telemetry.TrackTrace($"Loaded assembly: {item.FullName}", Microsoft.ApplicationInsights.DataContracts.SeverityLevel.Information);
                }
                await host.RunAsync();

                await host.WaitForShutdownAsync();
            }
        }
Beispiel #50
0
        /// <summary>
        /// If the request is an AJAX one and the exception is of type <see cref="UserException"/>
        /// or a descendant of <see cref="AccessDeniedException"/> or of <see cref="IntegrityViolationException"/>,
        /// transform it into a <see cref="UserErrorModel"/> and return it as a JSON
        /// with an appropriate error HTTP status code.
        /// </summary>
        /// <param name="filterContext">The context containing the exception.</param>
        /// <remarks>
        /// <see cref="AccessDeniedException"/> and descendants yeild HTTP status code 403 "Forbidden".
        /// <see cref="UniqueConstraintViolationException"/> and <see cref="ReferentialConstraintViolationException"/>
        /// yield HTTP Status 409 "Conflict".
        /// All other rexceptions result to 500 "Internal Server Error".
        /// </remarks>
        public void OnException(ExceptionContext filterContext)
        {
            if (filterContext.HttpContext.Request.Headers["X-Requested-With"] == "XMLHttpRequest")
            {
                var exception = filterContext.Exception;

                UserErrorModel userErrorModel = null;

                var statusCode = HttpStatusCode.InternalServerError;

                if (exception is AccessDeniedException ||
                    exception is IntegrityViolationException)
                {
                    string userMessage;

                    switch (exception)
                    {
                    case AccessDeniedException accessDeniedException:
                        statusCode  = HttpStatusCode.Forbidden;
                        userMessage = ErrorMessages.ACCESS_DENIED;

                        var telemetry = new Microsoft.ApplicationInsights.TelemetryClient();

                        telemetry.TrackException(exception);
                        break;

                    case UniqueConstraintViolationException uniqueConstraintViolationException:
                        statusCode  = HttpStatusCode.Conflict;
                        userMessage = ErrorMessages.UNIQUENESS_CONSTRAINT_VIOLATION;
                        break;

                    case ReferentialConstraintViolationException referentialConstraintViolationException:
                        statusCode  = HttpStatusCode.Conflict;
                        userMessage = ErrorMessages.RELATIONAL_CONSTRAINT_VIOLATION;
                        break;

                    default:
                        statusCode  = HttpStatusCode.InternalServerError;
                        userMessage = ErrorMessages.GENERIC_ERROR;
                        break;
                    }

                    userErrorModel = new UserErrorModel(userMessage);
                }
                else if (exception is UserException userException)
                {
                    userErrorModel = new UserErrorModel(userException);
                }

                if (userErrorModel != null)
                {
                    filterContext.Result = new JsonResult
                    {
                        Data                = userErrorModel,
                        ContentEncoding     = Encoding.UTF8,
                        JsonRequestBehavior = JsonRequestBehavior.AllowGet
                    };

                    filterContext.HttpContext.Response.StatusCode = (int)statusCode;

                    filterContext.ExceptionHandled = true;
                }
            }
        }
Beispiel #51
0
 private const int deleteInterval = 1; //Value in hours
 
 public AppController()
 {
     TelemetryClient = new Microsoft.ApplicationInsights.TelemetryClient();
     Server = new WebServer();
     XmlSettings = new AppSettings();
 }
Beispiel #52
0
        private async Task <IActionResult> PostSINnerInternal(UploadInfoObject uploadInfo)
        {
            _logger.LogTrace("Post SINnerInternalt: " + uploadInfo + ".");
            ApplicationUser user   = null;
            SINner          sinner = null;

            try
            {
                if (!ModelState.IsValid)
                {
                    var errors = ModelState.Select(x => x.Value.Errors)
                                 .Where(y => y.Count > 0)
                                 .ToList();
                    string msg = "ModelState is invalid: ";
                    foreach (var err in errors)
                    {
                        foreach (var singleerr in err)
                        {
                            msg += Environment.NewLine + "\t" + singleerr.ToString();
                        }
                    }
                    return(new BadRequestObjectResult(new HubException(msg)));
                }
                if (uploadInfo.UploadDateTime == null)
                {
                    uploadInfo.UploadDateTime = DateTime.Now;
                }
                if (uploadInfo.Client != null)
                {
                    if (!UploadClientExists(uploadInfo.Client.Id))
                    {
                        _context.UploadClients.Add(uploadInfo.Client);
                    }
                    else
                    {
                        _context.UploadClients.Attach(uploadInfo.Client);
                        _context.Entry(uploadInfo.Client).State = EntityState.Modified;
                        _context.Entry(uploadInfo.Client).CurrentValues.SetValues(uploadInfo.Client);
                    }
                }
                var returncode = HttpStatusCode.OK;
                user = await _signInManager.UserManager.FindByNameAsync(User.Identity.Name);

                foreach (var tempsinner in uploadInfo.SINners)
                {
                    sinner = tempsinner;
                    if (sinner.Id.ToString() == "string")
                    {
                        sinner.Id = Guid.Empty;
                    }

                    if (String.IsNullOrEmpty(sinner.JsonSummary))
                    {
                        return(BadRequest("sinner " + sinner.Id + ": JsonSummary == null"));
                    }

                    if (sinner.SINnerMetaData.Visibility.UserRights.Any() == false)
                    {
                        return(BadRequest("Sinner  " + sinner.Id + ": Visibility contains no entries!"));
                    }

                    if (sinner.LastChange == null)
                    {
                        return(BadRequest("Sinner  " + sinner.Id + ": LastChange not set!"));
                    }
                    if (sinner.SINnerMetaData.Visibility.Id == null)
                    {
                        sinner.SINnerMetaData.Visibility.Id = Guid.NewGuid();
                    }
                    var olduserrights = await(from a in _context.UserRights where a.SINnerId == sinner.Id select a).ToListAsync();
                    _context.UserRights.RemoveRange(olduserrights);
                    foreach (var ur in sinner.SINnerMetaData.Visibility.UserRights)
                    {
                        ur.Id       = Guid.NewGuid();
                        ur.SINnerId = sinner.Id;
                        _context.UserRights.Add(ur);
                    }

                    foreach (var tag in sinner.SINnerMetaData.Tags)
                    {
                        tag.SetSinnerIdRecursive(sinner.Id);
                    }

                    sinner.UploadClientId = uploadInfo.Client.Id;
                    SINner dbsinner = await CheckIfUpdateSINnerFile(sinner.Id.Value, user);

                    if (dbsinner != null)
                    {
                        _context.SINners.Attach(dbsinner);
                        if (String.IsNullOrEmpty(sinner.GoogleDriveFileId))
                        {
                            sinner.GoogleDriveFileId = dbsinner.GoogleDriveFileId;
                        }
                        if (String.IsNullOrEmpty(sinner.DownloadUrl))
                        {
                            sinner.DownloadUrl = dbsinner.DownloadUrl;
                        }
                        //_context.Entry(dbsinner.SINnerMetaData.Visibility).State = EntityState.Modified;
                        _context.Entry(dbsinner.SINnerMetaData.Visibility).CurrentValues.SetValues(sinner.SINnerMetaData.Visibility);

                        //_context.Tags.RemoveRange(dbsinner.AllTags);
                        _context.Entry(dbsinner).State = EntityState.Modified;
                        _context.Entry(dbsinner).CurrentValues.SetValues(sinner);
                        string msg = "Sinner " + sinner.Id + " updated: " + _context.Entry(dbsinner).State.ToString();
                        msg += Environment.NewLine + Environment.NewLine + "LastChange: " + dbsinner.LastChange;
                        _logger.LogError(msg);
                        List <Tag> taglist = sinner.SINnerMetaData.Tags;
                        UpdateEntityEntries(taglist);
                    }
                    else
                    {
                        returncode = HttpStatusCode.Created;
                        _context.SINners.Add(sinner);
                    }
                }
                try
                {
                    await _context.SaveChangesAsync();
                }

                catch (DbUpdateConcurrencyException ex)
                {
                    foreach (var entry in ex.Entries)
                    {
                        if (entry.Entity is SINner)
                        {
                            DbUpdateConcurrencyExceptionHandler(entry);
                        }
                        else if (entry.Entity is Tag)
                        {
                            DbUpdateConcurrencyExceptionHandler(entry);
                        }
                        else
                        {
                            throw new NotSupportedException(
                                      "Don't know how to handle concurrency conflicts for "
                                      + entry.Metadata.Name);
                        }
                    }
                }
                catch (Exception e)
                {
                    try
                    {
                        var tc = new Microsoft.ApplicationInsights.TelemetryClient();
                        Microsoft.ApplicationInsights.DataContracts.ExceptionTelemetry telemetry = new Microsoft.ApplicationInsights.DataContracts.ExceptionTelemetry(e);
                        telemetry.Properties.Add("User", user?.Email);
                        telemetry.Properties.Add("SINnerId", sinner?.Id?.ToString());
                        telemetry.Metrics.Add("TagCount", (double)sinner?.AllTags?.Count);
                        tc.TrackException(telemetry);
                    }
                    catch (Exception ex)
                    {
                        _logger.LogError(ex.ToString());
                    }
                    HubException hue = new HubException("Exception in PostSINnerFile: " + e.Message, e);
                    var          msg = new System.Net.Http.HttpResponseMessage(HttpStatusCode.Conflict)
                    {
                        ReasonPhrase = hue.Message
                    };
                    return(Conflict(msg));
                }
                List <Guid> myids = (from a in uploadInfo.SINners select a.Id.Value).ToList();
                switch (returncode)
                {
                case HttpStatusCode.OK:
                    return(Accepted("PostSINnerFile", myids));

                case HttpStatusCode.Created:
                    return(CreatedAtAction("PostSINnerFile", myids));

                default:
                    break;
                }
                return(BadRequest());
            }
            catch (Exception e)
            {
                try
                {
                    var tc = new Microsoft.ApplicationInsights.TelemetryClient();
                    Microsoft.ApplicationInsights.DataContracts.ExceptionTelemetry telemetry = new Microsoft.ApplicationInsights.DataContracts.ExceptionTelemetry(e);
                    telemetry.Properties.Add("User", user?.Email);
                    telemetry.Properties.Add("SINnerId", sinner?.Id?.ToString());
                    telemetry.Metrics.Add("TagCount", (double)sinner?.AllTags?.Count);
                    tc.TrackException(telemetry);
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex.ToString());
                }
                HubException hue = new HubException("Exception in PostSINnerFile: " + e.Message, e);
                return(BadRequest(hue));
            }
        }
 private void updateAstronomy(string response)
 {
     var json = JObject.Parse(response);
     JToken astronomyRoot;
     if (!json.TryGetValue("moon_phase", out astronomyRoot))
     {
         var tc = new Microsoft.ApplicationInsights.TelemetryClient();
         var properties = new Dictionary<String, string> { { "response", response } };
         tc.TrackEvent($"Unexpected response in {nameof(updateAstronomy)}", properties);
         return;
     }
     var rawSunrise = astronomyRoot["sunrise"];
     var rawSunset = astronomyRoot["sunset"];
     // Date doesn't matter, we only care about hours and minutes
     Sunrise = DateTime.Parse(rawSunrise["hour"]+":"+ rawSunrise["minute"]);
     Sunset = DateTime.Parse(rawSunset["hour"] + ":" + rawSunset["minute"]);
 }
 private void InitializeTelemetry()
 {
     this.telemetryClient = new Microsoft.ApplicationInsights.TelemetryClient()
     {
         InstrumentationKey = ImageResizePackage.AppInsightsGuidString,
     };
 }