/// <summary>
 /// </summary>
 /// <param name="context"></param>
 /// <param name="model"></param>
 /// <returns></returns>
 public StatusCode getForecast(
     RequestContext context,
     WeatherStationModel model
     )
 {
     return StatusCodes.BadNotImplemented;
 }
        protected override IController GetControllerInstance(
            RequestContext requestContext, Type controllerType)
        {
            try
            {
                if (controllerType == null)
                    return base.GetControllerInstance(requestContext, null);

                var controller = funqBuilder.CreateInstance(controllerType) as IController;

                return controller ?? base.GetControllerInstance(requestContext, controllerType);
            }
            catch (HttpException ex)
            {
                if (ex.GetHttpCode() == 404)
                {
                    try
                    {
                        if (ServiceStackController.CatchAllController != null)
                        {
                            return ServiceStackController.CatchAllController(requestContext);
                        }
                    }
                    catch { } //ignore not found CatchAllController
                }
                throw;
            }
        }
Example #3
0
        public override void Authenticate(RequestContext<AuthenticateRequest, AuthenticateResponse> requestContext)
        {
            SslConnection connection = _context.Connection as SslConnection;

            X509Certificate cert = connection.ClientCertificate;
            string certHashString = cert.GetCertHashString();

            foreach(User user in ServerContext.AccessControlList.Users)
            {
                SslAuthenticationParameters auth = (SslAuthenticationParameters)user.GetAuthentication("ssl_auth");

                if(auth != null && auth.CertificateHash.Equals(certHashString))
                {
                    ServerContext.ServerAuthenticationContext.AuthenticatedPermissionMember = user;

                    AuthenticateResponse response = requestContext.CreateResponse();
                    response.Succeeded = true;
                    response.Execute();
                    return;
                }
            }

            _log.WarnFormat("Could not find user associated with certificate '{0}'", certHashString);

            AuthenticateResponse errorResponse = requestContext.CreateResponse();
            errorResponse.Succeeded = false;
            errorResponse.CustomErrorMessage = "No client associated with specified certificate!";
            errorResponse.Execute();
        }
 public MetricsServices(RequestContext c,
                     SearchQueryRepository queries
                     )
 {
     context = c;
     this.SearchQueries = queries;
 }
Example #5
0
        public async Task<ViewEngineResult> FindView(RequestContext requestContext, string viewName)
        {
            var actionDescriptor = _actionDescriptorProvider.CreateDescriptor(requestContext) as ControllerBasedActionDescriptor;
            
            if (actionDescriptor == null)
            {
                return null;
            }
            
            if (String.IsNullOrEmpty(viewName))
            {
                viewName = actionDescriptor.ActionName;
            }

            string controllerName = actionDescriptor.ControllerName;
            var searchedLocations = new List<string>(_viewLocationFormats.Length);
            for (int i = 0; i < _viewLocationFormats.Length; i++)
            {
                string path = String.Format(CultureInfo.InvariantCulture, _viewLocationFormats[i], viewName, controllerName);
                IView view = await _virtualPathFactory.CreateInstance(path);
                if (view != null)
                {
                    return ViewEngineResult.Found(view);
                }
                searchedLocations.Add(path);
            }
            return ViewEngineResult.NotFound(searchedLocations);
        }
        public static MetricsServices InstantiateForMemory(RequestContext c)
        {
            return new MetricsServices(c,
                                      SearchQueryRepository.InstantiateForMemory(c)                                      
                                      );

        }
Example #7
0
        public void CanAddItemToOrderAndCalculate()
        {
            
            RequestContext c = new RequestContext();
            MerchantTribeApplication app = MerchantTribeApplication.InstantiateForMemory(c);
            c.CurrentStore = new Accounts.Store();
            c.CurrentStore.Id = 1;

            Order target = new Order();
            LineItem li = new LineItem() { BasePricePerItem = 19.99m, 
                                           ProductName = "Sample Product", 
                                           ProductSku = "ABC123", 
                                           Quantity = 2 };
            target.Items.Add(li);
            app.CalculateOrder(target);
            Assert.AreEqual(39.98m, target.TotalOrderBeforeDiscounts, "SubTotal was Incorrect");
            Assert.AreEqual(39.98m, target.TotalGrand, "Grand Total was incorrect");
            
            bool upsertResult = app.OrderServices.Orders.Upsert(target);
            Assert.IsTrue(upsertResult, "Order Upsert Failed");

            Assert.AreEqual(c.CurrentStore.Id, target.StoreId, "Order store ID was not set correctly");
            Assert.AreNotEqual(string.Empty, target.bvin, "Order failed to get a bvin");
            Assert.AreEqual(1, target.Items.Count, "Item count should be one");
            Assert.AreEqual(target.bvin, target.Items[0].OrderBvin, "Line item didn't receive order bvin");
            Assert.AreEqual(target.StoreId, target.Items[0].StoreId, "Line item didn't recieve storeid");
        }
        public static ScheduleService InstantiateForMemory(RequestContext c)
        {
            return new ScheduleService(c,
                                      QueuedTaskRepository.InstantiateForMemory(c)
                                      );

        }
 public ActionResult GetAllRequests(int?page)
 {
     int pageSize = 5;
     int pageNumber = (page ?? 1);
     var colection = new RequestContext().Requests.OrderByDescending(x => x.InitialDate);
     return View(colection.ToPagedList(pageNumber, pageSize));
 }
        /// <summary>
        /// Called when [execute].
        /// </summary>
        /// <param name="context">The context.</param>
        /// <returns>Base return container</returns>
        public override BaseReturnContainer OnExecute(RequestContext context)
        {
            GetUserTagsRequestContainer requestContainer = context.InParam as GetUserTagsRequestContainer;
            GetUserTagsReturnContainer returnContainer = new GetUserTagsReturnContainer();

            ISqlProvider sqlProvider = (ISqlProvider)ProviderFactory.Instance.CreateProvider<ISqlProvider>(requestContainer.ProviderName);
            Dictionary<string, object> parameters = new Dictionary<string, object>() { { "@userId", requestContainer.UserId }, { "@deleted", false } };
            DataSet returnedData = sqlProvider.ExecuteQuery(SqlQueries.GetUserProfileQuery, parameters);
            if (returnedData.Tables.Count > 0 && returnedData.Tables[0].Rows.Count == 1)
            {
                DataRow row = returnedData.Tables[0].Rows[0];
                returnContainer.Tags = row["Tags"].ToString().Split(new string[] { Constants.QuerySeparator }, StringSplitOptions.RemoveEmptyEntries).ToList<string>();
                double tempDouble;
                double.TryParse(row["AreaOfService"].ToString(), out tempDouble);
                returnContainer.AreaOfService = tempDouble;
                returnContainer.ReturnCode = ReturnCodes.C101;
            }
            else
            {
                // User does not exist
                returnContainer.ReturnCode = ReturnCodes.C001;
            }

            return returnContainer;
        }
        protected async Task HandleInitializeRequest(
            InitializeRequest initializeParams,
            RequestContext<InitializeResult> requestContext)
        {
            // Grab the workspace path from the parameters
            editorSession.Workspace.WorkspacePath = initializeParams.RootPath;

            await requestContext.SendResult(
                new InitializeResult
                {
                    Capabilities = new ServerCapabilities
                    {
                        TextDocumentSync = TextDocumentSyncKind.Incremental,
                        DefinitionProvider = true,
                        ReferencesProvider = true,
                        DocumentHighlightProvider = true,
                        DocumentSymbolProvider = true,
                        WorkspaceSymbolProvider = true,
                        HoverProvider = true,
                        CompletionProvider = new CompletionOptions
                        {
                            ResolveProvider = true,
                            TriggerCharacters = new string[] { ".", "-", ":", "\\" }
                        },
                        SignatureHelpProvider = new SignatureHelpOptions
                        {
                            TriggerCharacters = new string[] { " " } // TODO: Other characters here?
                        }
                    }
                });
        }
 public static MembershipServices InstantiateForDatabase(RequestContext c)
 {
     return new MembershipServices(c, 
                             UserQuestionRepository.InstantiateForDatabase(c),
                             CustomerAccountRepository.InstantiateForDatabase(c)
                             );
 }
Example #13
0
        public override V3Message execute(Request message, RequestContext context)
        {
            Object returnValue = null;
#if(FULL_BUILD)
            if (body.body == null)
                body.body = new object[0];
            else if (!body.body.GetType().IsArray)
                body.body = new object[] { body.body };

            try
            {
                if (Registry.ServiceRegistry.GetMapping(destination).Equals("*"))
                    destination = source;

                ThreadContext.getProperties()[ORBConstants.REQUEST_HEADERS] = headers;
                ThreadContext.getProperties()[ORBConstants.CLIENT_ID] = clientId;

                returnValue = Invoker.handleInvoke( message, destination, operation, (Object[])( (Object[])body.body )[0], context );
            }
            catch (Exception exception)
            {
                return new ErrMessage(messageId, exception);
            }
#endif
            return new AckMessage(messageId, clientId, returnValue);
        }
Example #14
0
        public override Task Render(RequestContext ctx, StringWriter stream, IDummy authObj)
        {
            #if MONO
            AddResource(new JsResource(Constants.kWebRoot, "/js/faqPageCompiled.js", true));
            #endif

            // render head
            base.Render(ctx, stream, authObj);

            using (new DivContainer(stream, HtmlAttributes.@class, "jumbotron clearfix"))
            {
                using (new DivContainer(stream, HtmlAttributes.@class, "container"))
                {
                    using (new DivContainer(stream, HtmlAttributes.@class, "row"))
                    {
                        using (new DivContainer(stream, HtmlAttributes.@class, "col-xs-12"))
                        {
                            BaseComponent.SPAN(stream, "Maintenance", HtmlAttributes.@class, "noTopMargin h1");
                            P("Metaexchange is currently in maintenance mode, please check back soon.");
                        }
                    }
                }
            }

            return null;
        }
Example #15
0
 /// <summary>
 /// Redirects to another page.
 /// </summary>
 /// <param name="context"></param>
 /// <param name="action"></param>
 /// <returns></returns>
 private ProcessingResult ProcessRedirect(RequestContext context, IActionResult action)
 {
     var redirect = (Redirect) action;
     context.Response.Status = HttpStatusCode.Redirect;
     context.Response.Add(new StringHeader("Location", redirect.Location));
     return ProcessingResult.SendResponse;
 }
        protected async Task HandleLaunchRequest(
            LaunchRequestArguments launchParams,
            RequestContext<object> requestContext)
        {
            // Execute the given PowerShell script and send the response.
            // Note that we aren't waiting for execution to complete here
            // because the debugger could stop while the script executes.
            Task executeTask =
                editorSession.PowerShellContext
                    .ExecuteScriptAtPath(launchParams.Program)
                    .ContinueWith(
                        async (t) =>
                        {
                            Logger.Write(LogLevel.Verbose, "Execution completed, terminating...");

                            await requestContext.SendEvent(
                                TerminatedEvent.Type,
                                null);

                            // Stop the server
                            this.Stop();
                        });

            await requestContext.SendResult(null);
        }
        /// <summary>
        /// Process a request.
        /// </summary>
        /// <param name="context">Request information</param>
        /// <returns>What to do next.</returns>
        public ProcessingResult Process(RequestContext context)
        {
            var uri = context.Request.Uri.AbsolutePath.TrimEnd('/');

            ControllerMapping mapping;
            if (!_controllers.TryGetValue(uri, out mapping))
                return ProcessingResult.Continue;

            int pos = uri.LastIndexOf('/');
            var actionName = uri.Substring(pos + 1);

            var controller = _controllerFactory.Create(mapping.ControllerType);
            var actions = mapping.FindAction(actionName);

            var form = context.Request.Form;
            var queryString = context.Request.QueryString;
            foreach (var action in actions)
            {

                foreach (var parameter in action.GetParameters())
                {
                    var actionParameter = parameter;
                    var httpParameter =
                        form.FirstOrDefault(
                            p => p.Name.Equals(actionParameter.Name, StringComparison.OrdinalIgnoreCase)) ??
                        queryString.FirstOrDefault(
                            p => p.Name.Equals(actionParameter.Name, StringComparison.OrdinalIgnoreCase));

                }
            }

            var result = mapping.Invoke(controller, actionName, null);
            return ProcessingResult.SendResponse;
        }
 public BusinessObjectsPropertiesRenderForeignKeyConstructorForDbContext(MyMeta.ITable table, RequestContext context)
 {
     this._context = context;
     this._table = table;
     this._script = context.ScriptSettings;
     this._output = context.Zeus.Output;
 }
Example #19
0
        private static async void MainAsync(string cachePath, double zoomLevel)
        {
            var browserSettings = new BrowserSettings();
            var requestContextSettings = new RequestContextSettings { CachePath = cachePath };

            // RequestContext can be shared between browser instances and allows for custom settings
            // e.g. CachePath
            using(var requestContext = new RequestContext(requestContextSettings))
            using (var browser = new ChromiumWebBrowser(TestUrl, browserSettings, requestContext))
            {
                if (zoomLevel > 1)
                {
                    browser.FrameLoadStart += (s, argsi) =>
                    {
                        var b = (ChromiumWebBrowser)s;
                        if (argsi.Frame.IsMain)
                        {
                            b.SetZoomLevel(zoomLevel);
                        }
                    };
                }
                await LoadPageAsync(browser);

                // Wait for the screenshot to be taken.
                await browser.ScreenshotAsync().ContinueWith(DisplayBitmap);

                await LoadPageAsync(browser, "http://github.com");

                // Wait for the screenshot to be taken.
                await browser.ScreenshotAsync().ContinueWith(DisplayBitmap);
            }
        }
 public void SetsMetaHeaders()
 {
     var request = new RequestContext(HttpMethods.Get, Enumerable.Empty<KeyValuePair<string, object>>());
      request.Prepare();
      Assert.AreEqual("dotnet", request.Request.Headers["X-Mashape-Language"]);
      Assert.AreEqual("0.1", request.Request.Headers["X-Mashape-Version"]);
 }
Example #21
0
        /// <summary>
        /// Create a new OffScreen Chromium Browser
        /// </summary>
        /// <param name="address">Initial address (url) to load</param>
        /// <param name="browserSettings">The browser settings to use. If null, the default settings are used.</param>
        /// <param name="requestContext">See <see cref="RequestContext" /> for more details. Defaults to null</param>
        /// <param name="automaticallyCreateBrowser">automatically create the underlying Browser</param>
        /// <param name="blendPopup">Should the popup be blended in the background in the rendering</param>
        /// <exception cref="System.InvalidOperationException">Cef::Initialize() failed</exception>
        public ChromiumWebBrowser(string address = "", BrowserSettings browserSettings = null,
            RequestContext requestContext = null, bool automaticallyCreateBrowser = true)
        {
            if (!Cef.IsInitialized && !Cef.Initialize())
            {
                throw new InvalidOperationException("Cef::Initialize() failed");
            }

            BitmapFactory = new BitmapFactory(BitmapLock);

            ResourceHandlerFactory = new DefaultResourceHandlerFactory();
            BrowserSettings = browserSettings ?? new BrowserSettings();
            RequestContext = requestContext;

            Cef.AddDisposable(this);
            Address = address;

            managedCefBrowserAdapter = new ManagedCefBrowserAdapter(this, true);

            if (automaticallyCreateBrowser)
            {
                CreateBrowser(IntPtr.Zero);
            }

            popupPosition = new Point();
            popupSize = new Size();
        }
Example #22
0
 /// <summary>
 /// Sets Content-Type to "application/javascript" and sends the java script as the body.
 /// </summary>
 /// <param name="context"></param>
 /// <param name="action"></param>
 /// <returns></returns>
 private ProcessingResult ProcessExecuteJavascript(RequestContext context, IActionResult action)
 {
     var js = (ExecuteJavascript)action;
     context.Response.ContentType.Value = "application/javascript";
     byte[] bytes = Encoding.UTF8.GetBytes(js.Value);
     context.Response.Body.Write(bytes, 0, bytes.Length);
     return ProcessingResult.SendResponse;
 }
 /// <summary>
 /// This renders short properties with DataAnnotations Attributes.
 /// </summary>
 /// <param name="column">The IColumn object</param>
 /// <param name="context">The RequestContext</param>
 /// <param name="omitList">Comma-delimited list of properties to omit</param>
 public BusinessObjectsPropertyRenderDataAnnotationsForDbContext(MyMeta.IColumn column, RequestContext context, string omitList)
     : this(column, context)
 {
     if (!string.IsNullOrEmpty(omitList))
         this._omitList = omitList.ToLower().Split(',');
     else
         this._omitList = new string[0];
 }
 protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
 {
     if (controllerType == null)
     {
         throw new HttpException(404, string.Format("The controller for path '{0}' could not be found.", requestContext.HttpContext.Request.Path));
     }
     return (IController)_kernel.Resolve(controllerType);
 }
 public ActionResult GetRequestsById(int? page)
 {
     string id = User.Identity.GetUserId();
     var collection = new RequestContext().Requests.Where(x => x.ClientID == id).OrderByDescending(x => x.InitialDate);
     int pageSize = 5;
     int pageNumber = (page ?? 1);
     return View("GetAllRequests", collection.ToPagedList(pageNumber,pageSize));
 }
Example #26
0
 public string GenerateUrl(string areacode, int days)
 {
     var values = new { areacode = areacode, days = days };
     RequestContext requestContext = new RequestContext();
     requestContext.HttpContext = new HttpContextWrapper(HttpContext.Current);
     requestContext.RouteData = RouteData;
     return RouteTable.Routes.GetVirtualPath(requestContext, new RouteValueDictionary(values)).VirtualPath;
 }
 public void SetsTheProperMethod()
 {
     foreach (var method in AllMethods)
      {
     var request = new RequestContext(method, Enumerable.Empty<KeyValuePair<string, object>>());
     request.Prepare();
     Assert.AreEqual(method.ToString().ToUpper(), request.Request.Method);
      }
 }
Example #28
0
 /// <summary>
 /// Creates a javascript alert.
 /// </summary>
 /// <param name="context"></param>
 /// <param name="action"></param>
 /// <returns></returns>
 private ProcessingResult ProcessJavascriptAlert(RequestContext context, IActionResult action)
 {
     var alert = (JavascriptAlert) action;
     context.Response.ContentType.Value = "application/javascript";
     string body = "alert('" + alert.Message.Replace("'", "\\'").Replace("\n", "\\n").Replace("\r", "") + "');";
     byte[] bytes = Encoding.UTF8.GetBytes(body);
     context.Response.Body.Write(bytes, 0, bytes.Length);
     return ProcessingResult.SendResponse;
 }
 public MembershipServices(RequestContext c, 
                     UserQuestionRepository questions,
                     CustomerAccountRepository customers
                     )
 {
     context = c;
     this.UserQuestions = questions;
     this.Customers = customers;
 }
 public static AccountService InstantiateForMemory(RequestContext c)
 {
     return new AccountService(c,
                              UserAccountRepository.InstantiateForMemory(c),
                              AuthTokenRepository.InstantiateForMemory(c),
                              ApiKeyRepository.InstantiateForMemory(c),
                              StoreUserRelationshipRepository.InstantiateForMemory(c),
                              StoreRepository.InstantiateForMemory(c));
 }