public Func<Type[], IHandler> CreateGenericClass(IReadOnlyList<ServiceDescription> serviceDescriptionChain, MethodDescription methodDescription, ServicePath path)
 {
     var type = CreateType(serviceDescriptionChain, methodDescription, path);
     if (type.IsGenericType)
         return t => (IHandler)Activator.CreateInstance(type.MakeGenericType(t), codecContainer);
     return t => (IHandler)Activator.CreateInstance(type, codecContainer);
 }
Exemple #2
0
 public GenericHandler(ICodecContainer codecContainer, IRawHandlerFactory delegateFactory, IReadOnlyList<ServiceDescription> serviceDescriptionChain, MethodDescription methodDescription, ServicePath servicePath)
 {
     rawHandlers = new ConcurrentDictionary<TypesKey, IHandler>();
     createRawHandler = delegateFactory.CreateGenericClass(serviceDescriptionChain, methodDescription, servicePath);
     genericParameterCount = methodDescription.GenericParameters.Count;
     typeCodec = codecContainer.GetManualCodecFor<Type>();
 }
        private static bool TryDecodeRequest(HttpListenerRequest httpWebRequest, out Request request)
        {
            var urlMatch = UrlEx.Match(httpWebRequest.Url.ToString());

            if (!urlMatch.Success)
            {
                request = null;
                return(false);
            }

            ServicePath servicePath;

            if (!ServicePath.TryParse(urlMatch.Groups[1].Value, out servicePath))
            {
                request = null;
                return(false);
            }

            var scope = httpWebRequest.Headers["scope"];

            if (string.IsNullOrWhiteSpace(scope))
            {
                scope = null;
            }

            var data = new byte[httpWebRequest.ContentLength64];

            using (var stream = httpWebRequest.InputStream)
            {
                stream.Read(data, 0, data.Length);
            }

            request = new Request(servicePath, scope, data);
            return(true);
        }
 public RestProperties(string baseUrl, ServicePath servicePath, RestHeader restHeader, RestQueryParameter restQueryParameter)
 {
     this.BaseUrl            = baseUrl;
     this.ServicePath        = servicePath;
     this.RestHeader         = restHeader;
     this.RestQueryParameter = restQueryParameter;
 }
 ///<summary>Sets the static time and ACL properties.</summary>
 protected override void OnInit(System.EventArgs e)
 {
     if (ServicePath.Substring(0, 1) == "/")
     {
         string Port   = Page.Request.ServerVariables["SERVER_PORT"];
         string Server =
             (Page.Request.IsSecureConnection) ?
             ("http://" + Page.Request.ServerVariables["SERVER_NAME"] + ((Port != "" && Port != "443") ? (":" + Port) : "")) :
             ("http://" + Page.Request.ServerVariables["SERVER_NAME"] + ((Port != "" && Port != "80") ? (":" + Port) : ""));
         ServicePath = Server + ServicePath;
     }
     if (UnauthorizedUrl == "" && ServicePath != "")
     {
         UnauthorizedUrl = NavClient.UnauthorizedUrl();
     }
     if (URL_ACL == null && ConnectionString == "" && ServicePath != "")
     {
         URL_ACL = NavClient.ACL();
     }
     OnInit(Page.Request.ApplicationPath);
     //CHG0131014 - OTSP/SUBRO/PRB0047380/SECURITY FIXES - Remove additional logs
     //AppLogger.Logger.Log("Redirect url:" + Page.Request.ServerVariables["SCRIPT_NAME"].ToLower());
     //AppLogger.Logger.Log("User Name:" + Page.User.Identity.Name);
     //CHG0131014 - OTSP/SUBRO/PRB0047380/SECURITY FIXES - Remove additional logs
     if (Auto && !CheckAccess(Page.Request.ServerVariables["SCRIPT_NAME"].ToLower(), Page.User))
     {
         AppLogger.Logger.Log("Page not authorized, redirecting to UnauthorizedUrl");
         Page.Response.Redirect(UnauthorizedUrl);
     }
     Visible = false;
     if (typeof(CSAAWeb.WebControls.PageTemplate).IsInstanceOfType(Page))
     {
         ((CSAAWeb.WebControls.PageTemplate)Page).NavACL = this;
     }
 }
        private bool TryDecodeRequest(byte[] inputData, out Request requestData)
        {
            int    uriDataLength = BitConverter.ToInt32(inputData, 0);
            string uriData       = Encoding.UTF8.GetString(inputData, 4, uriDataLength);

            if (string.IsNullOrEmpty(uriData))
            {
                requestData = null;
                return(false);
            }

            Uri uri = new Uri(uriData);

            ServicePath servicePath;

            if (!ServicePath.TryParse(uri.LocalPath, out servicePath))
            {
                requestData = null;
                return(false);
            }

            string scope = string.IsNullOrEmpty(uri.Query) || uri.Query.Length < 8 ? "" : uri.Query.Substring(7);

            byte[] data = new byte[inputData.Length - uriDataLength - 4];
            Buffer.BlockCopy(inputData, uriDataLength + 4, data, 0, inputData.Length - uriDataLength - 4);

            requestData = new Request(servicePath, scope, data);
            return(true);
        }
Exemple #7
0
 public Request(ServicePath servicePath, string serviceScope, byte[] data)
 {
     if (servicePath == null)
         throw new ArgumentNullException("servicePath", "Service path cannot be null");
     Path = servicePath;
     ServiceScope = serviceScope;
     Data = data;
 }
        public HttpHelper(IOptions <ServicePath> path, IOptions <ApiKeys> keys, RadarrClient radarrClient, TMDBClient tmdbClient)
        {
            _keys = keys.Value;
            _path = path.Value;

            _radarrClient = radarrClient;
            _tmdbClient   = tmdbClient;
        }
Exemple #9
0
        public ActionResult DeleteConfirmed(int id)
        {
            ServicePath servicePath = db.ServicePaths.Find(id);

            db.ServicePaths.Remove(servicePath);
            db.SaveChanges();
            return(RedirectToAction("Index"));
        }
Exemple #10
0
        public IHandler CreateHandler(ServiceDescription rootDescription, ServicePath path)
        {
            var serviceDescriptionChain = CreateServiceDescriptionChain(rootDescription, path);
            var methodDescription       = GetMethodDescription(serviceDescriptionChain, path);

            return(methodDescription.GenericParameters.Any()
                ? new GenericHandler(codecContainer, rawHandlerFactory, serviceDescriptionChain, methodDescription, path)
                : rawHandlerFactory.CreateGenericClass(serviceDescriptionChain, methodDescription, path)(null));
        }
Exemple #11
0
        private ServicePath GetServicePathConfiguration()
        {
            var servicePath = new ServicePath();

            configurationBuilder.GetSection("settings:Path")
            .Bind(servicePath);

            return(servicePath);
        }
Exemple #12
0
 public AdminController(IOptions <ServicePath> path, IMediator mediator, IMediaDbContext context, UserManager <ApplicationUser> userManager, RoleManager <IdentityRole> roleManager, IOptions <ApiKeys> apikeys)
 {
     _mediator    = mediator;
     _context     = context;
     _userManager = userManager;
     _roleManager = roleManager;
     _apikeys     = apikeys.Value;
     _path        = path.Value;
 }
        public async Task <ResponseBase> GetOrderAsync(decimal milkNeed, decimal coffeNeed, decimal waterNeed, bool milkCheck, bool coffeCheck, bool waterCheck)
        {
            var httpClient  = new HttpClient();
            var servicePath = new ServicePath();
            var getResponse = await httpClient.GetStringAsync(new Uri(string.Format(servicePath.ServiceURL + "component/getoffer?milkNeed={0}&coffeNeed={1}&waterNeed={2}&milkCheck={3}&coffeCheck={4}&waterCheck={5}", milkNeed, coffeNeed, waterNeed, milkCheck, coffeCheck, waterCheck)));

            var response = JsonConvert.DeserializeObject <ResponseBase>(getResponse);

            return(response);
        }
Exemple #14
0
        public async Task <List <Coffe_CoffeSize_View> > GetCoffeSizesAsync(int coffeId)
        {
            var httpClient  = new HttpClient();
            var servicePath = new ServicePath();
            var getResponse = await httpClient.GetStringAsync(new Uri(servicePath.ServiceURL + "coffesizemapping/getcoffesizes?coffeId=" + coffeId));

            var getCoffeSizes = JsonConvert.DeserializeObject <List <Coffe_CoffeSize_View> >(getResponse);

            return(getCoffeSizes);
        }
        public async Task <List <Coffe> > GetCoffesAsync()
        {
            var httpClient  = new HttpClient();
            var servicePath = new ServicePath();
            var getResponse = await httpClient.GetStringAsync(new Uri(servicePath.ServiceURL + "coffe/getcoffes"));

            var getCoffes = JsonConvert.DeserializeObject <List <Coffe> >(getResponse);

            return(getCoffes);
        }
        public async Task <List <Component> > GetStockDataAsync()
        {
            var httpClient  = new HttpClient();
            var servicePath = new ServicePath();
            var getResponse = await httpClient.GetStringAsync(new Uri(string.Format(servicePath.ServiceURL + "component/getstockdata")));

            var response = JsonConvert.DeserializeObject <List <Component> >(getResponse);

            return(response);
        }
        public void Trivial()
        {
            var implementationInfo = new ServiceImplementationInfo();
            var path = new ServicePath("MyService", "MyMethod");
            var handler = (ServiceMethodHandler)((i, d) => new byte[0]);
            factory.CreateMethodHandler(implementationInfo, path).Returns(handler);

            var handler1 = container.GetMethodHandler(implementationInfo, path);
            var handler2 = container.GetMethodHandler(implementationInfo, path);

            Assert.That(handler1, Is.EqualTo(handler2));
        }
        public void Trivial()
        {
            var serviceDescription = new ServiceDescriptionBuilder(new MethodDescriptionBuilder()).Build(typeof(ITrivialService));
            var path = new ServicePath("MyService", "MyMethod");
            var handler = Substitute.For<IHandler>();
            factory.CreateHandler(serviceDescription, path).Returns(handler);

            var handler1 = container.GetHandler(serviceDescription, path);
            var handler2 = container.GetHandler(serviceDescription, path);

            Assert.That(handler1, Is.EqualTo(handler2));
        }
        public void Trivial()
        {
            var implementationInfo = new ServiceImplementationInfo();
            var path    = new ServicePath("MyService", "MyMethod");
            var handler = (ServiceMethodHandler)((i, d) => new byte[0]);

            factory.CreateMethodHandler(implementationInfo, path).Returns(handler);

            var handler1 = container.GetMethodHandler(implementationInfo, path);
            var handler2 = container.GetMethodHandler(implementationInfo, path);

            Assert.That(handler1, Is.EqualTo(handler2));
        }
        public void Trivial()
        {
            var serviceDescription = new ServiceDescriptionBuilder(new MethodDescriptionBuilder()).Build(typeof(ITrivialService));
            var path    = new ServicePath("MyService", "MyMethod");
            var handler = Substitute.For <IHandler>();

            factory.CreateHandler(serviceDescription, path).Returns(handler);

            var handler1 = container.GetHandler(serviceDescription, path);
            var handler2 = container.GetHandler(serviceDescription, path);

            Assert.That(handler1, Is.EqualTo(handler2));
        }
        // GET: ServicePaths/Delete/5
        public ActionResult Delete(int?userId)
        {
            if (userId == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            ServicePath servicePath = db.ServicePaths.Find(userId);

            if (servicePath == null)
            {
                return(HttpNotFound());
            }
            return(RedirectToAction("ServicePath", new { userId = servicePath.ServiceProviderId }));
        }
        /// <summary>
        /// 获取初始化参数配置信息
        /// </summary>
        /// <param name="servicePath"></param>
        public static void saveServicePath(ServicePath servicePath)
        {
            var doc = new XmlDocument();

            doc.Load(MXmlPath);
            var nodeVerify    = doc.SelectSingleNode("//ElementTable[@TableName='VerifyUser']/ElementInfo");
            var elementVerify = nodeVerify as XmlElement;

            elementVerify.SetAttribute("UserName", servicePath.UserName);
            elementVerify.SetAttribute("PassWord", servicePath.PassWord);
            //调用框架服务地址
            setSerivePathXmlNode(doc, "ServicePath", "Package", servicePath.PackagePath);
            setSerivePathXmlNode(doc, "ServicePath", "Prodef", servicePath.ProdefPath);
            setSerivePathXmlNode(doc, "ServicePath", "Actdef", servicePath.ActdefPath);
            setSerivePathXmlNode(doc, "ServicePath", "Department", servicePath.DepartmentPath);
            setSerivePathXmlNode(doc, "ServicePath", "User", servicePath.DeparmentUserPath);
            setSerivePathXmlNode(doc, "ServicePath", "Bizdef", servicePath.BizdefPath);
            setSerivePathXmlNode(doc, "ServicePath", "BizdefForm", servicePath.BizdefFormPath);
            setSerivePathXmlNode(doc, "ServicePath", "ServiceIP", servicePath.ServiceIP);

            //Chorme驱动地址
            setSerivePathXmlNode(doc, "ChromeDriver", "ChromeDriverUrl", servicePath.ChromeDriverPath);

            //Iframe配置

            setSerivePathXmlNode(doc, "Iframe", "FirstPageIframe", servicePath.FirstPageIframeName);
            setSerivePathXmlNode(doc, "Iframe", "CreateProIframe", servicePath.CreateProIframeName);
            setSerivePathXmlNode(doc, "Iframe", "WorkFlowFrameIframe", servicePath.WorkFlowFrameIfram);
            setSerivePathXmlNode(doc, "Iframe", "DataCategory", servicePath.DataCategoryPath);
            //登陆相关设置
            setSerivePathXmlNode(doc, "Login", "LoginUrl", servicePath.LoginUrl);
            setSerivePathXmlNode(doc, "Login", "LoginUserName", servicePath.LoginUserName);
            setSerivePathXmlNode(doc, "Login", "LoginPassWord", servicePath.LoginPassWord);

            //数据库连接设置
            setSerivePathXmlNode(doc, "DBConnection", "DbName", servicePath.DbName);
            setSerivePathXmlNode(doc, "DBConnection", "DbUserName", servicePath.DbUserName);
            setSerivePathXmlNode(doc, "DBConnection", "DbPassWord", servicePath.DbPassWord);

            doc.Save(MXmlPath);
            servicePath.IsOrginal = false;
            _mServicePath         = servicePath;
            if (m_objDataSource != null)
            {
                m_objDataSource.Close();
                m_objDataSource.Dispose();
                m_objDataSource = null;
            }
            var temp = MObjDataSource;//重新连接数据库
        }
Exemple #23
0
        public ActionResult CreateServicePath(ServicePath servicePath)
        {
            if (ModelState.IsValid)
            {
                servicePath.CreationDate         = DateTime.Now;
                servicePath.LastModificationDate = DateTime.Now;
                db.ServicePaths.Add(servicePath);
                db.SaveChanges();
                return(RedirectToAction("ServicePath", new { userId = servicePath.ServiceProviderId }));
            }


            return(View(servicePath));
        }
Exemple #24
0
        // GET: ServicePaths/Details/5
        public ActionResult Details(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            ServicePath servicePath = db.ServicePaths.Find(id);

            if (servicePath == null)
            {
                return(HttpNotFound());
            }
            return(View(servicePath));
        }
Exemple #25
0
        // GET: /EditServicePath
        public ActionResult EditServicePath(int?userId)
        {
            if (userId == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            ServicePath servicePath = db.ServicePaths.Find(userId);

            if (servicePath == null)
            {
                return(HttpNotFound());
            }
            return(View(servicePath));
        }
        private Func <Type[], IHandler> CreateClass(params string[] path)
        {
            var serviceDescriptionChain = new List <ServiceDescription> {
                globalServiceDescription
            };

            for (int i = 1; i < path.Length - 1; i++)
            {
                serviceDescriptionChain.Add(serviceDescriptionChain.Last().Subservices.Single(x => x.Name == path[i]));
            }
            var methodDescription = serviceDescriptionChain.Last().Methods.Single(x => x.Name == path.Last());
            var servicePath       = new ServicePath(path);

            return(factory.CreateGenericClass(serviceDescriptionChain, methodDescription, servicePath));
        }
Exemple #27
0
        public async Task Given_a_service_path_check_is_blocked(string pathService)
        {
            // Arrange UnBlock Services
            await _client.GetAsync(string.Concat(UrlHost, "api/farfetch/v1/gateway/blockallservices"));

            // Act
            var service = new ServicePath()
            {
                Path = pathService
            };
            var resultValue = await _client.PostAsync <dynamic>(string.Concat(UrlHost, pathService), service);

            // Assert
            Assert.That(resultValue, Is.EqualTo(""));
        }
Exemple #28
0
        public ActionResult Create(ServicePath servicePath)
        {
            if (ModelState.IsValid)
            {
                servicePath.CreationDate         = DateTime.Now;
                servicePath.LastModificationDate = DateTime.Now;
                db.ServicePaths.Add(servicePath);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            ViewBag.CreatorId         = new SelectList(db.Users, "Id", "Sex", servicePath.CreatorId);
            ViewBag.ModifierId        = new SelectList(db.Users, "Id", "Sex", servicePath.ModifierId);
            ViewBag.ServiceProviderId = new SelectList(db.Users, "Id", "Sex", servicePath.ServiceProviderId);
            return(View(servicePath));
        }
Exemple #29
0
        // GET: ServicePaths/Edit/5
        public ActionResult Edit(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            ServicePath servicePath = db.ServicePaths.Find(id);

            if (servicePath == null)
            {
                return(HttpNotFound());
            }
            ViewBag.CreatorId         = new SelectList(db.Users, "Id", "Sex", servicePath.CreatorId);
            ViewBag.ModifierId        = new SelectList(db.Users, "Id", "Sex", servicePath.ModifierId);
            ViewBag.ServiceProviderId = new SelectList(db.Users, "Id", "Sex", servicePath.ServiceProviderId);
            return(View(servicePath));
        }
Exemple #30
0
        public ActionResult EditServicePath(ServicePath servicePath)
        {
            if (ModelState.IsValid)
            {
                ServicePath origin = db.ServicePaths.Where(y => y.id == servicePath.id).First();
                origin.Name    = servicePath.Name;
                origin.Cost    = servicePath.Cost;
                origin.Enabled = servicePath.Enabled;
                origin.LastModificationDate = DateTime.Now;
                origin.Message         = servicePath.Message;
                origin.Ratio           = servicePath.Ratio;
                db.Entry(origin).State = EntityState.Modified;
                db.SaveChanges();
                return(RedirectToAction("ServicePath", new { userId = origin.ServiceProviderId }));
            }

            return(View(servicePath));
        }
Exemple #31
0
        private static bool TryDecodeRequest(HttpListenerRequest httpWebRequest, out Request request)
        {
            using (var inputStream = httpWebRequest.InputStream)
            {
                ServicePath servicePath;
                if (!ServicePath.TryParse(httpWebRequest.Url.LocalPath, out servicePath))
                {
                    request = null;
                    return(false);
                }

                var scope = httpWebRequest.QueryString["scope"];
                var data  = inputStream.ReadToEnd(httpWebRequest.ContentLength64);

                request = new Request(servicePath, scope, data);
                return(true);
            }
        }
Exemple #32
0
 public ActionResult Edit(ServicePath servicePath)
 {
     if (ModelState.IsValid)
     {
         ServicePath origin = db.ServicePaths.Where(y => y.id == servicePath.id).First();
         origin.Name    = servicePath.Name;
         origin.Cost    = servicePath.Cost;
         origin.Enabled = servicePath.Enabled;
         origin.LastModificationDate = DateTime.Now;
         origin.Message         = servicePath.Message;
         origin.Ratio           = servicePath.Ratio;
         db.Entry(origin).State = EntityState.Modified;
         db.SaveChanges();
         return(RedirectToAction("Index"));
     }
     ViewBag.CreatorId         = new SelectList(db.Users, "Id", "Sex", servicePath.CreatorId);
     ViewBag.ModifierId        = new SelectList(db.Users, "Id", "Sex", servicePath.ModifierId);
     ViewBag.ServiceProviderId = new SelectList(db.Users, "Id", "Sex", servicePath.ServiceProviderId);
     return(View(servicePath));
 }
        public async Task <ComponentStocks> ConfirmOrderAsync(decimal milkNeed, decimal coffeNeed, decimal waterNeed, bool milkCheck, bool coffeCheck, bool waterCheck)
        {
            var httpClient  = new HttpClient();
            var servicePath = new ServicePath();

            ComponentUpdate componentUpdate = new ComponentUpdate();

            componentUpdate.MilkNeed   = milkNeed;
            componentUpdate.CoffeNeed  = coffeNeed;
            componentUpdate.WaterNeed  = waterNeed;
            componentUpdate.ExtraMilk  = milkCheck;
            componentUpdate.ExtraCoffe = coffeCheck;
            componentUpdate.ExtraWater = waterCheck;

            var serialazeJSON = JsonConvert.SerializeObject(componentUpdate);
            var returnResult  = await httpClient.PutAsync(servicePath.ServiceURL + "component/confirmorder", new StringContent(serialazeJSON, Encoding.UTF8, "application/json"));

            var contents = await returnResult.Content.ReadAsStringAsync();

            ComponentStocks response = JsonConvert.DeserializeObject <ComponentStocks>(contents);

            return(response);
        }
Exemple #34
0
 public SearchMovieByNameHandler(IOptions <ApiKeys> apikeys, IOptions <ServicePath> path)
 {
     _apikeys = apikeys.Value;
     _path    = path.Value;
 }
Exemple #35
0
        public byte[] Process(Type serviceInterface, string pathSeparatedBySlashes, string serviceScope, byte[] data, TimeoutSettings timeoutSettings)
        {
            ServicePath path;

            if (!ServicePath.TryParse(pathSeparatedBySlashes, out path))
            {
                throw new InvalidOperationException(string.Format("'{0}' is not a valid service path", pathSeparatedBySlashes));
            }

            var serviceName = serviceInterface.GetServiceName();
            var endPoint    = topology.GetEndPoint(serviceName, serviceScope);
            var sender      = requestSenderContainer.GetSender(endPoint.Protocol);
            var request     = new Request(path, serviceScope, data);

            timeoutSettings = timeoutSettings ?? TimeoutSettings.NoTimeout;

            bool hasNetworkTimeout      = timeoutSettings.MaxMilliseconds != -1 && timeoutSettings.MaxMilliseconds != 0 && timeoutSettings.MaxMilliseconds != int.MaxValue;
            var  startTime              = DateTime.Now;
            int  remainingTriesMinusOne = timeoutSettings.NotReadyRetryCount;

            while (remainingTriesMinusOne >= 0)
            {
                remainingTriesMinusOne--;

                Response response;
                try
                {
                    int?networkTimeout = hasNetworkTimeout ? timeoutSettings.MaxMilliseconds - (DateTime.Now - startTime).Milliseconds : (int?)null;
                    response = sender.Send(endPoint.Host, endPoint.Port, request, networkTimeout);
                }
                catch (TimeoutException ex)
                {
                    throw new ServiceTimeoutException(request, timeoutSettings.MaxMilliseconds, ex);
                }
                catch (Exception ex)
                {
                    throw new ServiceNetworkException(string.Format("Sending a '{0}' request to {1} failed", pathSeparatedBySlashes, endPoint), ex);
                }

                switch (response.Status)
                {
                case ResponseStatus.Ok:
                    return(response.Data);

                case ResponseStatus.NotReady:
                    if (remainingTriesMinusOne >= 0)
                    {
                        Thread.Sleep(timeoutSettings.NotReadyRetryMilliseconds);
                    }
                    break;

                case ResponseStatus.BadRequest:
                    throw new ServiceTopologyException(string.Format("'{0}' seems to be a bad request for {1}",
                                                                     pathSeparatedBySlashes, endPoint));

                case ResponseStatus.ServiceNotFound:
                    throw new ServiceTopologyException(string.Format("'{0}' service was not present at {1}",
                                                                     serviceName, endPoint));

                case ResponseStatus.Exception:
                {
                    Exception remoteException;
                    if (exceptionCodec.TryDecodeSingle(response.Data, out remoteException))
                    {
                        throw remoteException;
                    }
                    throw new ServiceNetworkException(
                              string.Format("'{0}' request caused {1} to return an unknown exception",
                                            pathSeparatedBySlashes, endPoint));
                }

                case ResponseStatus.InternalServerError:
                    throw new Exception(string.Format("'{0}' request caused {1} to encounter an internal server error",
                                                      pathSeparatedBySlashes, endPoint));

                default:
                    throw new ArgumentOutOfRangeException("response.Status");
                }
            }

            throw new ServiceTimeoutException(request, timeoutSettings.NotReadyRetryCount, timeoutSettings.NotReadyRetryMilliseconds);
        }
        /// <summary>
        /// Max page value for specified service path object
        /// </summary>
        /// <param name="navigationPageSize"></param>
        /// <param name="p"></param>
        /// <returns></returns>
        public int GetLastPage(int navigationPageSize, ServicePath p)
        {
            string path = "";
            int navigationLastPage = 0;

            if (p == ServicePath.GetXLeas)
            {
                path = "xLeas";
            }
            else if (p == ServicePath.GetXLeasByXSchool)
            {
                path = "xSchools/{refId}/xLeas";
            }
            else if (p == ServicePath.GetXLeasByXRoster)
            {
                path = "xRosters/{refId}/xLeas";
            }
            else if (p == ServicePath.GetXLeasByXStaff)
            {
                path = "xStaffs/{refId}/xLeas";
            }
            else if (p == ServicePath.GetXLeasByXStudent)
            {
                path = "xStudents/{refId}/xLeas";
            }
            else if (p == ServicePath.GetXLeasByXContact)
            {
                path = "xContacts/{refId}/xLeas";
            }
            else if (p == ServicePath.GetXSchools)
            {
                path = "xSchools";
            }
            else if (p == ServicePath.GetXSchoolsByXLea)
            {
                path = "xLeas/{refId}/xSchools";
            }
            else if (p == ServicePath.GetXSchoolsByXCalendar)
            {
                path = "xCalendars/{refId}/xSchools";
            }
            else if (p == ServicePath.GetXSchoolsByXCourse)
            {
                path = "xCourses/{refId}/xSchools";
            }
            else if (p == ServicePath.GetXSchoolsByXRoster)
            {
                path = "xRosters/{refId}/xSchools";
            }
            else if (p == ServicePath.GetXSchoolsByXStaff)
            {
                path = "xStaffs/{refId}/xSchools";
            }
            else if (p == ServicePath.GetXSchoolsByXStudent)
            {
                path = "xStudents/{refId}/xSchools";
            }
            else if (p == ServicePath.GetXSchoolsByXContact)
            {
                path = "xContacts/{refId}/xSchools";
            }
            else if (p == ServicePath.GetXCalendars)
            {
                path = "xCalendars";
            }
            else if (p == ServicePath.GetXCalendarsByXLea)
            {
                path = "xLeas/{refId}/xCalendars";
            }
            else if (p == ServicePath.GetXCalendarsByXSchool)
            {
                path = "xSchools/{refId}/xCalendars";
            }
            else if (p == ServicePath.GetXCourses)
            {
                path = "xCourses";
            }
            else if (p == ServicePath.GetXCoursesByXLea)
            {
                path = "xLeas/{refId}/xCourses";
            }
            else if (p == ServicePath.GetXCoursesByXSchool)
            {
                path = "xSchools/{refId}/xCourses";
            }
            else if (p == ServicePath.GetXCoursesByXRoster)
            {
                path = "xRosters/{refId}/xCourses";
            }
            else if (p == ServicePath.GetXRosters)
            {
                path = "xRosters";
            }
            else if (p == ServicePath.GetXRostersByXLea)
            {
                path = "xLeas/{refId}/xRosters";
            }
            else if (p == ServicePath.GetXRostersByXSchool)
            {
                path = "xSchools/{refId}/xRosters";
            }
            else if (p == ServicePath.GetXRostersByXCourse)
            {
                path = "xCourses/{refId}/xRosters";
            }
            else if (p == ServicePath.GetXRostersByXStaff)
            {
                path = "xStaffs/{refId}/xRosters";
            }
            else if (p == ServicePath.GetXRostersByXStudent)
            {
                path = "xStudents/{refId}/xRosters";
            }
            else if (p == ServicePath.GetXStaffs)
            {
                path = "xStaffs";
            }
            else if (p == ServicePath.GetXStaffsByXLea)
            {
                path = "xLeas/{refId}/xStaffs";
            }
            else if (p == ServicePath.GetXStaffsByXSchool)
            {
                path = "xSchools/{refId}/xStaffs";
            }
            else if (p == ServicePath.GetXStaffsByXCourse)
            {
                path = "xCourses/{refId}/xStaffs";
            }
            else if (p == ServicePath.GetXStaffsByXRoster)
            {
                path = "xRosters/{refId}/xStaffs";
            }
            else if (p == ServicePath.GetXStaffsByXStudent)
            {
                path = "xStudents/{refId}/xStaffs";
            }
            else if (p == ServicePath.GetXStudents)
            {
                path = "xStudents";
            }
            else if (p == ServicePath.GetXStudentsByXLea)
            {
                path = "xLeas/{refId}/xStudents";
            }
            else if (p == ServicePath.GetXStudentsByXSchool)
            {
                path = "xSchools/{refId}/xStudents";
            }
            else if (p == ServicePath.GetXStudentsByXRoster)
            {
                path = "xRosters/{refId}/xStudents";
            }
            else if (p == ServicePath.GetXStudentsByXStaff)
            {
                path = "xStaffs/{refId}/xStudents";
            }
            else if (p == ServicePath.GetXStudentsByXContact)
            {
                path = "xContacts/{refId}/xStudents";
            }
            else if (p == ServicePath.GetXContacts)
            {
                path = "xContacts";
            }
            else if (p == ServicePath.GetXContactsByXLea)
            {
                path = "xLeas/{refId}/xContacts";
            }
            else if (p == ServicePath.GetXContactsByXSchool)
            {
                path = "xSchools/{refId}/xContacts";
            }
            else if (p == ServicePath.GetXContactsByXStudent)
            {
                path = "xStudents/{refId}/xContacts";
            }

            RestRequest request = new RestRequest(path, Method.GET);
            request.AddHeader("Accept", "application/json");
            request.AddHeader("navigationPage", "1");
            request.AddHeader("navigationPageSize", navigationPageSize.ToString());

            var response = restClient.Execute(request);

            try
            {
                navigationLastPage = Int32.Parse(response.Headers.ToList()
                .Find(x => x.Name.Equals("navigationLastPage", StringComparison.CurrentCultureIgnoreCase))
                .Value.ToString());
            }
            catch(NullReferenceException)
            {
                navigationLastPage = 0;
            }

            return navigationLastPage;
        }
        private Type CreateType(IReadOnlyList<ServiceDescription> serviceDescriptionChain, MethodDescription methodDescription, ServicePath path)
        {
            int disambiguator = Interlocked.Increment(ref classNameDisambiguator);
            var typeBuilder = moduleBuilder.DefineType("__rpc_handler_" + string.Join(".", path) + "_" + disambiguator,
                                            TypeAttributes.Public | TypeAttributes.Sealed | TypeAttributes.Class,
                                            typeof(object), new[] { typeof(IHandler) });

            var genericTypeParameterBuilders = methodDescription.GenericParameters.Any()
                ? typeBuilder.DefineGenericParameters(methodDescription.GenericParameters.Select(x => x.Name).ToArray())
                : new GenericTypeParameterBuilder[0];

            var fieldCache = new HandlerClassFieldCache(typeBuilder);
            var classContext = new HandlerClassBuildingContext(serviceDescriptionChain, methodDescription, typeBuilder, genericTypeParameterBuilders, fieldCache);

            CreateMethodDelegate(classContext);
            CreateConstructor(classContext);

            return typeBuilder.CreateType();
        }
        public ServiceMethodHandler CreateMethodHandler(ServiceImplementationInfo serviceImplementationInfo, ServicePath servicePath)
        {
            var serviceInterface = serviceImplementationInfo.Interface;

            var dynamicMethod = new DynamicMethod(
                "__srpc__handle__" + serviceInterface.FullName + "__" + string.Join("_", servicePath),
                typeof(byte[]), ParameterTypes, Assembly.GetExecutingAssembly().ManifestModule);
            var il = dynamicMethod.GetILGenerator();
            var locals = new LocalVariableCollection(il, true);

            il.Emit(OpCodes.Ldarg_0);                                           // stack_0 = (TServiceImplementation) arg_0
            il.Emit(OpCodes.Castclass, serviceInterface);

            var serviceDesc = serviceImplementationInfo.Description;
            for (int i = 1; i < servicePath.Length - 1; i++)
            {
                var propertyInfo = serviceDesc.Type.GetProperty(servicePath[i]);
                il.Emit(OpCodes.Callvirt, propertyInfo.GetGetMethod());         // stack_0 = stack_0.Property
                SubserviceDescription subserviceDescription;
                if (!serviceDesc.TryGetSubservice(servicePath[i], out subserviceDescription))
                    throw new InvalidPathException();
                serviceDesc = subserviceDescription.Service;
            }

            var methodName = servicePath.MethodName;
            var methodInfo = serviceDesc.Type.GetMethod(methodName);
            MethodDescription methodDesc;
            if (!serviceDesc.TryGetMethod(methodName, out methodDesc))
                throw new InvalidPathException();

            bool hasRetval = methodDesc.ReturnType != typeof(void);
            var parameters = methodDesc.Parameters.Select((x, i) => new ParameterNecessity
                {
                    Description = x,
                    Codec = codecContainer.GetEmittingCodecFor(x.Type),
                    LocalVariable = x.Way != MethodParameterWay.Val ? il.DeclareLocal(x.Type) : null,
                    ArgumentIndex = i
                })
                .ToArray();

            var requestParameters = parameters
                    .Where(x => x.Description.Way == MethodParameterWay.Val || x.Description.Way == MethodParameterWay.Ref)
                    .ToArray();

            var responseParameters = parameters
                .Where(x => x.Description.Way == MethodParameterWay.Ref || x.Description.Way == MethodParameterWay.Out)
                .ToArray();

            LocalBuilder requestDataPointerVar = null;
            if (requestParameters.Any())
            {
                il.Emit(OpCodes.Ldarg_1);                                   // remainingBytes = arg_1.Length
                il.Emit(OpCodes.Ldlen);
                il.Emit(OpCodes.Stloc, locals.RemainingBytes);
                requestDataPointerVar =                                     // var pinned dataPointer = pin(arg_1)
                    il.Emit_PinArray(typeof(byte), locals, 1);
                il.Emit(OpCodes.Ldloc, requestDataPointerVar);              // data = dataPointer
                il.Emit(OpCodes.Stloc, locals.DataPointer);
            }

            foreach (var parameter in parameters)
            {
                switch (parameter.Description.Way)
                {
                    case MethodParameterWay.Val:
                        parameter.Codec.EmitDecode(il, locals, false);      // stack_i = decode(data, remainingBytes, false)
                        break;
                    case MethodParameterWay.Ref:
                        parameter.Codec.EmitDecode(il, locals, false);      // param_i = decode(data, remainingBytes, false)
                        il.Emit(OpCodes.Stloc, parameter.LocalVariable);
                        il.Emit(OpCodes.Ldloca, parameter.LocalVariable);   // stack_i = *param_i
                        break;
                    case MethodParameterWay.Out:
                        il.Emit(OpCodes.Ldloca, parameter.LocalVariable);   // stack_i = *param_i
                        break;
                    default:
                        throw new ArgumentOutOfRangeException();
                }
            }

            if (requestParameters.Any())
            {
                il.Emit_UnpinArray(requestDataPointerVar);                  // unpin(dataPointer)
            }

            il.Emit(OpCodes.Callvirt, methodInfo);                          // stack_0 = stack_0.Method(stack_1, stack_2, ...)

            if (hasRetval || responseParameters.Any())
            {
                IEmittingCodec retvalCodec = null;
                LocalBuilder retvalVar = null;

                if (hasRetval)
                {
                    retvalCodec = codecContainer.GetEmittingCodecFor(methodDesc.ReturnType);
                    retvalVar = il.DeclareLocal(methodDesc.ReturnType);             // var ret = stack_0
                    il.Emit(OpCodes.Stloc, retvalVar);
                    retvalCodec.EmitCalculateSize(il, retvalVar);                   // stack_0 = calculateSize(ret)
                }

                bool hasSizeOnStack = hasRetval;
                foreach (var parameter in responseParameters)
                {
                    parameter.Codec.EmitCalculateSize(il, parameter.LocalVariable); // stack_0 += calculateSize(param_i)
                    if (hasSizeOnStack)
                        il.Emit(OpCodes.Add);
                    else
                        hasSizeOnStack = true;
                }

                var dataArrayVar = il.DeclareLocal(typeof(byte[]));                 // var dataArray = new byte[size of retval]
                il.Emit(OpCodes.Newarr, typeof(byte));
                il.Emit(OpCodes.Stloc, dataArrayVar);

                var responseDataPointerVar =                                        // var pinned dataPointer = pin(dataArrayVar)
                        il.Emit_PinArray(typeof(byte), locals, dataArrayVar);
                il.Emit(OpCodes.Ldloc, responseDataPointerVar);                     // data = dataPointer
                il.Emit(OpCodes.Stloc, locals.DataPointer);

                foreach (var parameter in responseParameters)
                    parameter.Codec.EmitEncode(il, locals, parameter.LocalVariable);// encode(data, param_i)

                if (hasRetval)
                    retvalCodec.EmitEncode(il, locals, retvalVar);                  // encode(data, ret)

                il.Emit_UnpinArray(responseDataPointerVar);                         // unpin(dataPointer)
                il.Emit(OpCodes.Ldloc, dataArrayVar);                               // stack_0 = dataArray
            }
            else
            {
                il.Emit(OpCodes.Ldc_I4, 0);                                         // stack_0 = new byte[0]
                il.Emit(OpCodes.Newarr, typeof(byte));
            }

            il.Emit(OpCodes.Ret);
            return (ServiceMethodHandler)dynamicMethod.CreateDelegate(typeof(ServiceMethodHandler));
        }
 public ServiceMethodHandler GetMethodHandler(ServiceImplementationInfo serviceImplementationInfo, ServicePath servicePath)
 {
     return handlers.GetOrAdd(servicePath, p => factory.CreateMethodHandler(serviceImplementationInfo, p));
 }
 public IHandler GetHandler(ServiceDescription serviceDescription, ServicePath path)
 {
     return handlers.GetOrAdd(path, p => factory.CreateHandler(serviceDescription, p));
 }