Exemplo n.º 1
0
 public void AddParameter(string name, object value, Middleware.ParameterType type)
 {
     if (type == ParameterType.RequestBody)
     {
         Request.RequestFormat = DataFormat.Json;
         Request.AddParameter(name, JsonConvert.SerializeObject(value), (RestSharp.ParameterType)Enum.Parse(typeof(RestSharp.ParameterType), type.ToString()));
     }
     else
     {
         Request.AddParameter(name, value, (RestSharp.ParameterType)Enum.Parse(typeof(RestSharp.ParameterType), type.ToString()));
     }
 }
        RunExecuteMiddleware_should_call_error_handler_on_workflow_def_when_middleware_throws_and_def_has_handler()
        {
            // Arrange
            var middleware = BuildWorkflowMiddleware(WorkflowMiddlewarePhase.ExecuteWorkflow, 1);

            A.CallTo(HandleMethodFor(middleware)).ThrowsAsync(new ApplicationException("Something went wrong"));
            Middleware.AddRange(new[] { middleware });
            Definition.OnExecuteMiddlewareError = typeof(IDefLevelErrorHandler);

            // Act
            await Runner.RunExecuteMiddleware(Workflow, Definition);

            // Assert
            A
            .CallTo(HandleMethodFor(TopLevelErrorHandler))
            .MustNotHaveHappened();
            A
            .CallTo(HandleMethodFor(DefLevelErrorHandler))
            .MustHaveHappenedOnceExactly();
        }
Exemplo n.º 3
0
        public void ExecuteStep_should_bubble_up_exceptions_in_middleware()
        {
            // Arrange
            var middleware1 = BuildStepMiddleware(1);
            var middleware2 = BuildStepMiddleware(2);
            var middleware3 = BuildStepMiddleware(3);

            Middleware.AddRange(new[] { middleware1, middleware2, middleware3 });
            A
            .CallTo(HandleMethodFor(middleware2))
            .Throws(new ApplicationException("Failed"));

            // Act
            Func <Task <ExecutionResult> > action = async() => await Runner.ExecuteStep(Context, Body);

            // Assert
            action
            .ShouldThrow <ApplicationException>()
            .WithMessage("Failed");
        }
        public async Task RunExecuteMiddleware_should_only_run_middleware_in_ExecuteWorkflow_phase()
        {
            // Arrange
            var executeMiddleware = BuildWorkflowMiddleware(WorkflowMiddlewarePhase.ExecuteWorkflow, 1);
            var postMiddleware    = BuildWorkflowMiddleware(WorkflowMiddlewarePhase.PostWorkflow, 2);
            var preMiddleware     = BuildWorkflowMiddleware(WorkflowMiddlewarePhase.PreWorkflow, 3);

            Middleware.AddRange(new[] { preMiddleware, postMiddleware, executeMiddleware });

            // Act
            await Runner.RunExecuteMiddleware(Workflow, Definition);

            // Assert
            A
            .CallTo(HandleMethodFor(executeMiddleware))
            .MustHaveHappenedOnceExactly();

            A.CallTo(HandleMethodFor(preMiddleware)).MustNotHaveHappened();
            A.CallTo(HandleMethodFor(postMiddleware)).MustNotHaveHappened();
        }
Exemplo n.º 5
0
 public async Task <IActionResult> Edit(int id, [Bind("ID,Name,Email,Password,Avatar,Phone,Address,Status")] Staf staf, IFormFile ful)
 {
     Middleware.CheckStafLogin(HttpContext);
     if (id != staf.ID)
     {
         return(NotFound());
     }
     if (ModelState.IsValid)
     {
         try
         {
             if (ful != null)
             {
                 var tenImg = staf.ID + "." + ful.FileName.Split(".")[ful.FileName.Split(".").Length - 1];
                 var path   = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/Uploads/Staf", staf.Avatar);
                 System.IO.File.Delete(path);
                 path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/Uploads/Staf", tenImg);
                 using (var stream = new FileStream(path, FileMode.Create))
                 {
                     await ful.CopyToAsync(stream);
                 }
                 staf.Avatar = tenImg;
             }
             _context.Update(staf);
             await _context.SaveChangesAsync();
         }
         catch (DbUpdateConcurrencyException)
         {
             if (!StafExists(staf.ID))
             {
                 return(NotFound());
             }
             else
             {
                 throw;
             }
         }
         return(RedirectToAction(nameof(Index)));
     }
     return(View(staf));
 }
Exemplo n.º 6
0
        public static void Main(string [] args)
        {
            var store = new Store <int> ((state, action) =>
            {
                if (action is int)
                {
                    return((int)action);
                }
                if (action is string && (string)action == "+")
                {
                    return(state + 1);
                }
                if (action is string && (string)action == "-")
                {
                    return(state - 1);
                }

                return(state);
            }, 10);

            Console.WriteLine($"Initial state = {store.State}");

            store.Subscribe += number => Console.WriteLine($"State changed to {number}");
            store.Dispatch("+");
            store.Dispatch("-");
            store.Dispatch(8);
            store.Dispatch("-");
            store.Dispatch("-");

            Middleware <int> m = (state) => next => action =>
            {
                Console.WriteLine("Hello");
                var result = next(action);
                return(result);
            };

            var store2 = Store <int> .CreateStore((state, action) => state, 0,
                                                  Store <int> .ApplyMiddleware(m));

            store2.Dispatch(null);
        }
        public MessagePublishContextMiddleware(PublishContextActions actions)
        {
            _internalMiddleware = new Middleware <MessagePublishContext <T> >();

            //if (actions.LoggingAction != null) _internalMiddleware.Add(actions.LoggingAction);
            if (actions.ApmAction != null)
            {
                _internalMiddleware.Add(MakeGeneric <T>(actions.ApmAction));
            }
            if (actions.PrepareMessageContextForPublish != null)
            {
                _internalMiddleware.Add(MakeGeneric <T>(actions.PrepareMessageContextForPublish));
            }

            foreach (var customAction in actions.CustomActions)
            {
                _internalMiddleware.Add(MakeGeneric <T>(customAction));
            }

            _internalMiddleware.Add(MakeGeneric <T>(actions.InvokePublisherAction));
        }
Exemplo n.º 8
0
        // GET: Admin/Movie_Show/Details/5
        public async Task <IActionResult> Details(int?id)
        {
            Middleware.CheckStafLogin(HttpContext);
            if (id == null)
            {
                return(NotFound());
            }

            var movie_Show = await _context.Movie_Shows
                             .Include(m => m.Movie)
                             .Include(m => m.Room)
                             .Include(m => m.Room.Cinema)
                             .FirstOrDefaultAsync(m => m.ID == id);

            if (movie_Show == null)
            {
                return(NotFound());
            }

            return(View(movie_Show));
        }
Exemplo n.º 9
0
        public BaseHandlerSubscriber(Type handlerType, Middleware <HandleContext> handlerMiddleware, string subscriberId = null)
        {
            if (ReferenceEquals(null, handlerType))
            {
                throw new ArgumentNullException(nameof(handlerType));
            }
            if (ReferenceEquals(null, handlerMiddleware))
            {
                throw new ArgumentNullException(nameof(handlerMiddleware));
            }

            this.handlerType       = handlerType;
            this.handlerMiddleware = handlerMiddleware;
            var expectedHandlerType = typeof(T);

            if (expectedHandlerType.IsAssignableFrom(handlerType) == false)
            {
                throw new ArgumentException($"'{handlerType.FullName}' does not implement {expectedHandlerType.FullName}");
            }
            Id = subscriberId ?? handlerType.FullName;
        }
Exemplo n.º 10
0
        public static async Task ShowIn(ViewStack viewStack)
        {
            // Call model unit tests manually before the UI is shown:
            CellsModelTests.TestFromAndToRowName();
            CellsModelTests.TestDataStoreTransitiveChanges();

            CellsModel model = new CellsModel(ImmutableDictionary <CellPos, Cell> .Empty);
            Middleware <CellsModel>      logging   = Middlewares.NewLoggingMiddleware <CellsModel>();
            UndoRedoReducer <CellsModel> undoLogic = new UndoRedoReducer <CellsModel>();
            DataStore <CellsModel>       store     = new DataStore <CellsModel>(undoLogic.Wrap(CellsReducers.MainReducer), model, logging);

            MyPresenter presenter = new MyPresenter();

            presenter.targetView = viewStack.ShowView("7GUIs_Task7_Cells");
            await presenter.LoadModelIntoView(store);

            await TaskV2.Delay(2000);

            Toast.Show("Now simulating some table model changes..");
            // Simulate changes in the model to check if the UI updates correctly:
            CellsModelTests.SimulateSomeChangesInModel(store);
        }
Exemplo n.º 11
0
        public async override Task Execute(IJobExecutionContext context)
        {
            try
            {
                var result = new HeartBeat(Settings.App.Id);

                try
                {
                    var test = await Health.Test();

                    if (test != null)
                    {
                        if (!test.Status)
                            result.Errors.Add(test.Text);
                    }
                    else
                        throw new Exception("health check failed");
                }
                catch (Exception exception)
                {
                    result.Errors.Add("health check failed");
                    result.Errors.Add(exception.ToString());
                }

                await Execute(result);

                var timeout = 60000;

                if (context.PreviousFireTimeUtc.HasValue && context.NextFireTimeUtc.HasValue)
                    timeout = (int)context.NextFireTimeUtc.Value.Subtract(context.PreviousFireTimeUtc.Value).TotalMilliseconds;

                if (Middleware.Connected)
                    await Middleware.Send(result, timeout);
            }
            catch (Exception e)
            {
                Logger.Error(e);
            }
        }
Exemplo n.º 12
0
        // GET: Employees/Details/5
        public async Task <IActionResult> Details(int id)
        {
            if (id == null)
            {
                return(NotFound());
            }

            var      context  = new SqlLiteContext();
            Employee employee = await context.Employees
                                .FirstOrDefaultAsync(m => m.EmployeeId == id);

            if (employee == null)
            {
                return(NotFound());
            }

            CvViewModel CompleteCv      = new CvViewModel();
            Assigment   assigment       = new Assigment();
            Assigment   focusassingment = new Assigment();

            Expertise  expertise  = new Expertise();
            Middleware middelware = new Middleware();
            Training   training   = new Training();
            Trade      trade      = new Trade();
            Technique  tech       = new Technique();


            CompleteCv.Employee        = employee.GetEmployeeView(employee);
            CompleteCv.Expertises      = expertise.GetExpertiseView(id);
            CompleteCv.Middlewares     = middelware.GetMiddlewareView(id);
            CompleteCv.Techniques      = tech.GetTechniqueView(id);
            CompleteCv.Trades          = trade.GetTradeView(id);
            CompleteCv.DegreeTraining  = training.GetDegreeTrainingView(id);
            CompleteCv.Trainings       = training.GetTrainingView(id);
            CompleteCv.Assigments      = assigment.GetAllNonFocusAssignments(id);
            CompleteCv.FocusAssigments = focusassingment.GetAllFocusAssignments(id);

            return(View(CompleteCv));
        }
Exemplo n.º 13
0
        public async Task <IActionResult> Create([Bind("ID,Start_Show,Status,Room_ID,Movie_ID")] Movie_Show movie_Show)
        {
            Middleware.CheckStafLogin(HttpContext);
            var room = _context.Rooms.Where(m => m.ID.Equals(movie_Show.Room_ID)).First();

            if (ModelState.IsValid)
            {
                var listShowInRoom = _context.Movie_Shows.Where(s => s.Room_ID.Equals(movie_Show.Room_ID)).Where(s => s.Start_Show.Date.Equals(movie_Show.Start_Show.Date)).ToList();
                var movie          = _context.Movies.Where(s => s.ID.Equals(movie_Show.Movie_ID)).First();
                int total_m        = ConvertToMinute(movie_Show.Start_Show);
                int col            = total_m / 10;
                int cell           = movie.Running_Time / 10;
                if (movie.Running_Time % 10 > 0)
                {
                    cell = cell + 1;
                }
                if (col > (132 - cell + 1))
                {
                    //ViewBag.ERROR = "Không Đủ Khoảng Trống Để Thêm Ghế " + seat_lv.Name;
                    return(Redirect("/Admin/Movie_Show?idCinema=" + room.Cinema_ID + "&date=" + movie_Show.Start_Show.Date));
                }
                foreach (var item in listShowInRoom)
                {
                    col = total_m / 10;
                    for (int i = 1; i <= cell; i++)
                    {
                        if (col == (ConvertToMinute(item.Start_Show) / 10))
                        {
                            //ViewBag.ERROR = "Không Đủ Khoảng Trống Để Thêm Ghế " + seat_lv.Name;
                            return(Redirect("/Admin/Movie_Show?idCinema=" + room.Cinema_ID + "&date=" + movie_Show.Start_Show.Date));
                        }
                        col++;
                    }
                }
                _context.Add(movie_Show);
                await _context.SaveChangesAsync();
            }
            return(Redirect("/Admin/Movie_Show?idCinema=" + room.Cinema_ID + "&date=" + movie_Show.Start_Show.Date));
        }
Exemplo n.º 14
0
        public static bool Init(ModuleSetting Setting, ref LanguageManager Manager, bool AddByAssembly = true)
        {
            //string json_file = SettingsHSSever.Settings.GetPath("WebRouter.json");
            bool Load;

            Controller.Init(ref Manager);
            Load = Controller.AddByAssembly(Setting.Load.Controller);

            if (Load)
            {
                //Logger.LogSYSTEM(LogLevel.INFO, LanguageManager.Language["STR_LOG_WEB_ROUTER_INITING"]);
                Middleware.Init(ref Manager);
                if (AddByAssembly)
                {
                    Load = Middleware.AddByAssembly(Setting.Load.MiddleWare);
                }
            }

            if (Load)
            {
                Router.Init(ref Manager);
                if (AddByAssembly)
                {
                    Load = Router.AddByAssembly(Setting.Load.Module);
                }
                //Logger.LogSYSTEM(LogLevel.INFO, LanguageManager.Language["STR_LOG_WEB_ROUTER_INITED"]);
            }

            if (Load)
            {
                WebSocketRouter.Init(ref Manager);
                if (AddByAssembly)
                {
                    Load = WebSocketRouter.AddByAssembly(Setting.Load.Module);
                }
            }

            return(Load);
        }
Exemplo n.º 15
0
        public List <Frame> DetermineFrames(ConnegRules rules, GenerationRules codeRules, IContainer container)
        {
            if (_hasDeterminedFrames)
            {
                throw new InvalidOperationException("Has already determined frames");
            }

            _hasDeterminedFrames = true;

            if (!_hasAppliedConfigureAndAttributes)
            {
                rules.Apply(this);
                _hasAppliedConfigureAndAttributes = true;
                applyAttributesAndConfigureMethods(codeRules, container);
            }

            var list = Middleware.ToList();

            var arguments = Route.Segments.OfType <IRoutingFrameSource>();

            foreach (var argument in arguments)
            {
                if (Action.Method.Name == "Put" && Action.HandlerType.Name == "ValuesController")
                {
                    Debug.Assert(true);
                }

                var frame = argument.ToParsingFrame(Action);
                list.Add(frame);
            }


            list.Add(Action);

            list.AddRange(Postprocessors);

            return(list);
        }
Exemplo n.º 16
0
        public virtual async Task <IEnumerable <T> > Query <T>(MongoQuery query, ISessionCache sessionCache, ITrackingProvider tracking)
            where T : class
        {
            var pipe = new Middleware <QueryContext, IEnumerable <LoadContext> >();

            pipe.Use(new TrackingAction(tracking));
            pipe.Use(new UpdateCacheAction(sessionCache));
            pipe.Use(new OverrideUsingCacheAction <LoadContext>(sessionCache));
            pipe.Use(new MongoQueryFromDatabaseAction(_couchDb, _idManager, _idAccessor));

            //setup the load context
            var type = typeof(T);

            var ctx = new QueryContext()
            {
                Query = query,
                Type  = type
            };

            var results = await pipe.Execute(ctx);

            return(results.Select(x => x.Entity).Where(x => x != null).Cast <T>());
        }
Exemplo n.º 17
0
        public void ProcessRequest(HttpContext context)
        {
            var req = context.Request;
            var rep = context.Response;
            var svr = context.Server;

            var reponse = WeChat.Core.Api.MenuManage.QueryMenus.Get();



            if (req.HttpMethod.ToUpper() == "GET")
            {
                rep.ContentEncoding = Encoding.UTF8;
                var echo = req["echostr"];
                rep.Write(echo);
                return;
            }


            var responseText = Middleware.Execute(req).GetResponse();

            rep.Write(responseText);
        }
Exemplo n.º 18
0
            public Func <IDictionary <string, object>, Task> Build(Func <IDictionary <string, object>, Task> nextApp)
            {
                var constructor =
                    Middleware.GetConstructors()
                    .Where(ctor => {
                    var prms = ctor.GetParameters();
                    if (prms.Length != Args.Length + 1)
                    {
                        return(false);
                    }
                    var argTypes =
                        Enumerable.Concat(
                            Enumerable.Repeat(typeof(Func <IDictionary <string, object>, Task>), 1),
                            Args.Select(arg => arg.GetType())
                            ).ToArray();
                    return(Enumerable.Zip(prms, argTypes, (prm, type) => prm.ParameterType.IsAssignableFrom(type)).All(r => r));
                })
                    .Single();
                var middleware = constructor.Invoke(Enumerable.Concat(Enumerable.Repeat(nextApp, 1), Args).ToArray());
                var invoke     = middleware.GetType().GetMethod("Invoke", new [] { typeof(IDictionary <string, object>) });

                return((arg) => (Task)invoke.Invoke(middleware, new [] { arg }));
            }
        public async Task RunPreMiddleware_should_run_all_middleware_when_multiple_middleware()
        {
            // Arrange
            var middleware1 = BuildWorkflowMiddleware(WorkflowMiddlewarePhase.PreWorkflow, 1);
            var middleware2 = BuildWorkflowMiddleware(WorkflowMiddlewarePhase.PreWorkflow, 2);
            var middleware3 = BuildWorkflowMiddleware(WorkflowMiddlewarePhase.PreWorkflow, 3);

            Middleware.AddRange(new[] { middleware1, middleware2, middleware3 });

            // Act
            await Runner.RunPreMiddleware(Workflow, Definition);

            // Assert
            A
            .CallTo(HandleMethodFor(middleware3))
            .MustHaveHappenedOnceExactly()
            .Then(A
                  .CallTo(HandleMethodFor(middleware2))
                  .MustHaveHappenedOnceExactly())
            .Then(A
                  .CallTo(HandleMethodFor(middleware1))
                  .MustHaveHappenedOnceExactly());
        }
Exemplo n.º 20
0
        public async Task <IActionResult> Create([Bind("ID,Name,Email,Password,Avatar,Phone,Address,Status")] Staf staf, IFormFile ful)
        {
            Middleware.CheckStafLogin(HttpContext);
            if (ModelState.IsValid)
            {
                staf.Password = StringProcessing.CreateMD5(staf.Password);
                _context.Add(staf);
                await _context.SaveChangesAsync();

                var tenImg = staf.ID + "." + ful.FileName.Split(".")[ful.FileName.Split(".").Length - 1];
                var path   = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/Uploads/Staf", tenImg);
                using (var stream = new FileStream(path, FileMode.Create))
                {
                    await ful.CopyToAsync(stream);
                }
                staf.Avatar = tenImg;
                _context.Update(staf);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            return(View(staf));
        }
Exemplo n.º 21
0
        public async Task <IActionResult> Create([Bind("ID,Name,Image_1,Image_2,Trailer,Directors,Cast,Genre,Release_Date,Running_Time,Language,Rated,Desc,Keyword,Slug,Status")] Movie movie, IFormFile ful, IFormFile ful_2)
        {
            Middleware.CheckStafLogin(HttpContext);
            if (ModelState.IsValid)
            {
                _context.Add(movie);
                await _context.SaveChangesAsync();

                if (ful != null)
                {
                    var tenImg = movie.ID + "_1." + ful.FileName.Split(".")[ful.FileName.Split(".").Length - 1];
                    var path   = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/Uploads/Movie", tenImg);
                    using (var stream = new FileStream(path, FileMode.Create))
                    {
                        await ful.CopyToAsync(stream);
                    }
                    movie.Image_1 = tenImg;
                }

                if (ful_2 != null)
                {
                    var tenImg_2 = movie.ID + "_2." + ful_2.FileName.Split(".")[ful_2.FileName.Split(".").Length - 1];
                    var path_2   = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/Uploads/Movie", tenImg_2);
                    using (var stream = new FileStream(path_2, FileMode.Create))
                    {
                        await ful_2.CopyToAsync(stream);
                    }
                    movie.Image_2 = tenImg_2;
                }

                _context.Update(movie);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            return(View(movie));
        }
Exemplo n.º 22
0
        public IActionResult Index(int idCinema, DateTime?date)
        {
            Middleware.CheckStafLogin(HttpContext);
            if (idCinema == 0)
            {
                return(NotFound());
            }
            if (date == null)
            {
                date = DateTime.Now;
            }

            var listShow = _context.Movie_Shows.Include(m => m.Movie).Include(m => m.Room).Include(m => m.Room.Cinema).Where(m => m.Room.Cinema_ID.Equals(idCinema)).Where(m => m.Start_Show.Year.Equals(date.Value.Year)).Where(m => m.Start_Show.Month.Equals(date.Value.Month)).Where(m => m.Start_Show.Day.Equals(date.Value.Day)).ToArray();
            var listRoom = _context.Rooms.Where(r => r.Cinema_ID.Equals(idCinema)).ToArray();
            var cinema   = _context.Cinemas.Where(c => c.ID.Equals(idCinema)).First();

            ViewBag.listMovie = _context.Movies.ToList();
            ViewBag.listShow  = listShow;
            ViewBag.listRoom  = listRoom;
            ViewBag.Cinema    = cinema;
            ViewBag.Date      = date.Value;

            return(View());
        }
        public async Task RunPostMiddleware_should_only_run_middleware_in_PostWorkflow_phase()
        {
            // Arrange
            var postMiddleware1 = BuildWorkflowMiddleware(WorkflowMiddlewarePhase.PostWorkflow, 1);
            var postMiddleware2 = BuildWorkflowMiddleware(WorkflowMiddlewarePhase.PostWorkflow, 2);
            var preMiddleware1  = BuildWorkflowMiddleware(WorkflowMiddlewarePhase.PreWorkflow, 3);
            var preMiddleware2  = BuildWorkflowMiddleware(WorkflowMiddlewarePhase.PreWorkflow, 4);

            Middleware.AddRange(new[] { preMiddleware1, postMiddleware1, preMiddleware2, postMiddleware2 });

            // Act
            await Runner.RunPostMiddleware(Workflow, Definition);

            // Assert
            A
            .CallTo(HandleMethodFor(postMiddleware2))
            .MustHaveHappenedOnceExactly()
            .Then(A
                  .CallTo(HandleMethodFor(postMiddleware1))
                  .MustHaveHappenedOnceExactly());

            A.CallTo(HandleMethodFor(preMiddleware1)).MustNotHaveHappened();
            A.CallTo(HandleMethodFor(preMiddleware1)).MustNotHaveHappened();
        }
Exemplo n.º 24
0
        public MiddlewareRuntime(
            IEnumerable <RouteFuncAsyncMiddleware> routeFuncAsyncMiddlewareList,
            RouteFuncAsync handlerFunc
            )
        {
            _handlerFunc = handlerFunc;
            foreach (var routeFuncAsyncMiddleware in routeFuncAsyncMiddlewareList)
            {
                var middleware = new Middleware
                {
                    Next        = context => _handlerFunc(context),
                    HandlerFunc = routeFuncAsyncMiddleware
                };

                if (_middleware == null)
                {
                    _middleware = middleware;
                }
                else
                {
                    _middleware.Next = middleware.Invoke;
                }
            }
        }
        public async Task <IActionResult> Create([Bind("ID,Name,Image,Image_Selected,Image_Checked,Count_Cell,Price,Level,Status")] Category_Equipment Category_Equipment, IFormFile ful, IFormFile ful_selected, IFormFile ful_checked)
        {
            Middleware.CheckStafLogin(HttpContext);
            if (ModelState.IsValid)
            {
                _context.Add(Category_Equipment);
                await _context.SaveChangesAsync();

                var tenImg         = Category_Equipment.ID + "." + ful.FileName.Split(".")[ful.FileName.Split(".").Length - 1];
                var path           = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/Uploads/Category_Equipment", tenImg);
                var tenImgSelected = Category_Equipment.ID + "_selected." + ful_selected.FileName.Split(".")[ful_selected.FileName.Split(".").Length - 1];
                var pathSelected   = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/Uploads/Category_Equipment", tenImgSelected);
                var tenImgChecked  = Category_Equipment.ID + "_checked." + ful_checked.FileName.Split(".")[ful_checked.FileName.Split(".").Length - 1];
                var pathChecked    = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/Uploads/Category_Equipment", tenImgChecked);
                using (var stream = new FileStream(path, FileMode.Create))
                {
                    await ful.CopyToAsync(stream);
                }
                using (var stream = new FileStream(pathSelected, FileMode.Create))
                {
                    await ful_selected.CopyToAsync(stream);
                }
                using (var stream = new FileStream(pathChecked, FileMode.Create))
                {
                    await ful_checked.CopyToAsync(stream);
                }
                Category_Equipment.Image          = tenImg;
                Category_Equipment.Image_Checked  = tenImgChecked;
                Category_Equipment.Image_Selected = tenImgSelected;
                _context.Update(Category_Equipment);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            return(View(Category_Equipment));
        }
Exemplo n.º 26
0
 public MarshalBuilder Use(Middleware middleware)
 {
     _middleware.Add(middleware);
     return(this);
 }
Exemplo n.º 27
0
        private static Middleware <T>[] AddCollectMiddleWare(List <object> actions, Middleware <T>[] middlewares)
        {
            Middleware <T> collecterMiddleware = NewCollectActionMiddleware(actions);

            return(middlewares.AddViaUnion(collecterMiddleware).ToArray());
        }
Exemplo n.º 28
0
 public static Middleware Then(this Middleware middleware, Middleware nextMiddleware)
 {
     return((ctx, next) => middleware(ctx, () => nextMiddleware(ctx, next)));
 }
Exemplo n.º 29
0
        public string GetCustomerLogin()
        {
            var customer = Middleware.CustomerLogin(HttpContext);

            return(JsonConvert.SerializeObject(customer));
        }
Exemplo n.º 30
0
 public void SetMiddleware(Middleware middleware)
 {
     this.middleware = middleware;
 }
Exemplo n.º 31
0
        private async Task <DialogTurnResult> BeginRootDialogAsync(
            WaterfallStepContext stepContext,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            var activity = stepContext.Context.Activity;

            activity = Middleware.StripAtMentionText(activity);

            // Set activity text if request is from an adaptive card submit action
            activity = Middleware.AdaptiveCardSubmitActionHandler(activity);

            // Set activity text if request is from an adaptive card submit action
            activity = Middleware.AdaptiveCardSubmitActionHandler(activity);
            var command = activity.Text.Trim().ToLower();

            if (command == DialogMatches.FetchRosterPayloadMatch)
            {
                return(await stepContext.BeginDialogAsync(
                           nameof(FetchRosterDialog)));
            }
            else if (command == DialogMatches.FetchRosterApiMatch)
            {
                await stepContext.BeginDialogAsync(
                    nameof(ListNamesDialog));

                await stepContext.Context.SendActivityAsync(Strings.ThanksRosterTitleMsg);

                return(await stepContext.EndDialogAsync(null, cancellationToken));
            }
            else if (command == DialogMatches.HelloDialogMatch2 || command == DialogMatches.HelloDialogMatch1)
            {
                return(await stepContext.BeginDialogAsync(
                           nameof(HelloDialog)));
            }
            else if (command == DialogMatches.Help)
            {
                return(await stepContext.BeginDialogAsync(
                           nameof(HelpDialog)));
            }
            else if (command == DialogMatches.MultiDialog1Match1)
            {
                return(await stepContext.BeginDialogAsync(
                           nameof(MultiDialog1)));
            }
            else if (command == DialogMatches.MultiDialog2Match)
            {
                return(await stepContext.BeginDialogAsync(
                           nameof(MultiDialog2)));
            }
            else if (command == DialogMatches.FecthLastExecutedDialogMatch)
            {
                return(await stepContext.BeginDialogAsync(
                           nameof(GetLastDialogUsedDialog)));
            }
            else if (command == DialogMatches.Send1to1Conversation)
            {
                return(await stepContext.BeginDialogAsync(
                           nameof(ProactiveMsgTo1to1Dialog)));
            }
            else if (command == DialogMatches.SetUpTextMsg)
            {
                return(await stepContext.BeginDialogAsync(
                           nameof(UpdateTextMsgSetupDialog)));
            }
            else if (command == DialogMatches.UpdateLastSetupTextMsg)
            {
                return(await stepContext.BeginDialogAsync(
                           nameof(UpdateTextMsgDialog)));
            }
            else if (command == DialogMatches.SetUpCardMsg)
            {
                return(await stepContext.BeginDialogAsync(
                           nameof(UpdateCardMsgSetupDialog)));
            }
            else if (command == DialogMatches.UpdateCard)
            {
                return(await stepContext.BeginDialogAsync(
                           nameof(UpdateCardMsgDialog)));
            }
            else if (command == DialogMatches.TeamInfo)
            {
                return(await stepContext.BeginDialogAsync(
                           nameof(FetchTeamsInfoDialog)));
            }
            else if (command == DialogMatches.DeepLinkTabCard)
            {
                return(await stepContext.BeginDialogAsync(
                           nameof(DeepLinkStaticTabDialog)));
            }
            else if (command == DialogMatches.AtMentionMatch1 || command == DialogMatches.AtMentionMatch2 || command == DialogMatches.AtMentionMatch3)
            {
                return(await stepContext.BeginDialogAsync(
                           nameof(AtMentionDialog)));
            }
            else if (command == DialogMatches.DialogFlowMatch)
            {
                await stepContext.Context.SendActivityAsync(Strings.DialogFlowStep1);

                await stepContext.Context.SendActivityAsync(Strings.DialogFlowStep2);

                await stepContext.BeginDialogAsync(
                    nameof(BeginDialogExampleDialog));

                await stepContext.Context.SendActivityAsync(Strings.DialogFlowStep3);

                return(await stepContext.EndDialogAsync(null, cancellationToken));
            }
            else if (command == DialogMatches.HeroCard)
            {
                return(await stepContext.BeginDialogAsync(
                           nameof(HeroCardDialog)));
            }
            else if (command == DialogMatches.ThumbnailCard)
            {
                return(await stepContext.BeginDialogAsync(
                           nameof(ThumbnailcardDialog)));
            }
            else if (command == DialogMatches.MessageBack)
            {
                return(await stepContext.BeginDialogAsync(
                           nameof(MessagebackDialog)));
            }
            else if (command == DialogMatches.AdaptiveCard)
            {
                return(await stepContext.BeginDialogAsync(
                           nameof(AdaptiveCardDialog)));
            }
            else if (command == DialogMatches.PopUpSignIn)
            {
                return(await stepContext.BeginDialogAsync(
                           nameof(PopupSigninCardDialog)));
            }
            else if (command == DialogMatches.RunQuizQuestionsMatch)
            {
                await stepContext.Context.SendActivityAsync(Strings.QuizTitleWelcomeMsg);

                return(await stepContext.BeginDialogAsync(
                           nameof(QuizFullDialog)));
            }
            else if (command == DialogMatches.PromptFlowGameMatch)
            {
                return(await stepContext.BeginDialogAsync(
                           nameof(PromptDialog)));
            }
            else if (command == DialogMatches.DisplayCards)
            {
                return(await stepContext.BeginDialogAsync(
                           nameof(DisplayCardsDialog)));
            }
            else if (command == DialogMatches.StopShowingCards)
            {
                await stepContext.Context.SendActivityAsync(Strings.DisplayCardsThanksMsg);

                return(await stepContext.EndDialogAsync(null, cancellationToken));
            }
            else if (command == DialogMatches.LocalTime)
            {
                await stepContext.Context.SendActivityAsync(Strings.UTCTimeZonePrompt + stepContext.Context.Activity.Timestamp);

                await stepContext.Context.SendActivityAsync(Strings.LocalTimeZonePrompt + stepContext.Context.Activity.LocalTimestamp);

                return(await stepContext.EndDialogAsync(null, cancellationToken));
            }
            else if (command == DialogMatches.O365ConnectorCardDefault || command == DialogMatches.DisplayCardO365ConnectorCard2 || command == DialogMatches.DisplayCardO365ConnectorCard3)
            {
                return(await stepContext.BeginDialogAsync(
                           nameof(O365ConnectorCardDialog)));
            }
            else if (command == DialogMatches.O365ConnectorCardActionableCardDefault || command == DialogMatches.DisplayCardO365ConnectorActionableCard2)
            {
                return(await stepContext.BeginDialogAsync(
                           nameof(O365ConnectorCardActionsDialog)));
            }
            else if (command == DialogMatches.AuthSample)
            {
                var message = CreateAuthSampleMessage(stepContext);
                await stepContext.Context.SendActivityAsync(message);

                return(await stepContext.EndDialogAsync());
            }
            else if (command == DialogMatches.Facebooklogin)
            {
                return(await stepContext.BeginDialogAsync(
                           nameof(SimpleFacebookAuthDialog)));
            }
            // We shouldn't get here, but fail gracefully if we do.
            await stepContext.Context.SendActivityAsync(
                "I don't recognize that option.",
                cancellationToken : cancellationToken);

            // Continue through to the next step without starting a child dialog.
            return(await stepContext.EndDialogAsync(null, cancellationToken));
        }
Exemplo n.º 32
0
 public void AddParameter(string name, object value, Middleware.ParameterType type)
 {
     Request.AddParameter(name, value, (RestSharp.ParameterType)Enum.Parse(typeof(RestSharp.ParameterType), type.ToString()));
     if (type == ParameterType.RequestBody)
         Request.RequestFormat = DataFormat.Json;
 }