Ejemplo n.º 1
0
        protected override void ApplicationStartup(TinyIoCContainer container, IPipelines pipelines)
        {
            // intercept the request and fill common ViewBag data.
            pipelines.AfterRequest += (ctx) =>
            {
                ctx.ViewBag.StackName = _configManager.StackConfig.Name;

                if (string.IsNullOrEmpty(ctx.ViewBag.Header))
                {
                    ctx.ViewBag.Header = "";
                }

                ctx.ViewBag.Title = string.IsNullOrEmpty(ctx.ViewBag.Header)
                    ? _configManager.StackConfig.Name
                    : string.Format("{0} - {1}", _configManager.StackConfig.Name, ctx.ViewBag.Header);

                if (string.IsNullOrEmpty(ctx.ViewBag.SubHeading))
                {
                    ctx.ViewBag.SubHeading = "";
                }

                ctx.ViewBag.Pools      = _poolManager;
                ctx.ViewBag.Feed       = _configManager.WebServerConfig.Feed;
                ctx.ViewBag.LastUpdate = _statisticsManager.LastUpdate.ToString("HH:mm:ss tt zz"); // last statistics update.
            };

            CustomErrors.Enable(pipelines, new ErrorConfiguration());
        }
Ejemplo n.º 2
0
        public async Task <IActionResult> OnPostAsync(
            [FromServices] UserManager <IdentityUser> userManager,
            [FromServices] SignInManager <IdentityUser> signInManager)
        {
            if (!ModelState.IsValid)
            {
                return(Page());
            }

            var existingUser = await userManager.FindByNameAsync(Form.Username);

            if (existingUser != null)
            {
                CustomErrors.Add("Username already taken.");
                return(Page());
            }

            var user = await userManager.FindByNameAsync(Form.Email);

            var resetPasswordResult = await userManager.ResetPasswordAsync(user, Form.Code, Form.Password);

            if (resetPasswordResult.Succeeded)
            {
                user.UserName = Form.Username;
                await userManager.UpdateAsync(user);

                await signInManager.SignInAsync(user, true);

                return(Redirect(Form.ReturnUrl));
            }

            CustomErrors.Add("Failed to create account.");

            return(Page());
        }
        public async Task <IActionResult> OnPostAsync(
            [FromServices] UserManager <IdentityUser> userManager,
            [FromServices] SignInManager <IdentityUser> signInManager)
        {
            if (!ModelState.IsValid)
            {
                return(Page());
            }

            var user = new IdentityUser(Form.Username)
            {
                Email = Form.Email
            };

            var createUserResult = await userManager.CreateAsync(user, Form.Password);

            if (createUserResult.Succeeded)
            {
                await signInManager.SignInAsync(user, true);

                return(Redirect(Form.ReturnUrl));
            }

            foreach (var error in createUserResult.Errors)
            {
                CustomErrors.Add(error.Description);
            }

            return(Page());
        }
Ejemplo n.º 4
0
 public object GetById(int id)
 {
     if (BasicHttpAuth.IsAuthorized())
     {
         Article article;
         try
         {
             article = _articleService.GetById(id);
         }
         catch
         {
             throw new HttpResponseException(CustomErrors.CreateErrorMessage(StatusErrorCodes.ServerError, HttpStatusCode.InternalServerError));
         }
         if (article == null)
         {
             throw new HttpResponseException(CustomErrors.CreateErrorMessage(StatusErrorCodes.RecordNotFound, HttpStatusCode.NotFound));
         }
         return(new ArticleServiceSuccessVM()
         {
             Article = ArticleMappers.MapToVM(article), Total_elements = 1
         });
     }
     else
     {
         throw new HttpResponseException(CustomErrors.CreateErrorMessage(StatusErrorCodes.NotAuthorized, HttpStatusCode.Unauthorized));
     }
 }
Ejemplo n.º 5
0
        private async Task <Result> IsOrderValid(Order order)
        {
            //  var isCustomerExist = await _customerRepository.IsExists(order.CustomerId);
            // if (!isCustomerExist)
            //  {
            //     return Result.Fail(CustomErrors.CustomerByGivenIdNotExists);
            // }

            foreach (var orderItem in order.OrderItems)
            {
                var product = await _productRepository.FindById(orderItem.ProductId);

                if (product == null)
                {
                    return(Result.Fail(CustomErrors.NotExistByGivenId));
                }

                if (orderItem.Quantity >= product.AvailableQuantity)
                {
                    return(Result.Fail(new Error(CustomErrors.NotEnoughProductsInStore(
                                                     product.Name,
                                                     orderItem.Quantity,
                                                     product.AvailableQuantity))));
                }
            }

            return(Result.Ok());
        }
Ejemplo n.º 6
0
        internal /*public*/ static string GetErrorText()
        {
            HttpContext context = HttpContext.Current;

            if (CustomErrors.GetSettings(context).CustomErrorsEnabled(context.Request))
            {
                if (_strErrorTextRemote != null)
                {
                    return(_strErrorTextRemote);
                }

                lock (_syncObjectRemote) {
                    if (_strErrorTextRemote == null)
                    {
                        _strErrorTextRemote = (new UrlAuthFailedErrorFormatter()).GetHtmlErrorMessage(true);
                    }
                }

                return(_strErrorTextRemote);
            }


            if (_strErrorTextLocal != null)
            {
                return(_strErrorTextLocal);
            }

            lock (_syncObjectLocal) {
                if (_strErrorTextLocal == null)
                {
                    _strErrorTextLocal = (new UrlAuthFailedErrorFormatter()).GetHtmlErrorMessage(false);
                }
            }
            return(_strErrorTextLocal);
        }
Ejemplo n.º 7
0
        public async Task <IHttpActionResult> RepeatSubCalendarEvent([FromBody] getEventModel repeatSubEventRequestData)
        {
            this.authenticateUser(repeatSubEventRequestData);
            UserAccount retrievedUser = await repeatSubEventRequestData.getUserAccount(db);

            await retrievedUser.Login();

            retrievedUser.getTilerUser().updateTimeZoneTimeSpan(repeatSubEventRequestData.getTimeSpan);
            PostBackData    retValue = new PostBackData("", 1);
            DateTimeOffset  refNow   = repeatSubEventRequestData.getRefNow();
            DB_UserActivity activity = new DB_UserActivity(refNow, UserActivity.ActivityType.Repeat);
            JObject         json     = JObject.FromObject(repeatSubEventRequestData);

            activity.updateMiscelaneousInfo(json.ToString());
            if (retrievedUser.Status)
            {
                string CalendarType = repeatSubEventRequestData.ThirdPartyType.ToLower();

                switch (CalendarType)
                {
                case "google":
                {
                    CustomErrors error = new CustomErrors(CustomErrors.Errors.TilerConfig_Repeat_Third_Party);
                    retValue = new PostBackData(error);
                }
                break;

                case "tiler":
                {
                    HashSet <string> calendarIds = new HashSet <string>()
                    {
                        repeatSubEventRequestData.EventID
                    };
                    Task <Tuple <ThirdPartyControl.CalendarTool, IEnumerable <CalendarEvent> > > thirdPartyDataTask = ScheduleController.updatemyScheduleWithGoogleThirdpartyCalendar(retrievedUser.UserID, db);
                    DB_Schedule schedule = new DB_Schedule(retrievedUser, refNow, repeatSubEventRequestData.getCurrentLocation(), retrievalOptions: DataRetrievalSet.scheduleManipulationWithUpdateHistory, calendarIds: calendarIds);
                    schedule.CurrentLocation = repeatSubEventRequestData.getCurrentLocation();
                    var thirdPartyData = await thirdPartyDataTask.ConfigureAwait(false);

                    schedule.updateDataSetWithThirdPartyData(thirdPartyData);
                    activity.eventIds.Add(repeatSubEventRequestData.EventID);
                    retrievedUser.ScheduleLogControl.updateUserActivty(activity);
                    schedule.RepeatEvent(repeatSubEventRequestData.EventID, schedule.CurrentLocation);
                    await schedule.WriteFullScheduleToLog().ConfigureAwait(false);

                    retValue = new PostBackData("\"Success\"", 0);
                }
                break;

                default:
                    break;
                }
            }

            await AnalysisController.updateSuggestionAnalysis(retrievedUser.ScheduleLogControl).ConfigureAwait(false);

            TilerFront.SocketHubs.ScheduleChange scheduleChangeSocket = new TilerFront.SocketHubs.ScheduleChange();
            scheduleChangeSocket.triggerRefreshData(retrievedUser.getTilerUser());
            return(Ok(retValue.getPostBack));
        }
        public void Should_add_error_hook_when_enabled()
        {
            var pipelines = Substitute.For <IPipelines>();

            pipelines.OnError.Returns(Substitute.For <ErrorPipeline>());

            CustomErrors.Enable(pipelines, Substitute.For <CustomErrorsConfiguration>());

            pipelines.OnError.Received(1).AddItemToEndOfPipeline(Arg.Any <Func <NancyContext, Exception, Response> >());
        }
        public async Task <IActionResult> Post([FromBody] UserDto userDto)
        {
            var customErrors = new CustomErrors();

            if (userDto.id_role.ToString() == null || userDto.id_role == 0)
            {
                userDto.id_role = _rolesService.GetRoleByName("Anonimo").Result.Id;
            }
            if (userDto.id_country.ToString() == null || userDto.id_country == 0)
            {
                userDto.id_country = _countryService.GetCountryByName("Ecuador").Result.Id;
            }
            if (userDto.id_enterprise.ToString() == null || userDto.id_enterprise == 0)
            {
                userDto.id_enterprise = _enterpriseService.GetEnterpriseByName("Dummy").Result.Id;
            }
            if (userDto.phone_number == null || userDto.phone_number == "")
            {
                userDto.phone_number = "N/A";
            }
            if (userDto.profile_picture == null || userDto.profile_picture == "")
            {
                userDto.profile_picture = "N/A";
            }
            if (await _userService.CheckDuplicatedEmail(userDto.email))
            {
                customErrors.messages.Add("Email se encuentra en uso");
            }
            if (await _userService.CheckDuplicatedNickname(userDto.nickname))
            {
                customErrors.messages.Add("Nickname se encuentra en uso");
            }
            if (await _userService.CheckDuplicatedPhone(userDto.phone_number))
            {
                customErrors.messages.Add("Telefono se encuentra en uso");
            }
            if (customErrors.messages.Count > 0)
            {
                return(Ok(customErrors));
            }
            var user = _mapper.Map <User>(userDto);

            user.hashPassword = _passwordService.Hash(user.hashPassword);
            user = await _userService.InsertUser(user);

            var activationUrl = _uriService.GetActivationUri(Url.RouteUrl(nameof(ActivateAccount))).ToString() + _routingService.GetRoute() + $"api/User/activateAccount?activationCode={user.activation_code}";

            _userService.SendMail(user.activation_code, user.email, activationUrl);
            user.hashPassword = null;
            userDto           = _mapper.Map <UserDto>(user);
            var response = new ApiResponse <UserDto>(userDto);

            return(Ok(response));
        }
        public ErrorStatusCodeHandlerFixture()
        {
            configuration = new CustomErrorsConfiguration();

            browser = new Browser(new ConfigurableBootstrapper(with =>
            {
                with.ApplicationStartup((container, pipelines) => CustomErrors.Enable(pipelines, configuration));
                with.Module <TestModule>();
                with.StatusCodeHandler <ErrorStatusCodeHandler>();
            }));
        }
Ejemplo n.º 11
0
 public PostBackData(CustomErrors Error)
 {
     Status = 0;
     Data   = "Success";
     if (Error != null)
     {
         Data    = Error.Message;
         Message = Error.Message;
         Status  = Error.Code;
     }
 }
Ejemplo n.º 12
0
        protected override void ApplicationStartup(TinyIoCContainer container, IPipelines pipelines)
        {
            var configManager = container.Resolve <IConfigManager>();

            // todo: enable authentication support
            if (configManager.WebServerConfig.Backend.MetricsEnabled)
            {
                Metric.Config.WithNancy(config => config.WithMetricsModule("/admin/metrics"));
            }

            CustomErrors.Enable(pipelines, new ErrorConfiguration());
        }
        private void WriteErrorMessage(HttpContext context)
        {
            CustomErrors customErrorsSetting = CustomErrors.GetSettings(context);

            if (!customErrorsSetting.CustomErrorsEnabled(context.Request))
            {
                context.Response.Write((new FileAccessFailedErrorFormatter(context.Request.PhysicalPathInternal)).GetHtmlErrorMessage(false));
            }
            else
            {
                context.Response.Write((new FileAccessFailedErrorFormatter(null)).GetHtmlErrorMessage(true));
            }
        }
Ejemplo n.º 14
0
        protected override void ApplicationStartup(ILifetimeScope container, IPipelines pipelines)
        {
            base.ApplicationStartup(container, pipelines);

            ClientAppSettings.Enable(pipelines);
            Elmahlogging.Enable(pipelines, "elmah");
            CustomErrors.Enable(pipelines, new ErrorHandlingConfiguration());
            FormsAuthentication.Enable(pipelines, new FormsAuthenticationConfiguration
            {
                RedirectUrl = "~/login",
                UserMapper  = container.Resolve <IUserMapper>()
            });
        }
Ejemplo n.º 15
0
        public async Task <IHttpActionResult> DeleteCalEvent([FromBody] getEventModel myUser)
        {
            this.authenticateUser(myUser);
            UserAccount retrievedUser = await myUser.getUserAccount(db);// new UserAccount(myUser.UserName, myUser.UserID);

            await retrievedUser.Login();

            retrievedUser.getTilerUser().updateTimeZoneTimeSpan(myUser.getTimeSpan);
            PostBackData retValue;

            if (retrievedUser.Status)
            {
                HashSet <string> calendarIds = new HashSet <string>()
                {
                    myUser.EventID
                };
                Task <Tuple <ThirdPartyControl.CalendarTool, IEnumerable <CalendarEvent> > > thirdPartyDataTask = ScheduleController.updatemyScheduleWithGoogleThirdpartyCalendar(retrievedUser.UserID, db);
                DB_Schedule schedule = new DB_Schedule(retrievedUser, myUser.getRefNow(), myUser.getCurrentLocation(), calendarIds: calendarIds);
                schedule.CurrentLocation = myUser.getCurrentLocation();
                var thirdPartyData = await thirdPartyDataTask.ConfigureAwait(false);

                schedule.updateDataSetWithThirdPartyData(thirdPartyData);
                DB_UserActivity activity = new DB_UserActivity(myUser.getRefNow(), UserActivity.ActivityType.DeleteCalendarEvent, new List <String>()
                {
                    myUser.EventID
                });
                JObject json = JObject.FromObject(myUser);
                activity.updateMiscelaneousInfo(json.ToString());
                retrievedUser.ScheduleLogControl.updateUserActivty(activity);
                CustomErrors messageReturned = await schedule.deleteCalendarEventAndReadjust(myUser.EventID).ConfigureAwait(false);

                await schedule.WriteFullScheduleToLog().ConfigureAwait(false);

                int errorCode = messageReturned?.Code ?? 0;
                retValue = new PostBackData(messageReturned, errorCode);
            }
            else
            {
                retValue = new PostBackData("", 1);
            }

            TilerFront.SocketHubs.ScheduleChange scheduleChangeSocket = new TilerFront.SocketHubs.ScheduleChange();
            await AnalysisController.updateSuggestionAnalysis(retrievedUser.ScheduleLogControl).ConfigureAwait(false);

            scheduleChangeSocket.triggerRefreshData(retrievedUser.getTilerUser());
            return(Ok(retValue.getPostBack));
        }
 public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
 {
     if (!context.ModelState.IsValid)
     {
         CustomErrors cErrors = new CustomErrors();
         foreach (var modelState in context.ModelState)
         {
             foreach (var errors in modelState.Value.Errors)
             {
                 cErrors.messages.Add(errors.ErrorMessage);
             }
         }
         context.Result = new BadRequestObjectResult(cErrors);
         return;
     }
     await next();
 }
        public async Task <IActionResult> OnPostAsync([FromServices] SignInManager <IdentityUser> signInManager)
        {
            if (!ModelState.IsValid)
            {
                return(Page());
            }

            var signInResult = await signInManager
                               .PasswordSignInAsync(Form.Username, Form.Password, true, false);

            if (signInResult.Succeeded)
            {
                return(Redirect(Form.ReturnUrl));
            }

            CustomErrors.Add("Invalid login attempt, please try again.");

            return(Page());
        }
Ejemplo n.º 18
0
        // Method for registering in -> when we submit the form
        // DI at method level, injecting SignInManager & UserManager for User
        // UserManager is a service -> come from Startup -> AddIdentity
        // SignInManager is a service -> come from Startup -> AddIdentity
        public async Task <IActionResult> OnPostAsync(
            [FromServices] UserManager <IdentityUser> userManager,
            [FromServices] SignInManager <IdentityUser> signInManager
            )
        {
            // If register form is invalid, return that page again => user did not provide valid email || password
            if (!ModelState.IsValid)
            {
                return(Page());
            }

            // Created a User, with Username -> what he typed in the form
            var user = new IdentityUser(Form.Username)
            {
                // Adding email from form to user object as-well
                Email = Form.Email
            };

            // Creates user in store with user manager, based on identity (username included) user and password from form
            var createUserResult = await userManager.CreateAsync(user, Form.Password);

            // If creation succeeded
            if (createUserResult.Succeeded)
            {
                // Sign the User in
                await signInManager.SignInAsync(user, true);

                // If signInResult succeeded we want to pop user back on from where he came from, returnUrl contains all the info
                // that server need to redirect us back to the App
                return(Redirect(Form.ReturnUrl));
            }

            // Loop over errors in createUserResult -> when we try to create user and he fked up or didnt filled form correctly
            foreach (var error in createUserResult.Errors)
            {
                // Adding to our List of errors, error (it's description -> describes what error is) that popped for the reason above
                CustomErrors.Add(error.Description);
            }

            return(Page());
        }
Ejemplo n.º 19
0
        // Method for loging in -> when we submit the form => press the Log In button
        // DI at method level, injecting SignInManager for User
        // SignInManager is a service -> come from Startup -> AddIdentity
        public async Task <IActionResult> OnPostAsync([FromServices] SignInManager <IdentityUser> signInManager)
        {
            // If login form is invalid, return that page again => user did not provide valid username || password
            if (!ModelState.IsValid)
            {
                return(Page());
            }

            // Attempts to sign in the specified userName and password combination, if we close it's gonna persist, no lockout on failures
            // Providing username and pass from form to -> PasswordSignInAsync
            var signInResult = await signInManager.PasswordSignInAsync(Form.Username, Form.Password, true, false);

            if (signInResult.Succeeded)
            {
                return(Redirect(Form.ReturnUrl));
            }

            // Add this particular error to our List, dont provide details coz of hacking possibilities
            CustomErrors.Add("Invalid login attempt, please try again.");

            return(Page());
        }
Ejemplo n.º 20
0
 public object Get()
 {
     if (BasicHttpAuth.IsAuthorized())
     {
         try
         {
             var stores = new StoreService().GetAll();
             return(new StoreServiceSuccessVM()
             {
                 Stores = stores, Total_elements = stores.Count
             });
         }
         catch
         {
             throw new HttpResponseException(CustomErrors.CreateErrorMessage(StatusErrorCodes.ServerError, HttpStatusCode.InternalServerError));
         }
     }
     else
     {
         throw new HttpResponseException(CustomErrors.CreateErrorMessage(StatusErrorCodes.NotAuthorized, HttpStatusCode.Unauthorized));
     }
 }
Ejemplo n.º 21
0
 public object Get()
 {
     if (BasicHttpAuth.IsAuthorized())
     {
         try
         {
             var articles = _articleService.GetAll();
             return(new ArticlesServiceSuccessVM()
             {
                 Articles = articles.Select(x => ArticleMappers.MapToVM(x)).ToList(), Total_elements = articles.Count
             });
         }
         catch
         {
             throw new HttpResponseException(CustomErrors.CreateErrorMessage(StatusErrorCodes.ServerError, HttpStatusCode.InternalServerError));
         }
     }
     else
     {
         throw new HttpResponseException(CustomErrors.CreateErrorMessage(StatusErrorCodes.NotAuthorized, HttpStatusCode.Unauthorized));
     }
 }
Ejemplo n.º 22
0
        string getErrorMessage(int errorCode)
        {
            string retValue;
            string defaultMessage = "Tiler is having some issues please try again later";

            if (errorCode > 0 && errorCode < 20000000)
            {
                retValue = string.IsNullOrEmpty(Message) || string.IsNullOrWhiteSpace(Message) ?  defaultMessage : Message;
                return(retValue);
            }

            if (string.IsNullOrEmpty(Message))
            {
                if (errorDictionary.ContainsKey(errorCode))
                {
                    retValue = errorDictionary[errorCode];
                }
                else
                {
                    if (CustomErrors.errorCodeHasMessage(errorCode))
                    {
                        retValue = CustomErrors.getErrorMessage(errorCode);
                    }
                    else
                    {
                        retValue = defaultMessage;
                    }
                }
            }
            else
            {
                retValue = Message;
            }

            return(retValue);
        }
Ejemplo n.º 23
0
 protected override void ApplicationStartup(TinyIoCContainer container, IPipelines pipelines)
 {
     StaticConfiguration.EnableRequestTracing = true;
     CustomErrors.Enable(pipelines, new ErrorConfiguration());
 }
Ejemplo n.º 24
0
        public async Task <IHttpActionResult> SubeventEdit([FromBody] EditSubEventWhatIfModel SubEventEdit)
        {
            UserAccount retrievedUser = await SubEventEdit.getUserAccount(db);

            await retrievedUser.Login();

            retrievedUser.getTilerUser().updateTimeZoneTimeSpan(SubEventEdit.getTimeSpan);
            PostBackData returnPostBack;

            if (retrievedUser.Status)
            {
                int            SplitCount   = (int)SubEventEdit.Split;
                long           StartLong    = Convert.ToInt64(SubEventEdit.Start);
                long           EndLong      = Convert.ToInt64(SubEventEdit.End);
                long           LongBegin    = Convert.ToInt64(SubEventEdit.CalStart);
                long           LongDeadline = Convert.ToInt64(SubEventEdit.CalEnd);
                DateTimeOffset newStart     = TilerElementExtension.JSStartTime.AddMilliseconds(StartLong);
                DateTimeOffset newEnd       = TilerElementExtension.JSStartTime.AddMilliseconds(EndLong);
                DateTimeOffset Begin        = TilerElementExtension.JSStartTime.AddMilliseconds(LongBegin);
                if (LongBegin == 0)
                {
                    Begin = Utility.BeginningOfTime;
                }

                DateTimeOffset Deadline = TilerElementExtension.JSStartTime.AddMilliseconds(LongDeadline);
                if (LongDeadline == 0)
                {
                    Deadline = Utility.BeginningOfTime;
                }


                DateTimeOffset         now = SubEventEdit.getRefNow();
                DB_Schedule            schedule;
                Tuple <Health, Health> evaluation;

                string CalendarType = SubEventEdit.ThirdPartyType.ToLower();
                switch (CalendarType)
                {
                case "google":
                {
                    Models.ThirdPartyCalendarAuthenticationModel AllIndexedThirdParty = await ScheduleController.getThirdPartyAuthentication(retrievedUser.UserID, SubEventEdit.ThirdPartyUserID, "Google", db);

                    GoogleTilerEventControl googleControl = new GoogleTilerEventControl(AllIndexedThirdParty, db);
                    await googleControl.updateSubEvent(SubEventEdit).ConfigureAwait(false);

                    Dictionary <string, CalendarEvent> AllCalendarEvents = (await googleControl.getCalendarEvents(null, true).ConfigureAwait(false)).ToDictionary(obj => obj.getId, obj => obj);
                    GoogleThirdPartyControl            googleEvents      = new GoogleThirdPartyControl(AllCalendarEvents, AllIndexedThirdParty.getTilerUser());
                    DB_UserActivity activity = new DB_UserActivity(now, UserActivity.ActivityType.ThirdPartyUpdate);
                    retrievedUser.ScheduleLogControl.updateUserActivty(activity);
                    Task <Tuple <ThirdPartyControl.CalendarTool, IEnumerable <CalendarEvent> > > thirdPartyDataTask = ScheduleController.updatemyScheduleWithGoogleThirdpartyCalendar(retrievedUser.UserID, db);
                    schedule = new DB_Schedule(retrievedUser, now, SubEventEdit.getCurrentLocation());
                    var thirdPartyData = await thirdPartyDataTask.ConfigureAwait(false);

                    schedule.updateDataSetWithThirdPartyData(thirdPartyData);
                    evaluation = await schedule.TimeStone.EventUpdate().ConfigureAwait(false);
                }
                break;

                case "tiler":
                {
                    HashSet <string> calendarIds = new HashSet <string>()
                    {
                        SubEventEdit.EventID
                    };
                    Task <Tuple <ThirdPartyControl.CalendarTool, IEnumerable <CalendarEvent> > > thirdPartyDataTask = ScheduleController.updatemyScheduleWithGoogleThirdpartyCalendar(retrievedUser.UserID, db);
                    var retrievalOption = DataRetrievalSet.scheduleManipulation;
                    retrievalOption.Add(DataRetrivalOption.TimeLineHistory);

                    schedule = new DB_Schedule(retrievedUser, now, SubEventEdit.getCurrentLocation(), calendarIds: calendarIds, retrievalOptions: retrievalOption);
                    var thirdPartyData = await thirdPartyDataTask.ConfigureAwait(false);

                    schedule.updateDataSetWithThirdPartyData(thirdPartyData);
                    schedule.CurrentLocation = SubEventEdit.getCurrentLocation();
                    evaluation = await schedule.TimeStone.EventUpdate(
                        newStart,
                        newEnd,
                        Begin,
                        Deadline,
                        SplitCount,
                        SubEventEdit.EventID
                        ).ConfigureAwait(false);
                }
                break;

                default:
                    CustomErrors error = new CustomErrors(CustomErrors.Errors.Preview_Calendar_Type_Not_Supported);
                    returnPostBack = new PostBackData(error);
                    return(Ok(returnPostBack.getPostBack));
                }



                JObject before = evaluation.Item1.ToJson();
                JObject after  = evaluation.Item2.ToJson();

                HealthComparison healthComparison = new HealthComparison(evaluation.Item1, evaluation.Item2);
                var     delta     = healthComparison.delta();
                JObject deltaJson = new JObject();
                deltaJson.Add("conflictDeltaCount", delta.Item1);
                deltaJson.Add("tardyDeltaCount", delta.Item2);

                JObject resultData = new JObject();
                resultData.Add("before", before);
                resultData.Add("after", after);
                resultData.Add("delta", deltaJson);
                returnPostBack = new PostBackData(resultData, 0);
                return(Ok(returnPostBack.getPostBack));
            }
            else
            {
                returnPostBack = new PostBackData("", 1);
            }

            return(Ok(returnPostBack.getPostBack));
        }
 public void Should_throw_with_null_configuration_passed_to_enable()
 {
     Assert.Throws <ArgumentNullException>(() => CustomErrors.Enable(Substitute.For <IPipelines>(), null));
 }
 public void Should_throw_with_null_pipelines_passed_to_enable()
 {
     Assert.Throws <ArgumentNullException>(() => CustomErrors.Enable(null, new CustomErrorsConfiguration()));
 }
Ejemplo n.º 27
0
        protected override void ApplicationStartup(Nancy.TinyIoc.TinyIoCContainer container, Nancy.Bootstrapper.IPipelines pipelines)
        {
            base.ApplicationStartup(container, pipelines);

            CustomErrors.Enable(pipelines, new ErrorConfiguration());
        }
Ejemplo n.º 28
0
        public async Task <IHttpActionResult> UpdateCalEvent([FromBody] EditSubCalEventModel editSubEventRequest)
        {
            this.authenticateUser(editSubEventRequest);
            UserAccount retrievedUser = await editSubEventRequest.getUserAccount(db);

            await retrievedUser.Login();

            retrievedUser.getTilerUser().updateTimeZoneTimeSpan(editSubEventRequest.getTimeSpan);
            PostBackData retValue = new PostBackData("", 1);

            if (retrievedUser.Status)
            {
                string CalendarType = editSubEventRequest.ThirdPartyType.ToLower();
                switch (CalendarType)
                {
                case "google":
                {
                    DateTimeOffset myNow           = editSubEventRequest.getRefNow();
                    var            retrievalOption = DataRetrievalSet.scheduleManipulation;
                    retrievalOption.Add(DataRetrivalOption.TimeLineHistory);
                    DB_Schedule NewSchedule = new DB_Schedule(retrievedUser, myNow, editSubEventRequest.getCurrentLocation(), retrievalOption);
                    NewSchedule.CurrentLocation = editSubEventRequest.getCurrentLocation();
                    Models.ThirdPartyCalendarAuthenticationModel AllIndexedThirdParty = await ScheduleController.getThirdPartyAuthentication(retrievedUser.UserID, editSubEventRequest.ThirdPartyUserID, "Google", db);

                    GoogleTilerEventControl googleControl = new GoogleTilerEventControl(AllIndexedThirdParty, db);
                    await googleControl.updateSubEvent(editSubEventRequest).ConfigureAwait(false);

                    Dictionary <string, CalendarEvent> AllCalendarEvents = (await googleControl.getCalendarEvents(null, true).ConfigureAwait(false)).ToDictionary(obj => obj.getId, obj => obj);
                    GoogleThirdPartyControl            googleEvents      = new GoogleThirdPartyControl(AllCalendarEvents, AllIndexedThirdParty.getTilerUser());
                    DB_UserActivity activity = new DB_UserActivity(myNow, UserActivity.ActivityType.ThirdPartyUpdate);
                    retrievedUser.ScheduleLogControl.updateUserActivty(activity);

                    await NewSchedule.updateDataSetWithThirdPartyDataAndTriggerNewAddition(new Tuple <ThirdPartyControl.CalendarTool, IEnumerable <CalendarEvent> >(ThirdPartyControl.CalendarTool.google, new List <CalendarEvent> {
                            googleEvents.getThirdpartyCalendarEvent()
                        })).ConfigureAwait(false);

                    retValue = new PostBackData("\"Success\"", 0);
                }
                break;

                case "tiler":
                {
                    DateTimeOffset myNow = editSubEventRequest.getRefNow();
                    myNow = editSubEventRequest.getRefNow();
                    HashSet <string> calendarIds = new HashSet <string>()
                    {
                        editSubEventRequest.EventID
                    };
                    Task <Tuple <ThirdPartyControl.CalendarTool, IEnumerable <CalendarEvent> > > thirdPartyDataTask = ScheduleController.updatemyScheduleWithGoogleThirdpartyCalendar(retrievedUser.UserID, db);
                    DB_Schedule schedule = new DB_Schedule(retrievedUser, myNow, editSubEventRequest.getCurrentLocation(), retrievalOptions: DataRetrievalSet.scheduleManipulationWithUpdateHistory, calendarIds: calendarIds);
                    schedule.CurrentLocation = editSubEventRequest.getCurrentLocation();
                    var thirdPartyData = await thirdPartyDataTask.ConfigureAwait(false);

                    schedule.updateDataSetWithThirdPartyData(thirdPartyData);

                    long           StartLong    = Convert.ToInt64(editSubEventRequest.Start);
                    long           EndLong      = Convert.ToInt64(editSubEventRequest.End);
                    long           LongBegin    = Convert.ToInt64(editSubEventRequest.CalStart);
                    long           LongDeadline = Convert.ToInt64(editSubEventRequest.CalEnd);
                    DateTimeOffset newStart     = TilerElementExtension.JSStartTime.AddMilliseconds(StartLong);
                    DateTimeOffset newEnd       = TilerElementExtension.JSStartTime.AddMilliseconds(EndLong);
                    DateTimeOffset Begin        = TilerElementExtension.JSStartTime.AddMilliseconds(LongBegin);
                    if (LongBegin == 0)
                    {
                        Begin = Utility.BeginningOfTime;
                    }

                    DateTimeOffset Deadline = TilerElementExtension.JSStartTime.AddMilliseconds(LongDeadline);
                    if (LongDeadline == 0)
                    {
                        Deadline = Utility.BeginningOfTime;
                    }
                    int SplitCount = (int)editSubEventRequest.Split;
                    if (SplitCount >= 1)
                    {
                        SubCalendarEvent subEventedited = schedule.getSubCalendarEvent(editSubEventRequest.EventID);
                        Tuple <CustomErrors, Dictionary <string, CalendarEvent> > ScheduleUpdateMessage = await schedule.BundleChangeUpdate(editSubEventRequest.EventID, new EventName(retrievedUser.getTilerUser(), subEventedited, editSubEventRequest.EventName), newStart, newEnd, Begin, Deadline, SplitCount, editSubEventRequest.EscapedNotes).ConfigureAwait(false);

                        DB_UserActivity activity = new DB_UserActivity(myNow, UserActivity.ActivityType.InternalUpdate, new List <String>()
                            {
                                editSubEventRequest.EventID
                            });
                        retrievedUser.ScheduleLogControl.updateUserActivty(activity);
                        await schedule.persistToDB().ConfigureAwait(false);

                        //EventID eventId = new EventID(myUser.EventID);
                        //CalendarEvent calendarEvent = schedule.getCalendarEvent(eventId);
                        //SubCalendarEvent subEvent = calendarEvent.ActiveSubEvents.FirstOrDefault();
                        //SubCalEvent subCalEvent = subEvent.ToSubCalEvent(calendarEvent);
                        //JObject retSubEvent = new JObject();
                        //retSubEvent.Add("subEvent", JObject.FromObject(subCalEvent));
                        //retValue = new PostBackData(retSubEvent, 0);
                        retValue = new PostBackData();
                    }
                    else
                    {
                        CustomErrors error = new CustomErrors(CustomErrors.Errors.TilerConfig_Zero_SplitCount);
                        retValue = new PostBackData(error);
                    }
                }
                break;

                default:
                    break;
                }
            }
            await AnalysisController.updateSuggestionAnalysis(retrievedUser.ScheduleLogControl).ConfigureAwait(false);

            TilerFront.SocketHubs.ScheduleChange scheduleChangeSocket = new TilerFront.SocketHubs.ScheduleChange();
            scheduleChangeSocket.triggerRefreshData(retrievedUser.getTilerUser());
            return(Ok(retValue.getPostBack));
        }