Exemple #1
0
        public override Task Invoke(IOwinContext context)
        {
            String         path       = context.Get <String>("owin.RequestPath");
            HttpController controller = null;

            foreach (Regex regex in routes.Keys)
            {
                if (regex.IsMatch(path))
                {
                    var groups = regex.Match(path).Groups;
                    var dic    = regex.GetGroupNames().ToDictionary(name => name, name => groups[name].Value);
                    foreach (var key in dic.Keys.Where(t => t != "0"))
                    {
                        context.Environment.Add(key, dic[key]);
                    }
                    controller = routes[regex];
                    break;
                }
            }
            if (controller == null)
            {
                return(Next.Invoke(context));
            }
            return(Task.Factory.StartNew(() =>
            {
                controller.Service(context);
            }));
        }
        private void RegisterMethods(string processingGroup, HttpController httpController)
        {
            Type type = httpController.GetType();

            //check all methods of the HttpController class
            foreach (MethodInfo methodInfo in type.GetMethods())
            {
                string path;

                //load all attributes
                System.Attribute[] attr = System.Attribute.GetCustomAttributes(methodInfo);
                foreach (Attribute a in attr)
                {
                    if (a is Path)
                    {
                        Path pathAttribute = (Path)a;
                        path = pathAttribute.Method.ToString() + pathAttribute.Url;

                        if (!pathAttribute.Url.StartsWith("/"))
                        {
                            throw new Exception("Cannot include method since first parameter does not match target type. Make sure that the first parameter is type of HttpContext.");
                        }

                        if (methodInfo.GetParameters()[0].ParameterType.Name.CompareTo("HttpContext") != 0)
                        {
                            throw new Exception("Cannot include method since first parameter does not match target type. Make sure that the first parameter is type of HttpContext.");
                        }
                        _routingEngine.AddEntry(pathAttribute.Method.ToString() + pathAttribute.Url, processingGroup, httpController, methodInfo);
                    }
                }
            }
        }
Exemple #3
0
        public async void RefreshInfo(object sender, EventArgs e)
        {
            try
            {
                var r = await HttpController.UserInfo();

                if (r.code == System.Net.HttpStatusCode.Unauthorized)
                {
                    housesGroupBox.Visible = false;
                    userInfo.Text          = "Для дальнейшей работы авторизуйтесь";
                }
                else if (r.code == System.Net.HttpStatusCode.OK)
                {
                    housesGroupBox.Visible = true;
                    var definition = new
                    {
                        FullName = ""
                    };

                    var data = JsonConvert.DeserializeAnonymousType(r.response, definition);
                    userInfo.Text = "Добро пожаловать, " + data.FullName;
                }
            }
            catch
            {
                DialogResult result = MessageBox.Show(
                    "Повторите попытку",
                    "Ошибка!",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Error);
            }
        }
Exemple #4
0
        public object Register(string parameter)
        {
            try
            {
                Address   = $"http://{Global.__SERVERADDRESS}:{Global.__PORT}/UserInfo/Register";
                Method    = Method.POST;
                Parameter = parameter;

                HttpController controller = new HttpController()
                {
                    header = this
                };

                CustomMessage message;
                using (Stream stream = controller.Start())
                {
                    StreamReader reader = new StreamReader(stream);
                    message = JsonConvert.DeserializeObject <CustomMessage>(reader.ReadToEnd());
                }
                controller.Close();

                return(message);
            }
            catch (Exception objException)
            {
                if (objException.InnerException != null)
                {
                    throw new Exception(objException.InnerException.Message);
                }
                throw new Exception(objException.Message);
            }
        }
Exemple #5
0
            public static string WriteClientRegistration(HttpController controller)
            {
                string namespaceVersion   = $@"{(controller.NamespaceVersion != null ? $"{controller.NamespaceVersion}." : "")}{(controller.NamespaceSuffix != null ? $"{controller.NamespaceSuffix}." : string.Empty)}";
                string interfaceName      = $@"{namespaceVersion}I{controller.ClientName}";
                string implementationName = $@"{namespaceVersion}{controller.ClientName}";

                return($@"			services.AddScoped<{interfaceName}, {implementationName}>();");
            }
Exemple #6
0
 static public HttpController Instance()
 {
     if (m_Instance == null)
     {
         m_Instance = new HttpController();
     }
     return(m_Instance);
 }
Exemple #7
0
 public void Setup()
 {
     Client.InitializeClient();
     Client.SetClientUri("http://universities.hipolabs.com");
     parser = new Parser <List <UniversityModel> >();
     universityRequestController = new HttpController <List <UniversityModel> >(Client.ApiClient, parser);
     optionalParameters          = new Dictionary <string, string>();
 }
 public TeacherPage()
 {
     this.InitializeComponent();
     httpController = new HttpController();
     RFIDReader     = new MFRC522();
     InitRFIDReader();
     runTask();
 }
 public MainPage()
 {
     BluetoothStream.public_bluetooth.InitialiceBluetooth();
     this.InitializeComponent();
     Task.Run(_server.Run);
     httpController = new HttpController();
     runTask();
 }
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="processingGroup">name of the processing group</param>
 /// <param name="httpController">HttpController</param>
 /// <param name="methodInfo">method info</param>
 /// <param name="identifier"> target identifier (optional, only for internal usage)</param>
 /// <param name="path">unique path of the REST function</param>
 /// <param name="metrics">metrics of the routing entry</param>
 public RoutingEntry(string processingGroup, HttpController httpController, MethodInfo methodInfo, string identifier, string path, int metrics)
 {
     _processingGroup = processingGroup;
     _httpController  = httpController;
     _methodInfo      = methodInfo;
     Value            = identifier;
     _path            = path;
     _metrics         = metrics;
 }
Exemple #11
0
        public void GetEntryAsync_ParseIsBad_Exception()
        {
            var parser = new Parser <ComicModel>();
            var comicsRequestController = new HttpController <ComicModel>(Client.ApiClient, parser);

            Task <ComicModel> result = comicsRequestController.GetEntryAsync("application/json", "Get", "search?name=middle", optionalParameters, new System.Threading.CancellationToken());

            Assert.That(() => result, Throws.TypeOf <FailedToParseResponseDataExcpetion>());
        }
        public void HttpController_NameNotFilled_Error()
        {
            var controller = new HttpController(new FakeUserService(true), new FakeMailingService(), new FakeResponse());

            controller.Register("", "12346");

            var fakeResponse = (FakeResponse)controller.Response;

            Assert.AreEqual("Email cannot be empty.", fakeResponse.OutputText.ToString());
        }
Exemple #13
0
 public static string WriteErrorMessage(HttpController controller)
 {
     if (controller.Failed)
     {
         return($@"#warning {(controller.UnexpectedFailure ? "PLEASE MAKE A GITHUB REPO ISSUE" : "")} {controller.Name}Controller {(controller.UnexpectedFailure ? "has failed generation with unexpected error" : "is misconfigured for generation")} :: {controller.Error.Replace('\r', ' ').Replace('\n', ' ')}");
     }
     else
     {
         return(null);
     }
 }
Exemple #14
0
        public static void BeforeFeature()
        {
            HttpController.Init(() => "http://www.bing.com");
            HttpSteps.AddVariableLookupShortKey("SearchModel", typeof(SearchModel).FullName);
            var searchModel = new SearchModel
            {
                Term = "tree"
            };

            FeatureContext.Current.Add(searchModel.GetType().FullName, searchModel);
        }
 public override void AddController(HttpController httpController, bool multiprocessing)
 {
     if (multiprocessing)
     {
         AddController(httpController, DEFAULT_PROCESSING_GROUP_MULTI, multiprocessing);
     }
     else
     {
         AddController(httpController, DEFAULT_PROCESSING_GROUP_SIMPLE, multiprocessing);
     }
 }
Exemple #16
0
        public ProxyView()
        {
            InitializeComponent();

            if (App.isElevated)
            {
                this.PacAdminPrivilegeTextBlock.Foreground = Application.Current.Resources["GreenBrush"] as Brush;
                this.PacAdminPrivilegeTextBlock.Text       = LanguageResources.Instance["SETTING_PAC_SERVER_NOW_ADMIN"];
                this.PacPortNumberTextBox.IsEnabled        = true;
            }
            else
            {
                this.PacAdminPrivilegeTextBlock.Foreground = Application.Current.Resources["RedBrush"] as Brush;
                this.PacAdminPrivilegeTextBlock.Text       = LanguageResources.Instance["SETTING_PAC_SERVER_NEED_ADMIN"];
                this.PacPortNumberTextBox.IsEnabled        = false;
            }

            // 프록시 서버
            this.useStartup = Config.Proxy.startup;
            if (Config.Proxy.startup)
            {
                this.useProxyServer = true;
            }
            // PAC 서버
            this.usePac = Config.Proxy.usePac;
            this.PacDomainTextBox.Text     = Config.Proxy.pacDomain;
            this.PacPortNumberTextBox.Text = Config.Proxy.pacPort.ToString();
            this.useDecryptSsl             = Config.Proxy.decryptSsl;
            this.PortNumberTextBox.Text    = Config.Proxy.port.ToString();
            // 경유 프록시
            this.useUpstreamProxy = Config.Proxy.upstreamProxy;
            this.UpstreamProxyHostTextBox.Text = Config.Proxy.upstreamHost;
            this.UpstreamProxyPortTextBox.Text = Config.Proxy.upstreamPort.ToString();
            // 패킷 변조
            this.useRandomAdjutant = Config.Adjutant.useRandomAdjutant;
            this.setRandomAdjutant = "0,0,0,0";
            try
            {
                this.DollWhitelistTextBox.Text = string.Join(",", Config.Adjutant.dollWhitelist.Select(x => x.ToString()));
                this.DollBlacklistTextBox.Text = string.Join(",", Config.Adjutant.dollBlacklist.Select(x => x.ToString()));
                this.SkinWhitelistTextBox.Text = string.Join(",", Config.Adjutant.skinWhitelist.Select(x => x.ToString()));
                this.SkinBlacklistTextBox.Text = string.Join(",", Config.Adjutant.skinBlacklist.Select(x => x.ToString()));
            }
            catch { }
            this.setAdjutantSkin  = Config.Adjutant.adjutantSkinCategory;
            this.setAdjutantShape = Config.Adjutant.adjutantShape;

            HttpController http = new HttpController();

            // 언어 새로고침
            InitLanguage();

            this.Loaded += ProxyView2_Loaded;
        }
Exemple #17
0
            public static string WriteClassInterface(HttpController controller)
            {
                return
                    ($@"
{SharedWriter.GetObsolete(controller)}
public interface I{controller.ClientName} : I{Settings.ClientInterfaceName}
{{
{string.Join($"{Environment.NewLine}", controller.GetEndpoints().Select(WriteEndpointInterface))}
}}
");
            }
Exemple #18
0
            public static string WriteController(HttpController controller)
            {
                return
                    ($@"
{(controller.NamespaceSuffix != null ? $@"namespace {controller.NamespaceSuffix}
{{" : string.Empty)}

{WriteClassInterface(controller)}

{WriteClassImplementation(controller)}

{(controller.NamespaceSuffix != null ? $@"}}" : string.Empty)}
");
            }
        public void AddEntry(string destinationPath, string processingGroup, HttpController httpController, MethodInfo methodInfo)
        {
            //1. check whether path is valid
            if (!IsPathValid(destinationPath))
            {
                throw new Exception("Destination Path is in an invalid format: " + destinationPath);
            }
            //2. check whether path is distinct
            if (!IsPathDisjunct(destinationPath))
            {
                throw new Exception("Destination Path is not distinct: " + destinationPath);
            }

            //3. create and add route
            RoutingEntry routingEntry = new RoutingEntry(processingGroup, httpController, methodInfo, "Rx" + _counter++, destinationPath, destinationPath.Split('/').Length);

            _routingTree.AddPath(destinationPath, routingEntry);
        }
Exemple #20
0
            public static string GetRoute(HttpController controller, HttpEndpoint endpoint, bool async)
            {
                const string RouteParseRegex = @"{([^}]+)}";

                string routeUnformatted = endpoint.GetFullRoute(controller);

                var patterns = Regex.Matches(routeUnformatted, RouteParseRegex);

                var routeParameters = endpoint.GetRouteParameters().ToList();
                var queryParameters = endpoint.GetQueryParameters().ToList();

                foreach (var group in patterns)
                {
                    Match    match    = group as Match;
                    string   filtered = match.Value.Replace("{", "").Replace("}", "");
                    string[] split    = filtered.Split(new char[] { ':' });

                    string variable = split[0];


                    if (!routeParameters.Any(x => x.Name.Equals(variable, StringComparison.CurrentCultureIgnoreCase)))
                    {
                        throw new Exception($"{variable} is missing from passed in parameters. Please check your route.");
                    }
                    var parameter = routeParameters.SingleOrDefault(x => x.Name.Equals(variable, StringComparison.CurrentCultureIgnoreCase));
                    if (Helpers.IsRoutableType(parameter.Type))
                    {
                        routeUnformatted = routeUnformatted.Replace(match.Value, $"{{{Helpers.GetRouteStringTransform(parameter.Name, parameter.Type)}}}");
                    }
                }

                if (queryParameters.Any())
                {
                    string queryString = $"?{string.Join("&", queryParameters.Select(x => WriteQueryParameter(x, async)))}";

                    routeUnformatted += $"{queryString}";
                }



                routeUnformatted = routeUnformatted.Replace($"[{Constants.ControllerRouteReserved}]", $"{{{Constants.ControllerRouteReserved}}}");
                routeUnformatted = routeUnformatted.Replace($"[{Constants.ActionRouteReserved}]", $"{{{Constants.ActionRouteReserved}}}");
                return(routeUnformatted);
            }
Exemple #21
0
            public static string WriteEndpointImplementation(HttpController controller, HttpEndpoint endpoint)
            {
                return
                    ($@"

{SharedWriter.GetObsolete(endpoint)}
public {GetImplementationReturnType(endpoint.ReturnType, false)} {endpoint.Name}
(
{string.Join($",{Environment.NewLine}", endpoint.GetParameters().Select(SharedWriter.GetParameter))}
)
{{
{GetMethodDetails(controller, endpoint, false, false)}
}}

{SharedWriter.GetObsolete(endpoint)}
public {GetImplementationReturnType(nameof(HttpResponseMessage), false)} {endpoint.Name}Raw
(
{string.Join($",{Environment.NewLine}", endpoint.GetParametersWithoutResponseTypes().Select(SharedWriter.GetParameter))}
)
{{
{GetMethodDetails(controller, endpoint, false, true)}
}}

{SharedWriter.GetObsolete(endpoint)}
public {GetImplementationReturnType(endpoint.ReturnType, true)} {endpoint.Name}Async
(
{string.Join($",{Environment.NewLine}", endpoint.GetParameters().Select(SharedWriter.GetParameter))}
)
{{
{GetMethodDetails(controller, endpoint, true, false)}
}}

{SharedWriter.GetObsolete(endpoint)}
public {GetImplementationReturnType(nameof(HttpResponseMessage), true)} {endpoint.Name}RawAsync
(
{string.Join($",{Environment.NewLine}", endpoint.GetParametersWithoutResponseTypes().Select(SharedWriter.GetParameter))}
)
{{
{GetMethodDetails(controller, endpoint, true, true)}
}}

");
            }
Exemple #22
0
            public static string GetMethodDetails(HttpController controller, HttpEndpoint endpoint, bool async, bool raw)
            {
                var cancellationToken = endpoint.GetRequestModifiers().OfType <CancellationTokenModifier>().SingleOrDefault();
                var clientDependency  = new ClientDependency($"I{Settings.ClientInterfaceName}Wrapper");

                var requestModifiers = endpoint.GetRequestModifiers().ToList();

                var    bodyParameter = endpoint.GetBodyParameter();
                string bodyVariable  = bodyParameter?.Name ?? "null";

                var responseTypes = endpoint.GetResponseTypes();

                var routeConstraints = endpoint.GetRouteConstraints(controller);

                return
                    ($@"{string.Join(Environment.NewLine, routeConstraints.Select(WriteRouteConstraint).NotNull())}
{GetEndpointInfoVariables(controller, endpoint)}
string url = $@""{GetRoute(controller, endpoint, async)}"";
HttpResponseMessage response = null;
response = {GetAwait(async)}HttpOverride.GetResponseAsync({GetHttpMethod(endpoint.HttpType)}, url, null, {cancellationToken.Name}){GetAsyncEnding(async)};

if(response == null)
{{
	try
	{{
		response = {GetAwait(async)}{clientDependency.GetDependencyName($"I{Settings.ClientInterfaceName}")}.{nameof(IClientWrapper.ClientWrapper)}
					.Request(url)
{string.Join($"				{Environment.NewLine}", requestModifiers.Select(WriteRequestModifiers).NotNull())}
					.AllowAnyHttpStatus()
					{GetHttpMethod(endpoint)}
					{GetAsyncEnding(async)};
	}}
	catch({nameof(FlurlHttpException)} fhex)
	{{
{WriteResponseType(responseTypes.OfType<ExceptionResponseType>().Single(), async, false)}
{WriteErrorActionResultReturn(endpoint, async, raw)}
	}}

	{GetAwait(async)}HttpOverride.OnNonOverridedResponseAsync({GetHttpMethod(endpoint.HttpType)}, url, {bodyVariable}, response, {cancellationToken.Name}){GetAsyncEnding(async)};
}}
{string.Join(Environment.NewLine, responseTypes.Where(x => x.GetType() != typeof(ExceptionResponseType)).Select(x => WriteResponseType(x, async, raw)).NotNull())}
{WriteActionResultReturn(endpoint, async, raw)}");
            }
Exemple #23
0
        public async void upload(WaitForm f)
        {
            var r = await HttpController.UploadReport(data[index], Program.periods[form.periodList.SelectedIndex]);

            f.Close();
            if (!r.ContainsKey("create") || !r.ContainsKey("edit"))
            {
                MessageBox.Show("Произшла ошибка!");
            }
            else
            if ((r.ContainsKey("create") && r["create"].code == System.Net.HttpStatusCode.OK) &&
                (r.ContainsKey("edit") && r["edit"].code == System.Net.HttpStatusCode.OK))
            {
                MessageBox.Show("Отчет загружен успешно");
            }
            else
            {
                MessageBox.Show("Произшла ошибка!");
            }
        }
Exemple #24
0
            public static string GetEndpointInfoVariables(HttpController controller, HttpEndpoint endpoint)
            {
                var controllerVar = $@"var {Constants.ControllerRouteReserved} = ""{endpoint.Parent.Name}"";";
                var actionVar     = $@"var {Constants.ActionRouteReserved} = ""{endpoint.Name}"";";


                if (!endpoint.GetFullRoute(controller).Contains($"[{Constants.ControllerRouteReserved}]"))
                {
                    controllerVar = null;
                }

                if (!endpoint.GetFullRoute(controller).Contains($"[{Constants.ActionRouteReserved}]"))
                {
                    actionVar = null;
                }


                return
                    ($@"{controllerVar}
{actionVar}");
            }
Exemple #25
0
        public async void upload(WaitForm f)
        {
            var errors = new List <String>();

            Cursor = Cursors.WaitCursor;
            foreach (var h in data)
            {
                try
                {
                    var r = await HttpController.UploadReport(h, Program.periods[periodList.SelectedIndex]);

                    if (!r.ContainsKey("create") || !r.ContainsKey("edit"))
                    {
                        errors.Add(h.House);
                    }
                    else
                    if ((r.ContainsKey("create") && r["create"].code != System.Net.HttpStatusCode.OK) ||
                        (r.ContainsKey("edit") && r["edit"].code != System.Net.HttpStatusCode.OK))
                    {
                        errors.Add(h.House);
                    }
                }catch (Exception e)
                {
                    errors.Add(h.House);
                }
            }
            Cursor = Cursors.Arrow;
            f.Close();
            if (errors.Count == 0)
            {
                MessageBox.Show("Отчеты загружены успешно");
            }
            else
            {
                var form = new ErrorForm(errors);
                form.ShowDialog();
            }
        }
Exemple #26
0
            public static string WriteClassImplementation(HttpController controller)
            {
                var dependencies = controller.GetInjectionDependencies().ToList();

                dependencies.Insert(0, new ClientDependency($"I{Settings.ClientInterfaceName}Wrapper"));

                return
                    ($@"
{SharedWriter.GetObsolete(controller)}
{(Settings.UseInternalClients ? "internal" : "public")} class {controller.ClientName} : I{controller.ClientName}
{{
{string.Join($"{Environment.NewLine}", dependencies.Select(WriteDependenciesField))}

	public {controller.ClientName}(
{string.Join($",{Environment.NewLine}", dependencies.Select(WriteDependenciesParameter))})
	{{
{string.Join($"{Environment.NewLine}", dependencies.Select(WriteDependenciesAssignment))}
	}}

{string.Join($"{Environment.NewLine}", controller.GetEndpoints().Select(x => WriteEndpointImplementation(controller, x)))}
}}
");
            }
 public override void AddController(HttpController httpController, string processingGroup, bool multiprocessing)
 {
     if (!_httpProcessors.ContainsKey(processingGroup))
     {
         AddProcessor(processingGroup, multiprocessing);
     }
     else
     {
         //if the existing processing group has not the preferred type
         if (_httpProcessors[processingGroup].IsMultiProcessor != multiprocessing)
         {
             throw new Exception("Cannot add controller since preferred processing group is multiprocessing=" + !multiprocessing);
         }
     }
     //set service reference
     httpController.Service = this;
     //set provisional UUID if not set
     if (httpController.Uuid == null)
     {
         httpController.Uuid = httpController.GetType().GUID.ToString() + "_AUTO";
     }
     RegisterMethods(processingGroup, httpController);
 }
Exemple #28
0
        //
        // ====================================================================================================
        //
        public override string Post(string url)
        {
            HttpController httpRequest = new HttpController();

            return(httpRequest.postUrl(url));
        }
Exemple #29
0
        //
        // ====================================================================================================
        //
        public override string Post(string url, System.Collections.Specialized.NameValueCollection requestArguments)
        {
            HttpController httpRequest = new HttpController();

            return(httpRequest.postUrl(url, requestArguments));
        }
Exemple #30
0
        //
        // ====================================================================================================
        /// <summary>
        /// Simple http get of a url
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public override string Get(string url)
        {
            HttpController httpRequest = new HttpController();

            return(httpRequest.getURL(url));
        }