public void Add(Type type, object instance, bool includeInManifest) { _entries[type] = new ServiceEntry { Instance = instance, IncludeInManifest = includeInManifest }; }
public static XmlDocument BuildAddRq(ServiceEntry se, ServiceDetail sd) { try { XmlDocument doc = XmlUtils.MakeRequestDocument(); XmlElement parent = XmlUtils.MakeRequestParentElement(doc); RotoTrackDb db = new RotoTrackDb(); UserProfile u = db.UserProfiles.Find(sd.TechnicianId); Vehicle v = db.Vehicles.Find(sd.VehicleId); DSR dsr = db.DSRs.Include("WorkOrder").First(f => f.Id == se.DSRId); Customer c = db.Customers.Find(dsr.WorkOrder.CustomerId); MileageRate mr = db.MileageRates.Find(sd.MileageRateId); Area a = db.Areas.Find(u.AreaId); XmlElement Rq = doc.CreateElement("VehicleMileageAddRq"); parent.AppendChild(Rq); XmlElement RqType = doc.CreateElement("VehicleMileageAdd"); Rq.AppendChild(RqType); XmlElement VehicleRef = doc.CreateElement("VehicleRef"); RqType.AppendChild(VehicleRef); VehicleRef.AppendChild(XmlUtils.MakeSimpleElem(doc, "ListID", v.QBListId)); XmlElement CustomerRef = doc.CreateElement("CustomerRef"); RqType.AppendChild(CustomerRef); CustomerRef.AppendChild(XmlUtils.MakeSimpleElem(doc, "ListID", dsr.WorkOrder.QBListId)); XmlElement ItemRef = doc.CreateElement("ItemRef"); RqType.AppendChild(ItemRef); ItemRef.AppendChild(XmlUtils.MakeSimpleElem(doc, "ListID", mr.QBListId)); XmlElement ClassRef = doc.CreateElement("ClassRef"); RqType.AppendChild(ClassRef); ClassRef.AppendChild(XmlUtils.MakeSimpleElem(doc, "ListID", a.QBListId)); RqType.AppendChild(XmlUtils.MakeSimpleElem(doc, "TripStartDate", se.DateWorked.ToString("yyyy-MM-dd"))); RqType.AppendChild(XmlUtils.MakeSimpleElem(doc, "TripEndDate", se.DateWorked.ToString("yyyy-MM-dd"))); RqType.AppendChild(XmlUtils.MakeSimpleElem(doc, "TotalMiles", se.Mileage.ToString())); string fullName = ""; if (!string.IsNullOrEmpty(u.FirstName)) fullName += u.FirstName; if (!string.IsNullOrEmpty(u.LastName)) fullName += (" " + u.LastName); fullName += " guid="; fullName += se.GUID; RqType.AppendChild(XmlUtils.MakeSimpleElem(doc, "Notes", fullName)); RqType.AppendChild(XmlUtils.MakeSimpleElem(doc, "BillableStatus", "Billable")); return doc; } catch (Exception e) { string evLogTxt = ""; evLogTxt = "Error building vehicle mileage add request! " + e.Message + "\r\n"; Logging.RototrackErrorLog("QBMigrationTool: " + RototrackConfig.GetBuildType() + ": " + evLogTxt); return null; } }
internal override void Create(SlpReader reader) { base.Create(reader); var tmp = reader.ReadInt16(); var result = new ServiceEntry[tmp]; for (int i = 0; i < tmp; i++) { result[i] = Slp.Services.Locator.GetInstance<ServiceEntry>(reader); } Services = new ReadOnlyCollection<ServiceEntry>(result); }
public virtual ServiceEntry CreateServiceEntry(SlpReader reader) { if (reader.ReadByte() != 0) throw new ServiceProtocolException(ServiceErrorCode.ParseError); var result = new ServiceEntry(); result.Lifetime = reader.ReadTimeSpan(); result.Uri = new ServiceUri(reader.ReadString()); var count = reader.ReadByte(); for (int i = 0; i < count; i++) { var a = CreateAuthenticationBlock(reader); result.AuthBlocks.Add(a); ServiceEntry.OnAuthenticated(result, a); } return result; }
public Task Handle(HttpContext context, ServiceEntry serviceEntry) { throw new System.NotImplementedException(); }
private void WhenIAddAServiceBackIn(ServiceEntry serviceEntryTwo) { _consulServices.Add(serviceEntryTwo); }
internal AuthenticatedEventArgs(ServiceEntry serviceEntry, AuthenticationBlock auth) : base() { ServiceEntry = serviceEntry; Authentication = auth; }
public static async Task <ServiceEntry[]> AvaliableServices(string consulAgentUrl, string name, string tags = "") { bool flag = false; int j; string str; Func <string, string> func = null; List <ServiceEntry> serviceEntries = new List <ServiceEntry>(); ConsulClient consulClient = new ConsulClient((ConsulClientConfiguration config) => config.Address = new Uri(consulAgentUrl)); try { string str1 = tags; char[] chrArray = new char[] { ',' }; string[] strArrays = str1.Split(chrArray); for (int i = 0; i < (int)strArrays.Length; i++) { string str2 = strArrays[i]; IHealthEndpoint health = consulClient.Health; string str3 = name; if (!string.IsNullOrEmpty(str2)) { str = str2; } else { str = null; } CancellationToken cancellationToken = new CancellationToken(); ConfiguredTaskAwaitable <QueryResult <ServiceEntry[]> > configuredTaskAwaitable = health.Service(str3, str, true, cancellationToken).ConfigureAwait(false); ServiceEntry[] response = await configuredTaskAwaitable.Response; for (j = 0; j < (int)response.Length; j++) { ServiceEntry serviceEntry = response[j]; List <ServiceEntry> serviceEntries1 = serviceEntries; if (!serviceEntries1.Any <ServiceEntry>((ServiceEntry service) => (service.Service.Address != serviceEntry.Service.Address ? false : service.Service.Port == serviceEntry.Service.Port))) { serviceEntries.Add(serviceEntry); } } !flag; } !flag; string str4 = tags; chrArray = new char[] { ',' }; string[] strArrays1 = str4.Split(chrArray); for (j = 0; j < (int)strArrays1.Length; j++) { string str5 = strArrays1[j]; if (!string.IsNullOrEmpty(str5)) { List <ServiceEntry> serviceEntries2 = serviceEntries; List <ServiceEntry> list = serviceEntries2.Where <ServiceEntry>((ServiceEntry service) => { string[] strArrays2 = service.Service.Tags; if (func == null) { func = (string t) => t.Trim().ToLower(); } return(!strArrays2.Select <string, string>(func).Contains <string>(str5.ToLower())); }).ToList <ServiceEntry>(); foreach (ServiceEntry serviceEntry1 in list) { serviceEntries.Remove(serviceEntry1); } } } !flag; } finally { if (consulClient != null) { ((IDisposable)consulClient).Dispose(); } } return(serviceEntries.ToArray()); }
public void should_handle_request_to_consul_for_downstream_service_and_make_request_no_re_routes_and_rate_limit() { const int consulPort = 8523; const string serviceName = "web"; const int downstreamServicePort = 8187; var downstreamServiceOneUrl = $"http://localhost:{downstreamServicePort}"; var fakeConsulServiceDiscoveryUrl = $"http://localhost:{consulPort}"; var serviceEntryOne = new ServiceEntry() { Service = new AgentService() { Service = serviceName, Address = "localhost", Port = downstreamServicePort, ID = "web_90_0_2_224_8080", Tags = new[] { "version-v1" } }, }; var consulConfig = new FileConfiguration { DynamicReRoutes = new List <FileDynamicReRoute> { new FileDynamicReRoute { ServiceName = serviceName, RateLimitRule = new FileRateLimitRule() { EnableRateLimiting = true, ClientWhitelist = new List <string>(), Limit = 3, Period = "1s", PeriodTimespan = 1000 } } }, GlobalConfiguration = new FileGlobalConfiguration { ServiceDiscoveryProvider = new FileServiceDiscoveryProvider { Host = "localhost", Port = consulPort }, RateLimitOptions = new FileRateLimitOptions() { ClientIdHeader = "ClientId", DisableRateLimitHeaders = false, QuotaExceededMessage = "", RateLimitCounterPrefix = "", HttpStatusCode = 428 }, DownstreamScheme = "http", } }; var configuration = new FileConfiguration { GlobalConfiguration = new FileGlobalConfiguration { ServiceDiscoveryProvider = new FileServiceDiscoveryProvider { Host = "localhost", Port = consulPort } } }; this.Given(x => x.GivenThereIsAServiceRunningOn(downstreamServiceOneUrl, "/something", 200, "Hello from Laura")) .And(x => GivenTheConsulConfigurationIs(consulConfig)) .And(x => x.GivenThereIsAFakeConsulServiceDiscoveryProvider(fakeConsulServiceDiscoveryUrl, serviceName)) .And(x => x.GivenTheServicesAreRegisteredWithConsul(serviceEntryOne)) .And(x => _steps.GivenThereIsAConfiguration(configuration)) .And(x => _steps.GivenOcelotIsRunningUsingConsulToStoreConfig()) .When(x => _steps.WhenIGetUrlOnTheApiGatewayMultipleTimesForRateLimit("/web/something", 1)) .Then(x => _steps.ThenTheStatusCodeShouldBe(200)) .When(x => _steps.WhenIGetUrlOnTheApiGatewayMultipleTimesForRateLimit("/web/something", 2)) .Then(x => _steps.ThenTheStatusCodeShouldBe(200)) .When(x => _steps.WhenIGetUrlOnTheApiGatewayMultipleTimesForRateLimit("/web/something", 1)) .Then(x => _steps.ThenTheStatusCodeShouldBe(428)) .BDDfy(); }
public ServicePackageImpl(AbstractBundle bundle, ServiceEntry serviceEntry) { this.bundle = bundle; this.serviceEntry = serviceEntry; }
public static XmlDocument BuildAddRq(ServiceEntry se, ServiceDetail sd, int serviceId, decimal hours) { try { XmlDocument doc = XmlUtils.MakeRequestDocument(); XmlElement parent = XmlUtils.MakeRequestParentElement(doc); RotoTrackDb db = new RotoTrackDb(); UserProfile u = db.UserProfiles.Find(sd.TechnicianId); ServiceType st = db.ServiceTypes.Find(serviceId); DSR dsr = db.DSRs.Include("WorkOrder").First(f => f.Id == se.DSRId); Customer c = db.Customers.Find(dsr.WorkOrder.CustomerId); Area a = db.Areas.Find(u.AreaId); XmlElement Rq = doc.CreateElement("TimeTrackingAddRq"); parent.AppendChild(Rq); XmlElement RqType = doc.CreateElement("TimeTrackingAdd"); Rq.AppendChild(RqType); RqType.AppendChild(XmlUtils.MakeSimpleElem(doc, "TxnDate", se.DateWorked.ToString("yyyy-MM-dd"))); XmlElement EntityRef = doc.CreateElement("EntityRef"); RqType.AppendChild(EntityRef); EntityRef.AppendChild(XmlUtils.MakeSimpleElem(doc, "ListID", u.QBListId)); XmlElement CustomerRef = doc.CreateElement("CustomerRef"); RqType.AppendChild(CustomerRef); CustomerRef.AppendChild(XmlUtils.MakeSimpleElem(doc, "ListID", dsr.WorkOrder.QBListId)); XmlElement ItemServiceRef = doc.CreateElement("ItemServiceRef"); RqType.AppendChild(ItemServiceRef); ItemServiceRef.AppendChild(XmlUtils.MakeSimpleElem(doc, "ListID", st.QBListId)); HoursMinutes hrsMins = GetHoursMinutesFromDecimal(hours); int hoursInteger = hrsMins.Hours; int minutesInteger = hrsMins.Minutes; string duration = "PT" + hoursInteger.ToString() + "H" + minutesInteger.ToString() + "M" + "0S"; RqType.AppendChild(XmlUtils.MakeSimpleElem(doc, "Duration", duration)); XmlElement ClassRef = doc.CreateElement("ClassRef"); RqType.AppendChild(ClassRef); ClassRef.AppendChild(XmlUtils.MakeSimpleElem(doc, "ListID", a.QBListId)); string notes = "guid=" + se.GUID; RqType.AppendChild(XmlUtils.MakeSimpleElem(doc, "Notes", notes)); if (st.Name.ToUpper().StartsWith("DIRECT")) { RqType.AppendChild(XmlUtils.MakeSimpleElem(doc, "BillableStatus", "Billable")); } else { RqType.AppendChild(XmlUtils.MakeSimpleElem(doc, "BillableStatus", "NotBillable")); } return doc; } catch (Exception e) { string evLogTxt = ""; evLogTxt = "Error building time tracking add request! " + e.Message + "\r\n"; Logging.RototrackErrorLog("QBMigrationTool: " + RototrackConfig.GetBuildType() + ": " + evLogTxt); return null; } }
private string MakeServicePackage(ServiceEntry service) { return("com.mobius." + service.service + ".v" + service.version.Replace('/', '_')); }
public void ParseJCDFile(string jcdFile, string classpath, string java_home) { // load file XmlDocument doc = new XmlDocument(); doc.Load(new XmlTextReader(jcdFile)); // target XmlNode targetNode = doc[en.jcd][en.target]; if (target == null && targetNode != null) { // only set once in top-level package target = ((XmlElement)targetNode).GetAttribute("name"); } // java_home XmlNode jdkNode = doc[en.jcd][en.jdk]; if (jdkNode != null) { java_home = JCDParserResults.JDKToJAVA_HOME(((XmlElement)jdkNode).GetAttribute("version")); } XmlNode java_homeNode = doc[en.jcd][en.java_home]; if (java_homeNode != null) { java_home = ((XmlElement)java_homeNode).GetAttribute("path"); } java_home = java_home.ToLower(); // only set once in top-level package if (component_java_home == null) { component_java_home = java_home; } // classpath XmlNode classpathParentNode = doc[en.jcd][en.classpath]; if (classpathParentNode != null) { classpath = ""; XmlNodeList classpathNodes = classpathParentNode.ChildNodes; foreach (XmlNode classpathNode in classpathNodes) { if (classpathNode.LocalName == en.path) { classpath += ((XmlElement)classpathNode).GetAttribute("value") + ";"; } } classpath = classpath.TrimEnd(new char[] { ';' }); classpath = Environment.ExpandEnvironmentVariables(classpath); } classpath = classpath.ToLower(); // services XmlNode servicesParentNode = doc[en.jcd][en.services]; if (servicesParentNode != null) { foreach (XmlNode serviceNode in servicesParentNode.ChildNodes) { if (serviceNode.LocalName == en.service) { ServiceEntry e = new ServiceEntry(); XmlNode taskJdkNode = serviceNode[en.jdk]; XmlNode taskJava_HomeNode = serviceNode[en.java_home]; XmlNode taskClasspathParentNode = serviceNode[en.classpath]; if (taskJava_HomeNode != null) { e.java_home = ((XmlElement)taskJava_HomeNode).GetAttribute("path"); } else if (taskJdkNode != null) { e.java_home = JCDParserResults.JDKToJAVA_HOME(((XmlElement)taskJdkNode).GetAttribute("version")); } else { e.java_home = java_home; } e.classpath = classpath; if (taskClasspathParentNode != null) { XmlNodeList classpathNodes = taskClasspathParentNode.ChildNodes; e.classpath = ""; foreach (XmlNode classpathNode in classpathNodes) { if (classpathNode.LocalName == en.path) { e.classpath += ((XmlElement)classpathNode).GetAttribute("value") + ";"; } } e.classpath = e.classpath.TrimEnd(new char[] { ';' }); e.classpath = Environment.ExpandEnvironmentVariables(e.classpath); } e.service = ((XmlElement)serviceNode).GetAttribute("name"); e.version = ((XmlElement)serviceNode).GetAttribute("version"); serviceList.Add(e); } } } // compilation tasks XmlNode complistParentNode = doc[en.jcd][en.complist]; if (complistParentNode != null) { XmlNodeList complistTaskNodes = complistParentNode.ChildNodes; foreach (XmlNode complistTaskNode in complistTaskNodes) { if (complistTaskNode.NodeType == XmlNodeType.Comment) { continue; } string taskTool = complistTaskNode.LocalName; XmlNode taskJdkNode = complistTaskNode[en.jdk]; string taskJava_Home = (taskJdkNode != null) ? JCDParserResults.JDKToJAVA_HOME(((XmlElement)taskJdkNode).GetAttribute("version")) : java_home; XmlNode taskJava_HomeNode = complistTaskNode[en.java_home]; taskJava_Home = (taskJava_HomeNode != null) ? ((XmlElement)taskJava_HomeNode).GetAttribute("path") : taskJava_Home; XmlNode taskClasspathParentNode = complistTaskNode[en.classpath]; string taskClasspath = classpath; if (taskClasspathParentNode != null) { taskClasspath = ""; XmlNodeList classpathNodes = taskClasspathParentNode.ChildNodes; foreach (XmlNode classpathNode in classpathNodes) { if (classpathNode.LocalName == en.path) { taskClasspath += ((XmlElement)classpathNode).GetAttribute("value") + ";"; } } taskClasspath = taskClasspath.TrimEnd(new char[] { ';' }); taskClasspath = Environment.ExpandEnvironmentVariables(taskClasspath); } Complist.ComplistKey ck = new Complist.ComplistKey(taskTool, taskJava_Home, taskClasspath); Complist complist = null; foreach (Complist cl in complists) { if (cl.complistKey.Equals(ck)) { complist = cl; } } if (complist == null) { complist = new Complist(ck); complists.Add(complist); } XmlNodeList complistFileNodes = complistTaskNode.ChildNodes; foreach (XmlNode complistFileNode in complistFileNodes) { if (complistFileNode.LocalName != en.file) { continue; } string filename = DepackageFilename(((XmlElement)complistFileNode).GetAttribute("name")); complist.files.Add(filename); } } } // nested packages XmlNode nestedPackageParentNode = doc[en.jcd][en.nestedPackages]; if (nestedPackageParentNode != null) { XmlNodeList nestedPackageNodes = nestedPackageParentNode.ChildNodes; foreach (XmlNode nestedPackageNode in nestedPackageNodes) { if (nestedPackageNode.LocalName != en.package) { continue; } string packageDescriptorName = ((XmlElement)nestedPackageNode).GetAttribute("descriptor"); //check if the package descriptor is in the same directory as the parent string packageDirectory = Path.Combine(Path.GetPathRoot(jcdFile), Path.GetDirectoryName(jcdFile)); string packageFileName = Path.Combine(packageDirectory, packageDescriptorName); //if not, check in sibling pkg directory if (!File.Exists(packageFileName)) { int lastDirectoryPos = packageDirectory.LastIndexOfAny(new char[] { '\\', '/' }); if (lastDirectoryPos > -1) { string packageDirectoryParent = packageDirectory.Substring(0, lastDirectoryPos + 1); packageDirectory = Path.Combine(packageDirectoryParent, "pkg"); packageFileName = Path.Combine(packageDirectory, packageDescriptorName); } } if (!File.Exists(packageFileName)) { throw new Exception("Package descriptor, " + packageDescriptorName + ", not found"); } this.ParseJCDFile(packageFileName, classpath, java_home); } } XmlNode jarIncludesNode = doc[en.jcd][en.jarIncludes]; if (jarIncludesNode != null) { // product files XmlNode productFilesParentNode = jarIncludesNode[en.productFiles]; if (productFilesParentNode != null) { XmlNodeList productFileNodes = productFilesParentNode.ChildNodes; foreach (XmlNode productFileNode in productFileNodes) { if (productFileNode.LocalName == en.file) { CopyEntry ce = new CopyEntry(); string filename = DepackageFilename(((XmlElement)productFileNode).GetAttribute("name")); ce.from = "%BuildPath%\\" + Path.GetExtension(filename).TrimStart(new char[] { '.' }) + Path.DirectorySeparatorChar + filename; XmlNode packageNode = productFileNode[en.package]; if (packageNode != null) { string packagePath = ((XmlElement)packageNode).GetAttribute("name"); ce.to = packagePath.Replace('.', '\\'); } copyList.Add(ce); } else if (productFileNode.LocalName == en.manifest) { XmlElement manifestFileNode = (XmlElement)productFileNode[en.file]; string filename = DepackageFilename(manifestFileNode.GetAttribute("name")); manifest = "%BuildPath%\\" + Path.GetExtension(filename).TrimStart(new char[] { '.' }) + Path.DirectorySeparatorChar + filename; } } } // library files XmlNodeList libraryNodes = jarIncludesNode.ChildNodes; foreach (XmlNode libraryNode in libraryNodes) { if (libraryNode.LocalName != en.library) { continue; } string libraryPath = libraryNode[en.path].GetAttribute("value"); XmlNodeList fileNodes = libraryNode.ChildNodes; foreach (XmlNode fileNode in fileNodes) { if (fileNode.LocalName != en.file) { continue; } CopyEntry ce = new CopyEntry(); string filename = ((XmlElement)fileNode).GetAttribute("name"); ce.from = Path.Combine(libraryPath, filename); ce.to = Path.GetDirectoryName(filename); copyList.Add(ce); } } } // packageSteps XmlNode packageStepsParentNode = doc[en.jcd][en.packageSteps]; if (packageStepsParentNode != null) { XmlNodeList packageSteps = packageStepsParentNode.ChildNodes; foreach (XmlNode packageStep in packageSteps) { string packageStepName = ((XmlElement)packageStep).GetAttribute("name"); packageStepList.Add(packageStepName); } } }
public static XmlDocument BuildAddRq(ServiceEntry se, ServiceDetail sd) { try { XmlDocument doc = XmlUtils.MakeRequestDocument(); XmlElement parent = XmlUtils.MakeRequestParentElement(doc); RotoTrackDb db = new RotoTrackDb(); UserProfile u = db.UserProfiles.Find(sd.TechnicianId); Vehicle v = db.Vehicles.Find(sd.VehicleId); DSR dsr = db.DSRs.Include("WorkOrder").First(f => f.Id == se.DSRId); Customer c = db.Customers.Find(dsr.WorkOrder.CustomerId); MileageRate mr = db.MileageRates.Find(sd.MileageRateId); Area a = db.Areas.Find(u.AreaId); XmlElement Rq = doc.CreateElement("VehicleMileageAddRq"); parent.AppendChild(Rq); XmlElement RqType = doc.CreateElement("VehicleMileageAdd"); Rq.AppendChild(RqType); XmlElement VehicleRef = doc.CreateElement("VehicleRef"); RqType.AppendChild(VehicleRef); VehicleRef.AppendChild(XmlUtils.MakeSimpleElem(doc, "ListID", v.QBListId)); XmlElement CustomerRef = doc.CreateElement("CustomerRef"); RqType.AppendChild(CustomerRef); CustomerRef.AppendChild(XmlUtils.MakeSimpleElem(doc, "ListID", dsr.WorkOrder.QBListId)); XmlElement ItemRef = doc.CreateElement("ItemRef"); RqType.AppendChild(ItemRef); ItemRef.AppendChild(XmlUtils.MakeSimpleElem(doc, "ListID", mr.QBListId)); XmlElement ClassRef = doc.CreateElement("ClassRef"); RqType.AppendChild(ClassRef); ClassRef.AppendChild(XmlUtils.MakeSimpleElem(doc, "ListID", a.QBListId)); RqType.AppendChild(XmlUtils.MakeSimpleElem(doc, "TripStartDate", se.DateWorked.ToString("yyyy-MM-dd"))); RqType.AppendChild(XmlUtils.MakeSimpleElem(doc, "TripEndDate", se.DateWorked.ToString("yyyy-MM-dd"))); RqType.AppendChild(XmlUtils.MakeSimpleElem(doc, "TotalMiles", se.Mileage.ToString())); string fullName = ""; if (!string.IsNullOrEmpty(u.FirstName)) { fullName += u.FirstName; } if (!string.IsNullOrEmpty(u.LastName)) { fullName += (" " + u.LastName); } fullName += " guid="; fullName += se.GUID; RqType.AppendChild(XmlUtils.MakeSimpleElem(doc, "Notes", fullName)); RqType.AppendChild(XmlUtils.MakeSimpleElem(doc, "BillableStatus", "Billable")); return(doc); } catch (Exception e) { string evLogTxt = ""; evLogTxt = "Error building vehicle mileage add request! " + e.Message + "\r\n"; Logging.RototrackErrorLog("QBMigrationTool: " + RototrackConfig.GetBuildType() + ": " + evLogTxt); return(null); } }
public static IApplicationBuilder RegisterConsul(this IApplicationBuilder app, IApplicationLifetime lifetime, ServiceEntry serviceEntity, IConfiguration configuration) { ConsulClientConfiguration consulClientConfiguration = new ConsulClientConfiguration() { Address = new Uri($"http://127.0.0.1:8500") }; var consulClient = new ConsulClient(x => x = consulClientConfiguration);//请求注册的 Consul 地址 var httpCheck = new AgentServiceCheck() { DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(5), //服务启动多久后注册 Interval = TimeSpan.FromSeconds(10), //健康检查时间间隔,或者称为心跳间隔 HTTP = $"http://localhost:51606/api/health", //健康检查地址 Timeout = TimeSpan.FromSeconds(5) }; // Register service with consul var registration = new AgentServiceRegistration() { Checks = new[] { httpCheck }, ID = "donetcore",//Guid.NewGuid().ToString(), Name = "my.servicename1", Address = "localhost", Port = 51606, Tags = new[] { $"urlprefix-/my.servicename" }//添加 urlprefix-/servicename 格式的 tag 标签,以便 Fabio 识别 }; consulClient.Agent.ServiceRegister(registration).Wait();//服务启动时注册,内部实现其实就是使用 Consul API 进行注册(HttpClient发起) lifetime.ApplicationStopping.Register(() => { consulClient.Agent.ServiceDeregister(registration.ID).Wait();//服务停止时取消注册 }); return(app); }
public virtual void KnownTestDataGenericTestData() { ReferenceItems = new List <object>(); using (var session = Database.CreateSession()) { //add some domain 1 var dave = new Person("dave") { Id = "p1", BirthDate = new DateTime(1982, 1, 1) }; var chan = new Person("chan") { Id = "p2", BirthDate = new DateTime(1983, 1, 1) }; var pam = new Person("pam") { Id = "p3", BirthDate = new DateTime(1972, 1, 1) }; var john = new Person("john") { Id = "p4", BirthDate = new DateTime(1972, 1, 1) }; var max = new Person("max") { Id = "p5", BirthDate = new DateTime(1972, 1, 1) }; var book = new Book("using couchdb", dave, 50) { Id = "b1" }; book.AddEdition(new Edition("2nd", EditionType.Electronic) { ReleaseDate = DateTime.Now.AddDays(33) }); book.AddEdition(new Edition("1st", EditionType.Electronic) { ReleaseDate = DateTime.Now }); book.AddEdition(new Edition("1st", EditionType.HardBack) { ReleaseDate = DateTime.Now.AddDays(3) }); book.AddEdition(new Edition("preview", EditionType.Electronic) { ReleaseDate = DateTime.Now.AddDays(-10) }); var book2 = new Book("being awesome", dave, 51) { Id = "b2" }; book2.AddEdition(new Edition("1st", EditionType.Electronic) { ReleaseDate = DateTime.Now.AddDays(50) }); book2.AddEdition(new Edition("preview", EditionType.Electronic) { ReleaseDate = DateTime.Now.AddDays(-30) }); book2.AddContributor(pam, ContributorType.Editor); book2.AddContributor(chan, ContributorType.CoAuthor); var book3 = new Book("being epic with couchdb", chan, 100) { Id = "b3" }; book3.AddEdition(new Edition("1st", EditionType.Electronic) { ReleaseDate = DateTime.Now.AddDays(-10) }); //add some domain 2 var leeloo = new Cat { Id = "c1", Name = "leeloo", RequiresHeatPad = true }; var robbie = new Cat { Id = "c2", Name = "robbie", RequiresHeatPad = false }; var bonnie = new Dog { Id = "d1", Name = "bonnie", NumberOfWalksPerDay = 2 }; var starfire = new Dog { Id = "d2", Name = "starfire", NumberOfWalksPerDay = 1 }; var booking = new KennelBooking() { Animal = leeloo, Start = DateTime.Now, End = DateTime.Now.AddDays(2), Id = "bk1" }; //domain 3 var todo1 = new TodoTask("write an armchair example", PriorityLevel.Medium) { Id = "t1" }; var todo2 = new TodoTask("inital convert armchair to support .net core", PriorityLevel.High) { Id = "t2", IsComplete = true }; //domain 4 var repo = new Repoisitory("armchair") { Members = new Dictionary <string, Access>() { { "dave", Access.Administrator }, { "bob", Access.Contributor } } }; var repo2 = new Repoisitory("awesome-source") { Members = new Dictionary <string, Access>() { { "bob", Access.Administrator } } }; //domain 5 var serviceEntry1 = new ServiceEntry { Id = "se1", Name = "SqlServer", Description = "a sql server database", Tags = new List <string>(new [] { "Database", "Sql", "Relational" }) }; var serviceEntry2 = new ServiceEntry { Id = "se2", Name = "CouchDb", Description = "a document server database", Tags = new List <string>(new [] { "Database", "Document" }) }; var serviceEntry3 = new ServiceEntry { Id = "se3", Name = "PostgreSql", Description = "a relational and document server database", Tags = new List <string>(new [] { "Database", "Document", "Relational", "Sql" }) }; ReferenceItems.Add(dave); ReferenceItems.Add(chan); ReferenceItems.Add(pam); ReferenceItems.Add(john); ReferenceItems.Add(max); ReferenceItems.Add(book); ReferenceItems.Add(book2); ReferenceItems.Add(book3); ReferenceItems.Add(leeloo); ReferenceItems.Add(robbie); ReferenceItems.Add(bonnie); ReferenceItems.Add(starfire); ReferenceItems.Add(booking); ReferenceItems.Add(todo1); ReferenceItems.Add(todo2); ReferenceItems.Add(repo); ReferenceItems.Add(repo2); ReferenceItems.Add(serviceEntry1); ReferenceItems.Add(serviceEntry2); ReferenceItems.Add(serviceEntry3); session.AddRange(ReferenceItems.Cast <EntityRoot>()); session.Commit(); } }
public void should_proxy_websocket_input_to_downstream_service_and_use_service_discovery_and_load_balancer() { var downstreamPort = 5007; var downstreamHost = "localhost"; var secondDownstreamPort = 5008; var secondDownstreamHost = "localhost"; var serviceName = "websockets"; var consulPort = 8509; var fakeConsulServiceDiscoveryUrl = $"http://localhost:{consulPort}"; var serviceEntryOne = new ServiceEntry() { Service = new AgentService() { Service = serviceName, Address = downstreamHost, Port = downstreamPort, ID = Guid.NewGuid().ToString(), Tags = new string[0] }, }; var serviceEntryTwo = new ServiceEntry() { Service = new AgentService() { Service = serviceName, Address = secondDownstreamHost, Port = secondDownstreamPort, ID = Guid.NewGuid().ToString(), Tags = new string[0] }, }; var config = new FileConfiguration { ReRoutes = new List <FileReRoute> { new FileReRoute { UpstreamPathTemplate = "/", DownstreamPathTemplate = "/ws", DownstreamScheme = "ws", LoadBalancerOptions = new FileLoadBalancerOptions { Type = "RoundRobin" }, ServiceName = serviceName, } }, GlobalConfiguration = new FileGlobalConfiguration { ServiceDiscoveryProvider = new FileServiceDiscoveryProvider { Host = "localhost", Port = consulPort, Type = "consul" } } }; this.Given(_ => _steps.GivenThereIsAConfiguration(config)) .And(_ => _steps.StartFakeOcelotWithWebSocketsWithConsul()) .And(_ => GivenThereIsAFakeConsulServiceDiscoveryProvider(fakeConsulServiceDiscoveryUrl, serviceName)) .And(_ => GivenTheServicesAreRegisteredWithConsul(serviceEntryOne, serviceEntryTwo)) .And(_ => StartFakeDownstreamService($"http://{downstreamHost}:{downstreamPort}", "/ws")) .And(_ => StartSecondFakeDownstreamService($"http://{secondDownstreamHost}:{secondDownstreamPort}", "/ws")) .When(_ => WhenIStartTheClients()) .Then(_ => ThenBothDownstreamServicesAreCalled()) .BDDfy(); }
private string MakeServiceDirectory(ServiceEntry service) { return("com\\mobius\\" + service.service + "\\v" + service.version.Replace('/', '_')); }
/// <summary> /// Correct ArgumentException throw by a Dictionary when adding an existing key. /// </summary> void DoAdd( Type s, ServiceEntry e ) { Debug.Assert( !ReferenceEquals( s, null ) ); try { _services.Add( s, e ); } catch( ArgumentException ex ) { if( _services.ContainsKey( s ) ) throw new CKException( ex, CoreResources.ServiceAlreadyRegistered, s.FullName ); throw; } }
public void should_use_token_to_make_request_to_consul() { var token = "abctoken"; var consulPort = RandomPortFinder.GetRandomPort(); var serviceName = "web"; var servicePort = RandomPortFinder.GetRandomPort(); var downstreamServiceOneUrl = $"http://localhost:{servicePort}"; var fakeConsulServiceDiscoveryUrl = $"http://localhost:{consulPort}"; var serviceEntryOne = new ServiceEntry() { Service = new AgentService() { Service = serviceName, Address = "localhost", Port = servicePort, ID = "web_90_0_2_224_8080", Tags = new[] { "version-v1" } }, }; var configuration = new FileConfiguration { Routes = new List <FileRoute> { new FileRoute { DownstreamPathTemplate = "/api/home", DownstreamScheme = "http", UpstreamPathTemplate = "/home", UpstreamHttpMethod = new List <string> { "Get", "Options" }, ServiceName = serviceName, LoadBalancerOptions = new FileLoadBalancerOptions { Type = "LeastConnection" }, } }, GlobalConfiguration = new FileGlobalConfiguration() { ServiceDiscoveryProvider = new FileServiceDiscoveryProvider() { Scheme = "http", Host = "localhost", Port = consulPort, Token = token } } }; this.Given(_ => GivenThereIsAServiceRunningOn(downstreamServiceOneUrl, "/api/home", 200, "Hello from Laura")) .And(_ => GivenThereIsAFakeConsulServiceDiscoveryProvider(fakeConsulServiceDiscoveryUrl, serviceName)) .And(_ => GivenTheServicesAreRegisteredWithConsul(serviceEntryOne)) .And(_ => _steps.GivenThereIsAConfiguration(configuration)) .And(_ => _steps.GivenOcelotIsRunningWithConsul()) .When(_ => _steps.WhenIGetUrlOnTheApiGateway("/home")) .Then(_ => _steps.ThenTheStatusCodeShouldBe(HttpStatusCode.OK)) .And(_ => _steps.ThenTheResponseBodyShouldBe("Hello from Laura")) .And(_ => _receivedToken.ShouldBe(token)) .BDDfy(); }
private void processDay(BIOPDirectoryMessage epgDirectory, int day, ServiceEntry serviceEntry) { BIOPDirectoryMessage dayDirectory = findObject(epgDirectory.Bindings, day.ToString(), "dir") as BIOPDirectoryMessage; if (dayDirectory == null) return; BIOPFileMessage epgFile = findObject(dayDirectory.Bindings, serviceEntry.ReferenceNumber, "fil") as BIOPFileMessage; if (epgFile == null) return; processEPGFile(day, serviceEntry.ServiceID.ToString(), epgFile); }
public void should_handle_request_to_poll_consul_for_downstream_service_and_make_request() { int consulPort = RandomPortFinder.GetRandomPort(); const string serviceName = "web"; int downstreamServicePort = RandomPortFinder.GetRandomPort(); var downstreamServiceOneUrl = $"http://localhost:{downstreamServicePort}"; var fakeConsulServiceDiscoveryUrl = $"http://localhost:{consulPort}"; var serviceEntryOne = new ServiceEntry() { Service = new AgentService() { Service = serviceName, Address = "localhost", Port = downstreamServicePort, ID = $"web_90_0_2_224_{downstreamServicePort}", Tags = new[] { "version-v1" } }, }; var configuration = new FileConfiguration { Routes = new List <FileRoute> { new FileRoute { DownstreamPathTemplate = "/api/home", DownstreamScheme = "http", UpstreamPathTemplate = "/home", UpstreamHttpMethod = new List <string> { "Get", "Options" }, ServiceName = serviceName, LoadBalancerOptions = new FileLoadBalancerOptions { Type = "LeastConnection" }, } }, GlobalConfiguration = new FileGlobalConfiguration() { ServiceDiscoveryProvider = new FileServiceDiscoveryProvider() { Scheme = "http", Host = "localhost", Port = consulPort, Type = "PollConsul", PollingInterval = 0, Namespace = string.Empty } } }; this.Given(x => x.GivenThereIsAServiceRunningOn(downstreamServiceOneUrl, "/api/home", 200, "Hello from Laura")) .And(x => x.GivenThereIsAFakeConsulServiceDiscoveryProvider(fakeConsulServiceDiscoveryUrl, serviceName)) .And(x => x.GivenTheServicesAreRegisteredWithConsul(serviceEntryOne)) .And(x => _steps.GivenThereIsAConfiguration(configuration)) .And(x => _steps.GivenOcelotIsRunningWithConsul()) .When(x => _steps.WhenIGetUrlOnTheApiGatewayWaitingForTheResponseToBeOk("/home")) .Then(x => _steps.ThenTheStatusCodeShouldBe(HttpStatusCode.OK)) .And(x => _steps.ThenTheResponseBodyShouldBe("Hello from Laura")) .BDDfy(); }
public NDistServiceHost(NDistConfig config, ServiceEntry serviceConfig) { _config = config; ServiceEntry = serviceConfig; RootPath = Path.Combine(_config.GetSetting("DefaultServicePath").Value, serviceConfig.Name); }
public static XmlDocument BuildAddRq(ServiceEntry se, ServiceDetail sd, int serviceId, decimal hours) { try { XmlDocument doc = XmlUtils.MakeRequestDocument(); XmlElement parent = XmlUtils.MakeRequestParentElement(doc); RotoTrackDb db = new RotoTrackDb(); UserProfile u = db.UserProfiles.Find(sd.TechnicianId); ServiceType st = db.ServiceTypes.Find(serviceId); DSR dsr = db.DSRs.Include("WorkOrder").First(f => f.Id == se.DSRId); Customer c = db.Customers.Find(dsr.WorkOrder.CustomerId); Area a = db.Areas.Find(u.AreaId); XmlElement Rq = doc.CreateElement("TimeTrackingAddRq"); parent.AppendChild(Rq); XmlElement RqType = doc.CreateElement("TimeTrackingAdd"); Rq.AppendChild(RqType); RqType.AppendChild(XmlUtils.MakeSimpleElem(doc, "TxnDate", se.DateWorked.ToString("yyyy-MM-dd"))); XmlElement EntityRef = doc.CreateElement("EntityRef"); RqType.AppendChild(EntityRef); EntityRef.AppendChild(XmlUtils.MakeSimpleElem(doc, "ListID", u.QBListId)); XmlElement CustomerRef = doc.CreateElement("CustomerRef"); RqType.AppendChild(CustomerRef); CustomerRef.AppendChild(XmlUtils.MakeSimpleElem(doc, "ListID", dsr.WorkOrder.QBListId)); XmlElement ItemServiceRef = doc.CreateElement("ItemServiceRef"); RqType.AppendChild(ItemServiceRef); ItemServiceRef.AppendChild(XmlUtils.MakeSimpleElem(doc, "ListID", st.QBListId)); HoursMinutes hrsMins = GetHoursMinutesFromDecimal(hours); int hoursInteger = hrsMins.Hours; int minutesInteger = hrsMins.Minutes; string duration = "PT" + hoursInteger.ToString() + "H" + minutesInteger.ToString() + "M" + "0S"; RqType.AppendChild(XmlUtils.MakeSimpleElem(doc, "Duration", duration)); XmlElement ClassRef = doc.CreateElement("ClassRef"); RqType.AppendChild(ClassRef); ClassRef.AppendChild(XmlUtils.MakeSimpleElem(doc, "ListID", a.QBListId)); string notes = "guid=" + se.GUID; RqType.AppendChild(XmlUtils.MakeSimpleElem(doc, "Notes", notes)); if (st.Name.ToUpper().StartsWith("DIRECT")) { RqType.AppendChild(XmlUtils.MakeSimpleElem(doc, "BillableStatus", "Billable")); } else { RqType.AppendChild(XmlUtils.MakeSimpleElem(doc, "BillableStatus", "NotBillable")); } return(doc); } catch (Exception e) { string evLogTxt = ""; evLogTxt = "Error building time tracking add request! " + e.Message + "\r\n"; Logging.RototrackErrorLog("QBMigrationTool: " + RototrackConfig.GetBuildType() + ": " + evLogTxt); return(null); } }
private void InsertHandler(Type service, string key, IServiceLocationStrategy serviceLocationStrategy) { ServiceEntry serviceEntry = MakeServiceEntry(service, key); _serviceEntryStore.InsertHandler(serviceEntry, serviceLocationStrategy); }
public void should_use_consul_service_discovery_and_load_balance_request() { var consulPort = 8502; var serviceName = "product"; var downstreamServiceOneUrl = "http://localhost:50881"; var downstreamServiceTwoUrl = "http://localhost:50882"; var fakeConsulServiceDiscoveryUrl = $"http://localhost:{consulPort}"; var serviceEntryOne = new ServiceEntry() { Service = new AgentService() { Service = serviceName, Address = "localhost", Port = 50881, ID = Guid.NewGuid().ToString(), Tags = new string[0] }, }; var serviceEntryTwo = new ServiceEntry() { Service = new AgentService() { Service = serviceName, Address = "localhost", Port = 50882, ID = Guid.NewGuid().ToString(), Tags = new string[0] }, }; var configuration = new FileConfiguration { ReRoutes = new List <FileReRoute> { new FileReRoute { DownstreamPathTemplate = "/", DownstreamScheme = "http", UpstreamPathTemplate = "/", UpstreamHttpMethod = new List <string> { "Get" }, ServiceName = serviceName, LoadBalancerOptions = new FileLoadBalancerOptions { Type = "LeastConnection" }, } }, GlobalConfiguration = new FileGlobalConfiguration() { ServiceDiscoveryProvider = new FileServiceDiscoveryProvider() { Host = "localhost", Port = consulPort } } }; this.Given(x => x.GivenProductServiceOneIsRunning(downstreamServiceOneUrl, 200)) .And(x => x.GivenProductServiceTwoIsRunning(downstreamServiceTwoUrl, 200)) .And(x => x.GivenThereIsAFakeConsulServiceDiscoveryProvider(fakeConsulServiceDiscoveryUrl, serviceName)) .And(x => x.GivenTheServicesAreRegisteredWithConsul(serviceEntryOne, serviceEntryTwo)) .And(x => _steps.GivenThereIsAConfiguration(configuration)) .And(x => _steps.GivenOcelotIsRunningWithConsul()) .When(x => _steps.WhenIGetUrlOnTheApiGatewayMultipleTimes("/", 50)) .Then(x => x.ThenTheTwoServicesShouldHaveBeenCalledTimes(50)) .And(x => x.ThenBothServicesCalledRealisticAmountOfTimes(24, 26)) .BDDfy(); }
private static void WalkTimeTrackingRetForAdd(XmlNode TimeTrackingRet) { if (TimeTrackingRet == null) { return; } string Duration = TimeTrackingRet.SelectSingleNode("./Duration").InnerText; HoursMinutes hrsMins = GetHoursMinutesFromDuration(Duration); if (hrsMins == null) { return; } RotoTrackDb db = new RotoTrackDb(); string TxnID = ""; string seGUID = ""; string ItemServiceListID = ""; if (TimeTrackingRet.SelectSingleNode("./TxnID") != null) { TxnID = TimeTrackingRet.SelectSingleNode("./TxnID").InnerText; } if (TimeTrackingRet.SelectSingleNode("./Notes") != null) { string Notes = TimeTrackingRet.SelectSingleNode("./Notes").InnerText; seGUID = QBUtils.GetGuidFromNotes(Notes); } XmlNode ItemServiceRef = TimeTrackingRet.SelectSingleNode("./ItemServiceRef"); if (ItemServiceRef != null) { if (ItemServiceRef.SelectSingleNode("./ListID") != null) { ItemServiceListID = ItemServiceRef.SelectSingleNode("./ListID").InnerText; } } if (TxnID != null && seGUID != null && ItemServiceListID != null) { ServiceEntry se = null; if (db.ServiceEntries.Any(f => f.GUID == seGUID)) { se = db.ServiceEntries.First(f => f.GUID == seGUID); } if (se != null) { ServiceDetail sd = db.ServiceDetails.Find(se.ServiceDetailId); if (sd != null) { ServiceType regST = db.ServiceTypes.Find(sd.ServiceTypeId); ServiceType otST = db.ServiceTypes.Find(sd.OTServiceTypeId); if (regST != null && otST != null) { // We always update the regular hours first, so if reg and OT both have the same service list ID, then we need to also check if we already // wrote out the regular hours or not--else we will put both the reg and ot hours into regular hours since we match on reg hours first. // I was going to also look at the actual hours and minutes, but if those are identical, too, then this reduces to the same problem we have // solved here--we just have to assume reg hours are always written first, which they are. Also, I don't want to compare on hours/minutes // because that may fail due to rounding errors. if (ItemServiceListID == regST.QBListId && se.QBListIdForRegularHours == null) { se.QBListIdForRegularHours = TxnID; db.Entry(se).State = EntityState.Modified; db.SaveChanges(); } else if (ItemServiceListID == otST.QBListId && se.QBListIdForOTHours == null) { se.QBListIdForOTHours = TxnID; db.Entry(se).State = EntityState.Modified; db.SaveChanges(); } } } } } }
public ServiceRegistrationRequest(ServiceEntry service) : this() { Service = service; }
private void WhenIRemoveAService(ServiceEntry serviceEntryTwo) { _serviceEntries.Remove(serviceEntryTwo); }
public async Task <object> Execute(ServiceEntry serviceEntry, object[] parameters, string serviceKey = null) { return(await serviceEntry.Executor(serviceKey, parameters)); }
public void should_send_request_to_service_after_it_becomes_available_in_consul() { var consulPort = 8501; var serviceName = "product"; var downstreamServiceOneUrl = "http://localhost:50879"; var downstreamServiceTwoUrl = "http://localhost:50880"; var fakeConsulServiceDiscoveryUrl = $"http://localhost:{consulPort}"; var serviceEntryOne = new ServiceEntry() { Service = new AgentService() { Service = serviceName, Address = "localhost", Port = 50879, ID = Guid.NewGuid().ToString(), Tags = new string[0] }, }; var serviceEntryTwo = new ServiceEntry() { Service = new AgentService() { Service = serviceName, Address = "localhost", Port = 50880, ID = Guid.NewGuid().ToString(), Tags = new string[0] }, }; var configuration = new FileConfiguration { ReRoutes = new List <FileReRoute> { new FileReRoute { DownstreamPathTemplate = "/", DownstreamScheme = "http", UpstreamPathTemplate = "/", UpstreamHttpMethod = new List <string> { "Get" }, ServiceName = serviceName, LoadBalancerOptions = new FileLoadBalancerOptions { Type = "LeastConnection" }, } }, GlobalConfiguration = new FileGlobalConfiguration() { ServiceDiscoveryProvider = new FileServiceDiscoveryProvider() { Host = "localhost", Port = consulPort } } }; this.Given(x => x.GivenProductServiceOneIsRunning(downstreamServiceOneUrl, 200)) .And(x => x.GivenProductServiceTwoIsRunning(downstreamServiceTwoUrl, 200)) .And(x => x.GivenThereIsAFakeConsulServiceDiscoveryProvider(fakeConsulServiceDiscoveryUrl, serviceName)) .And(x => x.GivenTheServicesAreRegisteredWithConsul(serviceEntryOne, serviceEntryTwo)) .And(x => _steps.GivenThereIsAConfiguration(configuration)) .And(x => _steps.GivenOcelotIsRunningWithConsul()) .And(x => _steps.WhenIGetUrlOnTheApiGatewayMultipleTimes("/", 10)) .And(x => x.ThenTheTwoServicesShouldHaveBeenCalledTimes(10)) .And(x => x.ThenBothServicesCalledRealisticAmountOfTimes(4, 6)) .And(x => WhenIRemoveAService(serviceEntryTwo)) .And(x => GivenIResetCounters()) .And(x => _steps.WhenIGetUrlOnTheApiGatewayMultipleTimes("/", 10)) .And(x => ThenOnlyOneServiceHasBeenCalled()) .And(x => WhenIAddAServiceBackIn(serviceEntryTwo)) .And(x => GivenIResetCounters()) .When(x => _steps.WhenIGetUrlOnTheApiGatewayMultipleTimes("/", 10)) .Then(x => x.ThenTheTwoServicesShouldHaveBeenCalledTimes(10)) .And(x => x.ThenBothServicesCalledRealisticAmountOfTimes(4, 6)) .BDDfy(); }
private async Task <HttpResultMessage <object> > RemoteExecuteAsync(ServiceEntry entry, HttpMessage httpMessage) { HttpResultMessage <object> resultMessage = new HttpResultMessage <object>(); var provider = _concurrent.GetValueOrDefault(httpMessage.RoutePath); var list = new List <object>(); if (provider.Item1 == null) { provider.Item2 = ServiceLocator.GetService <IServiceProxyFactory>().CreateProxy(httpMessage.ServiceKey, entry.Type); provider.Item3 = provider.Item2.GetType().GetTypeInfo().DeclaredMethods.Where(p => p.Name == entry.MethodName).FirstOrDefault(); provider.Item1 = FastInvoke.GetMethodInvoker(provider.Item3); _concurrent.GetOrAdd(httpMessage.RoutePath, ValueTuple.Create <FastInvokeHandler, object, MethodInfo>(provider.Item1, provider.Item2, provider.Item3)); } foreach (var parameterInfo in provider.Item3.GetParameters()) { var value = httpMessage.Parameters[parameterInfo.Name]; var parameterType = parameterInfo.ParameterType; var parameter = _typeConvertibleService.Convert(value, parameterType); list.Add(parameter); } try { var methodResult = provider.Item1(provider.Item2, list.ToArray()); var task = methodResult as Task; if (task == null) { resultMessage.Data = methodResult; } else { await task; var taskType = task.GetType().GetTypeInfo(); if (taskType.IsGenericType) { resultMessage.Data = taskType.GetProperty("Result").GetValue(task); } } resultMessage.IsSucceed = resultMessage.Data != null; // resultMessage.StatusCode = resultMessage.IsSucceed ? (int)StatusCode.Success : (int)StatusCode.RequestError; resultMessage.StatusCode = resultMessage.IsSucceed ? StatusCode.OK : StatusCode.RequestError; //StatusCode.Success : (int)StatusCode.RequestError; } catch (Exception exception) { if (_logger.IsEnabled(LogLevel.Error)) { _logger.LogError(exception, "执行远程调用逻辑时候发生了错误。"); } // resultMessage = new HttpResultMessage<object> { Data = null, Message = "执行发生了错误。", StatusCode = (int)StatusCode.RequestError }; //if (exception is CPlatformException) //{ // resultMessage.StatusCode = ((CPlatformException)exception).ExceptionCode; //} //else //{ // resultMessage.StatusCode = StatusCode.UnKnownError; //} resultMessage.StatusCode = GetGetExceptionStatusCode(exception); resultMessage.Message = GetExceptionMessage(exception); resultMessage.IsSucceed = false; } return(resultMessage); }
private void WhenIRemoveAService(ServiceEntry serviceEntryTwo) { _consulServices.Remove(serviceEntryTwo); }
/// <summary> /// Correct ArgumentException throw by a Dictionary when adding an existing key. /// </summary> void DoAdd( Type s, ServiceEntry e ) { Debug.Assert( s != null ); try { _services.Add( s, e ); } catch( ArgumentException ex ) { if( _services.ContainsKey( s ) ) throw new CKException( ex, R.ServiceAlreadyRegistered, s.FullName ); throw; } }
public static IDictionary <string, string> GetMetadata(ServiceEntry healthService) { return(GetMetadata(healthService.Service.Tags)); }
public override Task Handle(HttpContext context, ServiceEntry serviceEntry) { throw new LmsException("websocket通信请依赖Lms.WebSocketServer包"); }
private string DefaultSortKeySelector(ServiceEntry apiDescription) { return(TagsSelector(apiDescription).First()); }
public ServiceEntryResponse SaveServiceEntry([FromBody] ServiceEntry serviceEntryList) { try { string Details = JsonConvert.SerializeObject(serviceEntryList.serviceDetails); string vehicleno = serviceEntryList.vehicleNumber; int vehicletype = serviceEntryList.VehicleType; int partytype = serviceEntryList.partyType; int baytype = serviceEntryList.baytype; string url = serviceEntryList.base64img; string remarks = serviceEntryList.remarks; string customer = serviceEntryList.customername; decimal total = serviceEntryList.Total; decimal discount = serviceEntryList.discount; decimal netamt = serviceEntryList.netamount; var path = ""; if (!Directory.Exists(System.Web.Hosting.HostingEnvironment.MapPath("~/Images/" + DateTime.Now.ToString("dd_MM_yyyy")))) { Directory.CreateDirectory(System.Web.Hosting.HostingEnvironment.MapPath("~/Images/" + DateTime.Now.ToString("dd_MM_yyyy"))); } path = Path.Combine(System.Web.Hosting.HostingEnvironment.MapPath("~/Images/" + DateTime.Now.ToString("dd_MM_yyyy") + "/"), "V_" + DateTime.Now.ToString("dd_MM_yyyy_hhmmss") + ".jpg"); string base64Img = ""; int index = serviceEntryList.base64img.IndexOf(','); base64Img = serviceEntryList.base64img.Substring(index + 1); File.WriteAllBytes(path, Convert.FromBase64String(base64Img)); int pathindex = path.IndexOf("Images/"); path = path.Substring(index + 1); int EntryStarNo = int.Parse(WebConfigurationManager.AppSettings["ServiceEntryStartNo"].ToString()); ObjectResult <Nullable <int> > queryResult = db.VSR_Trn_ServiceEntry_Save(EntryStarNo, baytype, partytype, vehicleno, vehicletype, path, remarks, customer, total, discount, netamt, Details); int ID = 0; foreach (Nullable <int> result in queryResult) { ID = result.Value; } ServiceEntryResponse SR = new ServiceEntryResponse(); List <VSR_Trn_ServiceEntryDetails_GetByServeEntryID_Result> ServicePricing = new List <VSR_Trn_ServiceEntryDetails_GetByServeEntryID_Result>(); ServicePricing = db.VSR_Trn_ServiceEntryDetails_GetByServeEntryID(ID).ToList(); DataTable dt = ToDataTable(ServicePricing); // System.Web.UI.ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "openModal", "window.open('../Report/RDLCVwr.aspx?rt=gplqtn&ft=pdf&no=" + e.CommandArgument.ToString() + "' ,'_blank');", true); LocalReport report = new LocalReport(); report.ReportPath = "Reports\\ServiceCenter\\serviceentryPrint.rdlc"; //report.ReportEmbeddedResource = ("serviceentryPrint.rdlc"); report.DataSources.Add(new ReportDataSource("DataSet1", dt)); Export(report); //m_currentPageIndex = 0; //Print(); SR.status = 1; SR.message = "Saved Successfully !!"; SR.ServiceDetails = ServicePricing; return(SR); } catch (Exception ex) { ServiceEntryResponse SR = new ServiceEntryResponse(); SR.status = 0; SR.message = "Error Occured While Saving Details"; return(SR); } }
private IEnumerable <string> InferResponseContentTypes(ServiceEntry apiDescription, ApiResponseType apiResponseType) { return(apiDescription.SupportedResponseMediaTypes); }
private async Task LocalExecuteAsync(ServiceEntry entry, RemoteInvokeMessage remoteInvokeMessage, RemoteInvokeResultMessage resultMessage) { try { var result = await entry.Func(remoteInvokeMessage.Parameters); var task = result as Task; if (task == null) { resultMessage.Result = result; } else { task.Wait(); var taskType = task.GetType().GetTypeInfo(); if (taskType.IsGenericType) resultMessage.Result = taskType.GetProperty("Result").GetValue(task); } } catch (Exception exception) { if (_logger.IsEnabled(LogLevel.Error)) _logger.LogError("执行本地逻辑时候发生了错误。", exception); resultMessage.ExceptionMessage = GetExceptionMessage(exception); } }
private Collection<ServiceEntry> createServiceEntries(byte[] contentData) { Collection<byte[]> contentFields = Utils.SplitBytes(contentData, 0x1d); if (contentFields[0].Length != 0 || contentFields[1].Length != 0) { Logger.Instance.Write("Service Info data is in the wrong format (1) - cannot be processed"); return(null); } int count = 0; try { count = Int32.Parse(Utils.GetAsciiString(contentFields[2])); } catch (ArgumentException) { Logger.Instance.Write("Service Info data is in the wrong format (2) - cannot be processed"); return (null); } catch (ArithmeticException) { Logger.Instance.Write("Service Info data is in the wrong format (2) - cannot be processed"); return (null); } int entryIndex = count + 3; Collection<ServiceEntry> serviceEntries = new Collection<ServiceEntry>(); while (entryIndex < contentFields.Count) { ServiceEntry serviceEntry = new ServiceEntry(Utils.GetAsciiString(contentFields[entryIndex]), Utils.GetAsciiString(contentFields[entryIndex + 1]), Utils.GetAsciiString(contentFields[entryIndex + 2]), Utils.GetAsciiString(contentFields[entryIndex + 3])); serviceEntries.Add(serviceEntry); entryIndex += 4; } return (serviceEntries); }