Example #1
0
        public JsonResult GetDealershipInfo(int id)
        {
            try
            {
                var service               = new DealershipAccountService(db);
                var dealership            = service.GetDealership(id);
                var dealershipEditManager = new DealershipManager
                {
                    Id          = dealership.Id,
                    CompanyName = dealership.CompanyName,
                    Email       = dealership.Email,
                    City        = dealership.City,
                    State       = dealership.State,
                    ZipCode     = dealership.ZipCode,
                    Notes       = dealership.Notes,
                    PhoneNumber = dealership.PhoneNumber,
                    FaxNumber   = dealership.FaxNumber
                };

                return(Json(dealershipEditManager, JsonRequestBehavior.AllowGet));
            }
            catch (Exception ex)
            {
                var errorService = new ErrorService(db);
                errorService.logError(ex);

                throw (ex);
            }
        }
Example #2
0
        protected override void OnStart(string[] args)
        {
            /* when we start our service we are generating xml files according to data from database */
            var projectPath = AppDomain.CurrentDomain.BaseDirectory;
            var manager     = new MyConfigurationManager.ConfigurationManager();
            var pathOption  = manager.GetOptions <PathsOptions>(projectPath + "xmlConfig.xml");

            try
            {
                var          repositories = new UnitOfWork(pathOption.DBpath1);
                OrderService orderService = new OrderService(repositories);

                /* now getting list of orders */
                var ordersInfo = orderService.GetListOfOrders();

                XmlGenerateService <Order> orders = new XmlGenerateService <Order>(pathOption.ClientDirectory + "\\Orders.xml");

                /* generating xml file */
                orders.XmlGenerate(ordersInfo);
            }

            catch (Exception trouble)
            {
                /* if something went wrong */
                var          repositories2 = new UnitOfWork(pathOption.DBpath2);
                ErrorService service       = new ErrorService(repositories2);
                service.AddErrors(new Errors(trouble.GetType().Name, trouble.Message, DateTime.Now));
            }
        }
Example #3
0
        public JsonResult GetCurrentDealershipInfo()
        {
            try
            {
                var service               = new DealershipAccountService(db);
                var currentId             = service.GetCurrentUserDealershipIdFromIdentity();
                var dealership            = db.Dealerships.FirstOrDefault(x => x.Id == currentId);
                var dealershipEditManager = new DealershipManager
                {
                    Id          = dealership.Id,
                    CompanyName = dealership.CompanyName,
                    Email       = dealership.Email,
                    City        = dealership.City,
                    State       = dealership.State,
                    ZipCode     = dealership.ZipCode,
                    Notes       = dealership.Notes,
                    PhoneNumber = dealership.PhoneNumber,
                    FaxNumber   = dealership.FaxNumber
                };

                return(Json(dealershipEditManager, JsonRequestBehavior.AllowGet));
            }
            catch (Exception ex)
            {
                var errorService = new ErrorService(db);
                errorService.logError(ex);

                throw (ex);
            }
        }
Example #4
0
        public ActionResult Create(evento model)
        {
            try
            {
                var      idusu = SesionLogin().ID;
                DateTime fec   = DateTime.Today;


                model.usuario_mod = SesionLogin().Sigla;
                model.fecha_mod   = DateTime.Now;
                model.id_usuario  = idusu;
                model.estado      = "1";
                model.id_usuario  = idusu;
                //!(model.fecha.ToString().Equals(fec.ToString())) ||
                if (model.fecha < fec)
                {
                    return(JsonError("Fecha ingresada no debe ser anterior a la de hoy."));
                }

                if (ModelState.IsValid)
                {
                    _db.evento.Add(model);
                    _db.SaveChanges();
                    return(JsonExitoMsg("Evento"));
                }
            }
            catch (Exception ex)
            {
                ErrorService.LogError(ex);
                return(JsonError("Hey !!! hubo un problema."));
            }

            return(View());
        }
Example #5
0
        public void IsReturnTypeCorrect()
        {
            var actual   = ErrorService.GetError("test");
            var expected = typeof(Error);

            Assert.IsType(expected, actual);
        }
Example #6
0
        protected override void OnStart(string[] args)
        {
            ThreadPool.QueueUserWorkItem(async state =>
            {
                logger = new Logger();
                string connectionString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
                try
                {
                    var repositories          = new UnitOfWork(connectionString);
                    OrderService orderService = new OrderService(repositories);
                    var ordersInfo            = await orderService.GetOrders();

                    //making proper file name
                    DateTime now = DateTime.Now;
                    var currTime = now.ToString("yyyy_MM_dd_HH_mm_ss");

                    XmlGenerator <Order> orders = new XmlGenerator <Order>(logger.parsedOptions.options.PathsOptions.SourceDirectory + "Sales_" + currTime + ".txt");
                    await orders.XmlGenerate(ordersInfo);
                    this.OnStop();
                }
                catch (Exception trouble)
                {
                    var repositories2    = new UnitOfWork(connectionString);
                    ErrorService service = new ErrorService(repositories2);
                    service.AddErrors(new Error(trouble.GetType().Name, trouble.Message, DateTime.Now));
                }
                Thread loggerThread = new Thread(new ThreadStart(logger.Start));
                loggerThread.Start();
            });
        }
Example #7
0
        public async Task <ActionResult> RemoveLogin(string loginProvider, string providerKey)
        {
            try
            {
                ManageMessageId?message;
                var             result = await UserManager.RemoveLoginAsync(User.Identity.GetUserId(), new UserLoginInfo(loginProvider, providerKey));

                if (result.Succeeded)
                {
                    var user = await UserManager.FindByIdAsync(User.Identity.GetUserId());

                    if (user != null)
                    {
                        await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false);
                    }
                    message = ManageMessageId.RemoveLoginSuccess;
                }
                else
                {
                    message = ManageMessageId.Error;
                }
                return(RedirectToAction("ManageLogins", new { Message = message }));
            }
            catch (Exception ex)
            {
                var errorService = new ErrorService(db);
                errorService.logError(ex);

                throw (ex);
            }
        }
Example #8
0
 public void LoadData()
 {
     if (NetworkInterface.GetIsNetworkAvailable())
     {
         IScheduler scheduler = Scheduler.Dispatcher;
         scheduler.Schedule(() =>
         {
             GetTwitterFeed();
             GetCanucksGameFeed();
             GetCanucksticketsFeed();
             GetCanucksStoreFeed();
             GetCanucksPromoFeed();
             CheckForErrors();
         });
     }
     else
     {
         var builder = new StringBuilder();
         builder.AppendLine("To update the application a network connection is required.");
         builder.AppendLine("The application will attempt to load saved data");
         builder.AppendLine();
         builder.AppendLine(
             "When a network connection has been re-established tap on the ellipsis at the bottom right hand corner and select ‘refresh’");
         ErrorService errorService = new ErrorService(builder.ToString(), "No network connection detected")
                                     .ErrorDialog(true);
         errorService.HandleError();
     }
 }
Example #9
0
        public void FromException_GeneratesCorrectTransactionExceptionData()
        {
            IErrorService errorService = new ErrorService(Mock.Create <IConfigurationService>());
            var           now          = DateTime.UtcNow;

            Exception ex;

            try
            {
                throw new Exception("Oh no!");
            }
            catch (Exception e)
            {
                ex = e;
            }

            var errorData = errorService.FromException(ex);

            NrAssert.Multiple(
                () => Assert.AreEqual("Oh no!", errorData.ErrorMessage),
                () => Assert.AreEqual("System.Exception", errorData.ErrorTypeName),
                () => Assert.IsFalse(string.IsNullOrEmpty(errorData.StackTrace)),
                () => Assert.IsTrue(errorData.NoticedAt > now.AddMinutes(-1) && errorData.NoticedAt < now.AddMinutes(1))
                );
        }
Example #10
0
        public ActionResult SetProfileImages(HttpPostedFileBase[] headerImageFile)
        {
            try
            {
                //get the dealer id from dealership account service
                var dealershipService = new DealershipAccountService(db);
                var imageService      = new ImageManagementService(db);
                var currentDealerId   = dealershipService.GetCurrentUserDealershipIdFromIdentity();

                //add images to Dealership table using image service
                var dealership = db.Dealerships.FirstOrDefault(x => x.Id == currentDealerId);
                if (dealership != null)
                {
                    //imageService.AssignProfileImagesToDealership(currentDealerId, headerImageFile, iconImageFile);
                }

                return(RedirectToAction("Index"));
            }
            catch (Exception ex)
            {
                var errorService = new ErrorService(db);
                errorService.logError(ex);

                throw (ex);
            }
        }
Example #11
0
        public IActionResult Index()
        {
            var feature = HttpContext.Features.Get <IExceptionHandlerFeature>();
            var error   = feature?.Error;

            if (error != null)
            {
                if (error is ForbiddenException)
                {
                    return(RedirectToAction("AccessDenied", "User"));
                }
                else if (error is NotFoundException)
                {
                    return(RedirectToAction("NotFound"));
                }
                else if (error is UnauthorizedException)
                {
                    return(RedirectToAction("Logout", "User"));
                }
                else
                {
                    var task = ErrorService.CreateError(new AppErrorModel(error, MyUser?.UserId.ToString(), "global error handler"));
                }
            }

            return(View(new ErrorViewModel {
                RequestId = System.Diagnostics.Activity.Current?.Id ?? HttpContext.TraceIdentifier
            }));
        }
Example #12
0
        //GET - retrieve jason representations of vehicle images to render to view
        public JsonResult LoadVehicleImages(int id)
        {
            try
            {
                var vehicleService    = new VehicleSearchService(db);
                var dealershipService = new DealershipAccountService(db);
                var images            = vehicleService.GetAllVehicleImages(id);


                var vehicleImages = new List <VehicleImageViewModel>();
                if (images != null)
                {
                    foreach (var item in images)
                    {
                        var imageBytes = item.ImageBytes;
                        //convert image byte array to base64 string to be rendered properly in browser
                        var imageBytesBase64String = Convert.ToBase64String(imageBytes);


                        vehicleImages.Add(new VehicleImageViewModel(item.Id, imageBytesBase64String));
                    }
                    return(Json(vehicleImages, JsonRequestBehavior.AllowGet));
                }
                return(null);
            }
            catch (Exception ex)
            {
                var errorService = new ErrorService(db);
                errorService.logError(ex);

                throw (ex);
            }
        }
Example #13
0
        //Get - retrieve vehicle search results
        public JsonResult GetSearchResults(string make, string model, string transmission, string style, string condition, int year, int minPrice, int maxPrice, int minMileage, int maxMileage, int cylinderNumber, string exteriorColor)
        {
            try
            {
                using (var db = new AutoScoutDBContext())
                {
                    //create instance of Vehicle Search Service
                    var vehicleSearchService = new VehicleSearchService(db);

                    //send search result criteria from parameters to SearchInventory method which will return matching vehicles
                    var searchResults     = vehicleSearchService.SearchInventory(make, model, year, minPrice, maxPrice, minMileage, maxMileage, transmission, style, condition, cylinderNumber, exteriorColor);
                    var vehicleViewModels = new List <VehicleSearchCriteriaViewModel>();
                    foreach (var item in searchResults)
                    {
                        var companyName = vehicleSearchService.GetCompanyName(item.DealershipId);
                        vehicleViewModels.Add(new VehicleSearchCriteriaViewModel(item.Id, item.Make, item.Model, item.Year, item.Price, item.Mileage, item.Transmission, item.Style, item.Condition, item.CylinderNumber, item.ExteriorColor, item.DealershipId, companyName));
                    }
                    //return JSON objects to view model
                    return(Json(vehicleViewModels, JsonRequestBehavior.AllowGet));
                }
            }
            catch (Exception ex)
            {
                var errorService = new ErrorService(db);
                errorService.logError(ex);

                throw (ex);
            }
        }
Example #14
0
        public IHttpActionResult Get()
        {
            ErrorService errorService = CreateErrorService();
            var          errors       = errorService.GetErrors();

            return(Ok(errors));
        }
        public void List_Return_ShouldNotBeNull(
            int?start,
            int?end,
            bool archived)
        {
            // Arrange

            var context = GenerateContext("ListErros");
            var service = new ErrorService(context);

            var expected = context.Errors
                           .Where(x => x.IsArchived == archived)
                           .Skip(start.HasValue ? start.Value : 0)
                           .ToList();

            // Act
            if (end.HasValue)
            {
                expected = expected
                           .Take(end.Value)
                           .ToList();
            }

            var result = service.List(
                start,
                end,
                archived);

            // Assert
            Assert.NotNull(result);
            Assert.Equal(result.Count(), expected.Count());
        }
Example #16
0
        public ActionResult Edit(WebApplicationMod.Clientes model, string chk_activo, string chk_irfs, string chk_adm_cheq, string chk_contdolares, string chk_eeff, string chk_tesoreria, string chk_payroll, string chk_idioma, string chk_impu, string chk_snringles, string ivaselect)
        {
            try
            {
                // Almaceno el usuario modificador de la empresa.
                model.Usu = "Jackermann";

                //  convierto Checkbox en S o N
                model.Activo        = chk_activo == "true" ? "S" : "N";
                model.IRFS          = chk_irfs == "true" ? "S" : "N";
                model.AdmCheque     = chk_adm_cheq == "true" ? "S" : "N";
                model.CTD           = chk_contdolares == "true" ? "S" : "N";
                model.publicar_eeff = chk_eeff == "true" ? "S" : "N";
                model.TES           = chk_tesoreria == "true" ? "S" : "N";
                //model.RRHH = chk_payroll == "true" ? "S" : "N";
                model.RRHH     = chk_payroll == "true" ? "S" : "N";
                model.IIng     = chk_idioma == "true" ? "S" : "N";
                model.impsug   = chk_impu == "true" ? "S" : "N";
                model.snr_ingl = chk_snringles == "true" ? "S" : "N";
                model.Tipo     = ivaselect;

                if (ModelState.IsValid)
                {
                    _db.Entry(model).State = System.Data.Entity.EntityState.Modified;
                    _db.SaveChanges();
                    return(JsonExitoMsg(model.ID.ToString()));
                }
                return(JsonError("Hey !!! hubo un problema."));
            }
            catch (Exception ex)
            {
                ErrorService.LogError(ex);
                return(JsonError("Hey !!! hubo un problema."));
            }
        }
Example #17
0
        private ErrorService CreateErrorService()
        {
            var userId       = Guid.Parse(User.Identity.GetUserId());
            var errorService = new ErrorService(userId);

            return(errorService);
        }
Example #18
0
        public async Task RefreshDataAsync()
        {
            UpdateInProgress = true;

            if (ViewMode == SprudelDetailPageViewModeEnum.DisplayFavorite)
            {
                var repo     = CreateSprudelRepository();
                var newInfos = await repo.RefreshAsync();

                if (newInfos.Succeeded)
                {
                    QueryResult = newInfos.Results.Single(r => r.UniqueId == QueryResult.UniqueId);
                }
                else
                {
                    ErrorService.ShowLightDismissError("Refresh der Preise ist fehlgeschlagen");
                }
            }
            else
            {
                var gasinfoProxy = CreateGasPriceInfoProxy();
                var result       = await gasinfoProxy.DownloadAsync(QueryResult);

                if (result.Succeeded)
                {
                    QueryResult = result.Result;
                }
                else
                {
                    ErrorService.ShowLightDismissError("Refresh der Preise ist fehlgeschlagen");
                }
            }

            UpdateInProgress = false;
        }
Example #19
0
        public async Task DownloadInfoAsync(double lat1, double long1, double lat2, double long2)
        {
            var fueltype  = QueryResult.FuelType;
            var parameter = new GasQuery(Guid.NewGuid().ToString(), fueltype, long1, lat1, long2, lat2);

            try
            {
                var gasinfoProxy = CreateGasPriceInfoProxy();
                var result       = await gasinfoProxy.DownloadAsync(parameter);

                if (result.Succeeded)
                {
                    SetQueryResultToGeocodeResult(result.Result);
                    SendUpdateMapNotification();

                    CurrentLocationFound = true;
                }
                else
                {
                    ErrorService.ShowLightDismissError("Die Preisinformationen konnten nicht ermittelt werden");
                }
            }
            catch (Exception)
            {
                ErrorService.ShowLightDismissError("Die Preisinformationen konnten nicht ermittelt werden");
            }

            UpdateInProgress = false;
        }
Example #20
0
        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            object errorObj = Request[ConstHelper.ErrorCode];

            if (errorObj != null)
            {
                var errorKey  = errorObj.ToString();
                var errorText = ErrorService.Get(errorKey);
                ViewBag.ExceptionText = errorText;
            }

            if (UserContext.Current != null && !UserContext.Current.IsPhoneVerified)
            {
                if (!Request.Path.Contains("/home/") && !Request.Path.Contains("/account/") && !Request.Path.Contains("/about") && !Request.Path.Contains("/help") && !Request.Path.Contains("/feedback"))
                {
                    var result = RedirectToAction("activation", "account", null);
                    filterContext.Result = result;
                }
            }

            //if (UserContext.Current != null && UserContext.Current.IsOutdated)
            //{
            //    if (!Request.Path.Contains("/home/") && !Request.Path.Contains("/account/") && !Request.Path.Contains("/about") && !Request.Path.Contains("/help") && !Request.Path.Contains("/feedback"))
            //    {
            //        var result = RedirectToAction("activation", "account", null);
            //        filterContext.Result = result;
            //    }
            //}

            base.OnActionExecuting(filterContext);
        }
        public void Register_Should_Add_New_Error()
        {
            // Arrange
            var fakeContext = new FakeContext("RegisterError");

            fakeContext.FillWith <Level>();
            fakeContext.FillWith <Microsservice>();
            fakeContext.FillWith <Model.Models.Environment>();

            var   context = new CentralDeErrosDbContext(fakeContext.FakeOptions);
            var   service = new ErrorService(context);
            Error entry   = new Error
            {
                Title                 = "Teste1",
                Origin                = "1.0.0.1",
                Details               = "Detail1",
                ErrorDate             = DateTime.Today,
                MicrosserviceClientId = new Guid("031c156c-c072-4793-a542-4d20840b8031"),
                EnviromentId          = 1,
                LevelId               = 1,
                IsArchived            = false
            };

            // Act
            var result = service.Register(entry);

            // Assert
            Assert.True(result.Id == 1, $"Should return new error with id 1. returned: {result.Id}");
            Assert.True(context.Errors.Count() == 1, $"Should have one error saved. > Amount: {context.Errors.Count()}");
        }
Example #22
0
        public IHttpActionResult Get(int id)
        {
            ErrorService errorService = CreateErrorService();
            var          error        = errorService.GetErrorById(id);

            return(Ok($"Here is the error you requested: {error}"));
        }
        public void Register_Should_Throw_When_Add_Non_Existent_FK(
            Guid microsserviceId,
            int LevelId,
            int environmentId)
        {
            // Arrange
            var context = GenerateContext("RegisterBadError");
            var service = new ErrorService(context);

            Error entry = new Error
            {
                Id                    = 1,
                Title                 = "Teste1",
                Origin                = "1.0.0.1",
                Details               = "Detail1",
                ErrorDate             = DateTime.Today,
                MicrosserviceClientId = microsserviceId,
                EnviromentId          = environmentId,
                LevelId               = LevelId,
                IsArchived            = false
            };

            // Act
            // Assert
            Assert.Throws <Exception>(() => service.Register(entry));
        }
Example #24
0
        public ActionResult Delete(string id)
        {
            int id_ex = Int32.Parse(id);

            var model = _db.evento.FirstOrDefault(p => p.id == id_ex);

            if (model == null)
            {
                return(RedirectToAction("Create"));
            }

            try
            {
                model.usuario_mod = SesionLogin().Sigla;
                model.fecha_mod   = DateTime.Now;
                model.estado      = "0";

                if (ModelState.IsValid)
                {
                    _db.Entry(model).State = System.Data.Entity.EntityState.Modified;
                    _db.SaveChanges();
                    return(JsonExitoMsg("Eliminado"));
                }
            }
            catch (Exception ex)
            {
                ErrorService.LogError(ex);
                return(JsonError("Hey !!! hubo un problema."));
            }

            return(View());
        }
Example #25
0
        // GET: Vehicles/Delete/5
        public void Delete(int?id)
        {
            try
            {
                if (id != null)
                {
                    Vehicle vehicle = db.Vehicles.Find(id);
                    if (vehicle != null)
                    {
                        string make  = vehicle.Make;
                        string model = vehicle.Model;
                        string year  = vehicle.Year.ToString();
                        string item  = year + " " + make + " " + model;
                        ViewBag.stringDescription = item;

                        var dealershipService = new DealershipAccountService(db);
                        var currentDealerId   = dealershipService.GetCurrentUserDealershipIdFromIdentity();
                        dealershipService.DeleteVehicleFromInventory(vehicle.Id, currentDealerId);
                    }
                }
            }
            catch (Exception ex)
            {
                var errorService = new ErrorService(db);
                errorService.logError(ex);

                throw (ex);
            }
        }
Example #26
0
        public async Task <ActionResult> Edit([Bind(Include = "Id,CompanyName,Email,City,State,ZipCode,FaxNumber,Notes,PhoneNumber")] Dealership dealership)
        {
            try
            {
                var    service    = new DealershipAccountService(db);
                string identityId = service.GetCurrentUserIdentity();
                dealership.AutoScoutIdentityUserId = identityId;

                if (ModelState.IsValid)
                {
                    db.Entry(dealership).State = EntityState.Modified;
                    await db.SaveChangesAsync();

                    ViewBag.ResponseMessage = "Your changes have been saved.";
                }
                //ViewBag.AutoScoutIdentityUserId = new SelectList(db.Dealerships, "Id", "Email", dealership.AutoScoutIdentityUserId);
                return(View("ManageProfile"));
            }
            catch (Exception ex)
            {
                var errorService = new ErrorService(db);
                errorService.logError(ex);

                throw (ex);
            }
        }
Example #27
0
        //GET
        public ActionResult AddImage(int?id)
        {
            try
            {
                var vehicle = db.Vehicles.FirstOrDefault(x => x.Id == id);

                if (vehicle != null)
                {
                    string make   = vehicle.Make;
                    string vModel = vehicle.Model;
                    string year   = vehicle.Year.ToString();
                    string item   = year + " " + make + " " + vModel;
                    ViewBag.stringDescription = item;
                }

                VehicleImage image = new VehicleImage();
                return(View(image));
            }
            catch (Exception ex)
            {
                var errorService = new ErrorService(db);
                errorService.logError(ex);

                throw (ex);
            }
        }
Example #28
0
        public ActionResult Update(evento model)
        {
            try
            {
                //var idusu = SesionLogin().ID;

                model.usuario_mod = SesionLogin().Sigla;
                model.fecha_mod   = DateTime.Now;
                model.id_usuario  = SesionLogin().ID;
                model.estado      = "1";
                if (model.fecha < DateTime.Now)
                {
                    return(JsonError("Fecha ingresada no debe ser anterior a la de hoy."));
                }

                if (ModelState.IsValid)
                {
                    _db.Entry(model).State = System.Data.Entity.EntityState.Modified;
                    _db.SaveChanges();
                    return(JsonExitoMsg("Actualizado"));
                }
                return(JsonError("Error"));
            }
            catch (Exception ex)
            {
                ErrorService.LogError(ex);
                return(JsonError("Hey !!! hubo un problema."));
            }
        }
Example #29
0
        public ActionResult AddImage(int id, VehicleImage model, HttpPostedFileBase imageFile)
        {
            try
            {
                var db = new AutoScoutDBContext();
                //var vehicle = db.Vehicles.FirstOrDefault(x => x.Id == vehicleId);
                Vehicle vehicle = db.Vehicles.Find(id);

                if (vehicle != null)
                {
                    string make   = vehicle.Make;
                    string vModel = vehicle.Model;
                    string year   = vehicle.Year.ToString();
                    string item   = year + " " + make + " " + vModel;
                    ViewBag.stringDescription = item;
                }

                if (imageFile != null)
                {
                    var service = new ImageManagementService(db);
                    service.AssignImageToVehicle(id, imageFile);
                }

                return(RedirectToAction("Edit", new { id = id }));;
            }
            catch (Exception ex)
            {
                var errorService = new ErrorService(db);
                errorService.logError(ex);

                throw (ex);
            }
        }
Example #30
0
 public void LoadData()
 {
     CheckPlayOff();
     if (!NetworkInterface.GetIsNetworkAvailable())
     {
         var builder = new StringBuilder();
         builder.AppendLine("To update the application a network connection is required.");
         builder.AppendLine("The application will attempt to load saved data");
         builder.AppendLine();
         builder.AppendLine(
             "When a network connection has been re-established tap on the ellipsis at the bottom right hand corner and select ‘refresh’");
         ErrorService errorService = new ErrorService(builder.ToString(), "No network connection detected")
                                     .ErrorDialog(true);
         errorService.HandleError();
         LoadCachedData();
     }
     else
     {
         if (IsPlayoffs)
         {
             LoadPlayoffScoresAndSchedules();
         }
         LoadScoresAndSchedules();
         IScheduler scheduler = Scheduler.Dispatcher;
         scheduler.Schedule(() =>
         {
             GetNewsStream();
             GetFeatures();
             GetTwitterFeed();
             GetFeedInfoItems();
             CheckForErrors();
         });
     }
 }
        public void ValidateErrorInfo_Returns_False_Test()
        {
            // Arrange
            ErrorService service = new ErrorService();

            // Act
            bool result = service.ValidateErrorInfo(new ErrorInfo());

            // Assert
            Assert.False(result);
        }
        public void ValidateToken_Returns_True_Test()
        {
            // Arrange
            ErrorService service = new ErrorService();

            // Act
            bool result = service.ValidateToken("token");

            // Assert
            Assert.True(result);
        }
        public void ValidateErrorInfo_Returns_True_Test()
        {
            // Arrange
            ErrorService service = new ErrorService();

            ErrorInfo info = new ErrorInfo
                                 {
                                     ApplicationName = "ApplicationName",
                                     Host = "Host",
                                     Message = "Message",
                                     Detail = "Error"
                                 };

            // Act
            bool result = service.ValidateErrorInfo(info);

            // Assert
            Assert.True(result);
        }
        /// <summary>
        /// Setup steps that we do each time WorkflowDesigner is refreshed. Right now we just configure what assemblies to show in the
        /// type lists for Variable/Argument types.
        /// </summary>
        /// <param name="workflowDesigner"></param>
        private void ConfigureWorkflowDesigner(WorkflowDesigner workflowDesigner)
        {
            Errors = new ErrorService(this);
            ErrorService errors = Errors;
            workflowDesigner.Context.Services.Publish<IXamlLoadErrorService>(errors);
            workflowDesigner.Context.Services.Publish<IValidationErrorService>(errors);

            workflowDesigner.Text = xamlCode; // setup for workflowDesigner.Load()
            workflowDesigner.Load(); // initialize workflow based on Text property

            if (errors.ErrorList.Any())
            {
                // There were XAML errors loading, don't bother adding a validationErrorInfo
                // since it's kind of redunant, but do set the WorkflowDesigner to readonly mode.
                // If the user fixes the Xaml errors we'll get a new WorkflowDesigner which will
                // have an empty errors.ErrorList.
                if (!workflowDesigner.IsInErrorState())
                {
                    // If we are still going to show a diagram, make it translucent to make it clear it's read-only
                    workflowDesigner.Context.Items.GetValue<ReadOnlyState>().IsReadOnly = true;
                    workflowDesigner.View.Opacity = 0.60; // code smell: setting View property from WorkflowItem ctor. But it's hard to get IsReadOnly from XAML.
                }
            }
            else
            {
                // Do initial validation synchronously to avoid UI glitches
                // (buttons enabled-until-validation-realizes-workflow-isn't-valid)
                try
                {
                    var rootActivity = AsDynamicActivity();
                    if (rootActivity == null)
                    {
                        // It loaded but it's not a workflow and we can't validate it in detail.
                        // All we know is that it's not a valid workflow. E.g. it could be a XAML object like
                        // <x:String xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">32</x:String>
                        errors.ShowValidationErrors(new[] { new ValidationErrorInfo(MSG_Validation_Error) });
                    }
                    else
                    {
                        ValidationResults myValidationResults = ActivityValidationServices.Validate(rootActivity);
                        errors.ShowValidationErrors((from err in myValidationResults.Errors select new ValidationErrorInfo(err)).ToList());
                    }
                }
                catch (XamlException e)  // Yes, ActivityValidationServices.Validate can throw  No, it's not documented on MSDN.
                {
                    // Bad XAML (e.g. setting nonexistent properties) is not a valid workflow
                    errors.ShowXamlLoadErrors(new[] { new XamlLoadErrorInfo(e.Message, e.LineNumber, e.LinePosition) });
                }
            }
        }