public void SetWebLocalStorage(int ID_hrStaff, string Key, string Value) { ServiceConfig srvcont = new ServiceConfig(_ServiceConfigParameters); DateTime dNow = DateTime.Now; if (srvcont.DataContext.tbl_genWebLocalStorage.Where(w=> w.ID_hrStaff == ID_hrStaff && w.Key==Key).FirstOrDefault() != null) { var entity = srvcont.DataContext.tbl_genWebLocalStorage.Where(w => w.ID_hrStaff == ID_hrStaff && w.Key == Key).FirstOrDefault(); srvcont.DataContext.DeleteObject(entity); } Entities.tbl_genWebLocalStorage setWebLocalStorage = new Entities.tbl_genWebLocalStorage(); setWebLocalStorage.ID = Guid.NewGuid().ToString(); setWebLocalStorage.ID_hrStaff = ID_hrStaff; setWebLocalStorage.Key = Key; setWebLocalStorage.Value = Value; setWebLocalStorage.OBSOLATE = false; setWebLocalStorage.TS_CREATE = dNow; setWebLocalStorage.VALID_FROM = dNow; setWebLocalStorage.VALID_TO = dNow; setWebLocalStorage.CREATED_BY = ID_hrStaff; srvcont.DataContext.tbl_genWebLocalStorage.AddObject(setWebLocalStorage); srvcont.DataContext.SaveChanges(); }
public static void LogException(Exception exToHandle, ServiceConfig srvcont, RequestItem Item) { ServiceConfig srvcontext = new ServiceConfig(srvcont.ConfigurationParameters); if (srvcontext.ConfigurationParameters.ExceptionLogNeeded) { DateTime dNow = DateTime.Now; Entities.tbl_genLog logentry = new Entities.tbl_genLog(); logentry.ID_LogType = 1; logentry.LogID = exToHandle.GetType().Name; logentry.ID_Staff = Item.UserId; logentry.SessionID = Item.SessionId; logentry.RequestText = Item.ToString(); logentry.LogText = exToHandle.ToString(); logentry.CREATED_BY = Item.UserId; logentry.TS_CREATE = dNow; logentry.VALID_FROM = dNow; logentry.VALID_TO = dNow; srvcontext.DataContext.tbl_genLog.AddObject(logentry); try { srvcontext.DataContext.SaveChanges(); } catch (Exception ex) { throw; } } }
public void tbl_genLog_Logger(int ID_hrStaff,int ID_reqpUserID, int ID_LogType, string RequestText = "",string SessionID = "", string LogText = "") { ServiceConfig srvcont = new ServiceConfig(_ServiceConfigParameters); try { System.Diagnostics.StackFrame sf = new System.Diagnostics.StackFrame(1); var method = sf.GetMethod(); string methodName = method.Name; DateTime dNow = DateTime.Now; Entities.tbl_genLog userlog = new Entities.tbl_genLog(); //LogType 3 = UserAction userlog.ID_LogType = ID_LogType; userlog.LogID = methodName; userlog.ID_Staff = ID_reqpUserID; userlog.SessionID = SessionID; userlog.RequestText = RequestText; userlog.LogText = LogText; userlog.TS_CREATE = dNow; userlog.VALID_FROM = dNow; userlog.VALID_TO = dNow; userlog.CREATED_BY = ID_hrStaff; srvcont.DataContext.tbl_genLog.AddObject(userlog); srvcont.DataContext.SaveChanges(); } catch (Exception) { //no action } }
public ActionResult EditEnvironment(string id, string name, ServiceConfig model) { var item = GetConfigurationReader().GetConfiguration(id); var env = (from e in item.Services where e.ServiceName == name select e).First(); env.ServiceName = model.ServiceName; env.Username = model.Username; if (!model.PasswordIsUnchanged) env.Password = model.Password; if (env.Parameters == null) env.Parameters = new List<ConfigParameter>(); var keyName = Request.Form["keyName"]; var value = Request.Form["keyValue"]; if (keyName.ContainsCharacters()) { var param = (from p in env.Parameters where p.Name == keyName select p).FirstOrDefault(); if (param.IsNull()) { param = new ConfigParameter(); env.Parameters.Add(param); } param.Name = keyName; if (keyName.ToLower().Contains("password")) { param.Value = value.Encrypt("mayTheKeysSupportAllMyValues"); param.BinaryValue = param.Value.GetByteArray(); if (param.Value.Decrypt("mayTheKeysSupportAllMyValues") != value) throw new StardustCoreException("Encryption validation failed!"); } else param.Value = value; } GetConfigurationReader().WriteConfigurationSet(item, id); ViewBag.Id = id; return RedirectToAction("EditEnvironment", new { id = id, name = model.ServiceName }); }
public void CallServiceBaseMethod(RequestItem Item) { ResponseItem re = new ResponseItem(Item); re.RequestItem.RequestLog = re.RequestItem.RequestLog + "srv_start: " + DateTime.Now.ToString() + ","; ServiceConfig srvcont = new ServiceConfig(_serviceconfigparameters); HelperClasses.Serializer srl = new HelperClasses.Serializer(); try { DateTime dFrom = DateTime.Now.AddMonths(-10).Date; DateTime dTo = DateTime.Now.AddMonths(2).Date; var periodsFrom = (from row in srvcont.DataContext.tbl_trDate.Where(w => w.Date >= dFrom && w.Date <= dTo) select row.PeriodStarting).Distinct().ToList(); var periodsFromTo = from period in periodsFrom select new { PeriodFromTo = period.Value.ToString("yyyy-MM-dd") + " - " + (period.Value.Day == 1 ? period.Value.AddDays(14).ToString("yyyy-MM-dd") : (new DateTime(period.Value.AddMonths(1).Year, period.Value.AddMonths(1).Month, 1)).AddDays(-1).ToString("yyyy-MM-dd")) }; re.ResponseBody = srl.NTSoftJsonSerialize(periodsFromTo.ToArray()); re.RequestCompleted = true; } catch (Exception ex) { //re.ResponseBody = ex.ToString(); re.RequestCompleted = false; } re.RequestItem.RequestLog = re.RequestItem.RequestLog + "srv_finish: " + DateTime.Now.ToString() + ","; }
public DataTable GetUser(string userCode) { if (HelperMediator.GetInstance().stringHelper.CheckSpecialCharacters(userCode)) { return(null); } H_HDBUsers h_HDBUsers = new H_HDBUsers() { UserCodeHDB = userCode }; return(ServiceConfig.GetInstance().GetOperation().SimpleQuery(h_HDBUsers)); }
public static void Main(string[] args) { ServiceConfig.LoadServiceConfig(); if (!string.IsNullOrWhiteSpace(ConfigManager.Config.ApiServer?.ListenUrl)) { // Get the bind address and port from config: var server = WebApp.Start <Startup>(url: ConfigManager.Config.ApiServer.ListenUrl); Console.WriteLine($"ACE API listening at {ConfigManager.Config.ApiServer.ListenUrl}"); } else { Console.WriteLine("There was an error in your API configuration."); } Console.ReadLine(); // need a readline or the error flashes without being seen }
// The demand is not added now (in 4.5), to avoid a breaking change. To be considered in the next version. /* * [PermissionSet(SecurityAction.Demand, Unrestricted = true)] // because we call code from a non-APTCA assembly; transactions are not supported in partial trust, so customers should not be broken by this demand */ public static Transaction GetMessageTransaction(Message message) { ServiceConfig serviceConfig = new ServiceConfig(); serviceConfig.Transaction = TransactionOption.Disabled; ServiceDomain.Enter(serviceConfig); try { return(TransactionMessageProperty.TryGetTransaction(message)); } finally { ServiceDomain.Leave(); } }
public static void Register() { // Use this class to set configuration options for your mobile service var options = new ConfigOptions(); // Use this class to set WebAPI configuration options var config = ServiceConfig.Initialize(new ConfigBuilder(options)); // To display errors in the browser during development, uncomment the following // line. Comment it out again when you deploy your service for production use. // config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always; // in production I do not recommed it! Database.SetInitializer(new MobileServiceInitializer()); }
public static AbstractBoosterService ReBuildService(ServiceConfig config, bool Runtime) { Type serviceType = Type.GetType(config.ServiceTypeId); if (serviceType == null || !typeof(AbstractBoosterService).IsAssignableFrom(serviceType)) { return(null); } AbstractBoosterService service = (AbstractBoosterService)Activator.CreateInstance(serviceType); service.Id = config.Guid; service.ServiceTypeId = config.ServiceTypeId; service.ServiceName = config.ServiceName; service.ServiceGroup = config.ServiceGroup; service.ServicePolicy = config.ServicePolicy; service.ServiceDescription = config.ServiceDescription; service.Operations = new List <OperateObject>(); //解析所有的操作 var operations = Newtonsoft.Json.JsonConvert.DeserializeObject <JArray>(config.Operations); if (operations != null && operations.Count > 0) { foreach (var item in operations) { var opObject = new OperateObject() { OperateId = item["OperateId"].ToString(), OperateTarget = item["OperateTarget"].ToString(), OperateDescription = item["OperateDescription"].ToString(), Operations = new List <IOperation>(), }; foreach (var opItem in item["Operations"] as JArray) { IOperation operation = new Operation(opItem["OperationString"].ToString()); operation.HandleOperationMethod(service, (m, p) => { if (operation.ValidateOperationMethod(m, p)) { opObject.Operations.Add(operation); } }); } service.Operations.Add(opObject); } } return(service); }
public static void Register() { // Use this class to set configuration options for your mobile service ConfigOptions options = new ConfigOptions(); // Use this class to set WebAPI configuration options HttpConfiguration config = ServiceConfig.Initialize(new ConfigBuilder(options)); config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CustomContractResolver(config.Formatters.JsonFormatter); // To display errors in the browser during development, uncomment the following // line. Comment it out again when you deploy your service for production use. // config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always; Database.SetInitializer(new MobileServiceInitializer()); }
public static void Register() { // Use this class to set configuration options for your mobile service ConfigOptions options = new ConfigOptions(); options.LoginProviders.Add(typeof(LinkedInLoginProvider)); // Use this class to set WebAPI configuration options HttpConfiguration config = ServiceConfig.Initialize(new ConfigBuilder(options)); // To display errors in the browser during development, uncomment the following // line. Comment it out again when you deploy your service for production use. // config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always; Database.SetInitializer(new DotNetRuntimeAuthInitializer()); }
private void ServiceRunning_Click(object sender, MouseButtonEventArgs e) { if (!ServiceConfig.IsServiceInstalled) { MessageBox.Show("The service must be installed before you can run it.", "Service Not Installed", MessageBoxButton.OK, MessageBoxImage.Warning); return; } if (ServiceConfig.IsServiceRunning) { ServiceConfig.StopService(); } else { ServiceConfig.StartService(); } }
/// <summary> /// Get default or saved service config settings /// </summary> /// <returns> </returns> public static ServiceConfig GetAppServiceConfig() { var serviceConfig = new ServiceConfig(); var appDataPath = GetAppDataFolder(); var serviceConfigFile = appDataPath + "\\serviceconfig.json"; #if DEBUG serviceConfigFile = appDataPath + "\\serviceconfig.debug.json"; #endif if (File.Exists(serviceConfigFile)) { serviceConfig = JsonConvert.DeserializeObject <ServiceConfig>(File.ReadAllText(serviceConfigFile)); } return(serviceConfig); }
private ServiceConfig CreateServicedConfig() { ServiceConfig config = new ServiceConfig(); config.TrackingEnabled = true; config.TrackingAppName = "MbUnit Transaction Test Case"; config.TrackingComponentName = this.Invoker.Name; config.Transaction = TransactionOption.Required; if (TimeOutValue != 0) { config.TransactionTimeout = TimeOutValue; } return(config); }
/// <summary> /// The register. /// </summary> public static void Register() { // Use this class to set configuration options for your mobile service var options = new ConfigOptions(); // Use this class to set WebAPI configuration options ServiceConfig.Initialize(new ConfigBuilder(options)); // To display errors in the browser during development, uncomment the following // line. Comment it out again when you deploy your service for production use. // config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always; var migrator = new DbMigrator(new Configuration()); migrator.Update(); }
/// <summary> /// Specifies how the ASP.NET application will respond to individual HTTP request. /// </summary> /// <param name="app">Instance of <see cref="IAppBuilder"/>.</param> public void Configuration(IAppBuilder app) { CorsConfig.ConfigureCors(ConfigurationManager.AppSettings["cors"]); app.UseCors(CorsConfig.Options); var configuration = new HttpConfiguration(); AutofacConfig.Configure(configuration); app.UseAutofacMiddleware(AutofacConfig.Container); FormatterConfig.Configure(configuration); RouteConfig.Configure(configuration); ServiceConfig.Configure(configuration); app.UseWebApi(configuration); }
public Cargo OCadastroRapidoDoCargo() { string idGeneral = Guid.NewGuid().ToString(); Cargo Cargo = new Cargo(); Cargo.id = idGeneral; Cargo.idClassificacaoBrasileiraOcupacao = "8814927D-1427-4EBD-BAC6-EBBC88E8C131"; Cargo.descricao = FakeDataGenerator.FakeDescricao(50); Cargo.status = "A"; Cargo = JsonConvert.DeserializeObject <Cargo>(Services.POST(ServiceConfig.GetUrlAdm() + "/hypercube_adm/v1/cargo", JsonConvert.SerializeObject(Cargo))); return(Cargo); }
public static void Register() { AppServiceExtensionConfig.Initialize(); // Use this class to set configuration options for your mobile service ConfigOptions options = new ConfigOptions(); // Use this class to set WebAPI configuration options HttpConfiguration config = ServiceConfig.Initialize(new ConfigBuilder(options)); // To display errors in the browser during development, uncomment the following // line. Comment it out again when you deploy your service for production use. // config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always; Database.SetInitializer(new UWPDevMVAInitializer()); }
public DataTable GetAllST() { string[] objs = new string[0]; R_LogisticsExceptionReport rpt_LogisticsExceptionReport = new R_LogisticsExceptionReport() { NotInSTType = "1,8" }; DataTable dataTable = ServiceConfig.GetInstance().GetOperation().SimpleGroupQuery( rpt_LogisticsExceptionReport , "STName, STType" , "STName, STType"); return(dataTable); }
public static void Register() { // Use this class to set configuration options for your mobile service ConfigOptions options = new ConfigOptions(); // Use this class to set WebAPI configuration options HttpConfiguration config = ServiceConfig.Initialize(new ConfigBuilder(options)); #if DEBUG config.Formatters.JsonFormatter.SerializerSettings.Formatting = Formatting.Indented; config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always; #endif Database.SetInitializer(new MobileServiceInitializer()); }
/// <summary> /// Get the service configuration /// </summary> /// <param name="configFilePath">The path to the config file</param> /// <returns></returns> public static ServiceConfig GetServiceConfiguration(string configFilePath) { var serviceConfig = new ServiceConfig(); if (File.Exists(configFilePath)) { string json = File.ReadAllText(configFilePath); var serializerSettings = new JsonSerializerSettings() { ObjectCreationHandling = ObjectCreationHandling.Replace }; serviceConfig = JsonConvert.DeserializeObject <ServiceConfig>(json, serializerSettings); } return(serviceConfig); }
/// <summary> /// 获取报表相关参数 /// </summary> /// <param name="model"></param> /// <param name="arg"></param> /// <returns></returns> public ReportResult GetReportResult(string model, ReportArg arg) { DbContext currentDb = SysContext.GetCurrentDb(); ReportResult reportResult = new ReportResult(); reportModelName = model; reportModelConfig = ServiceHelper.GetServiceConfig(model); List <NameValue> list_0 = GetLegendNameValues(currentDb, arg); List <NameValue> list_1 = GetAxisNameValues(currentDb, arg); foreach (NameValue item in list_1) { reportResult.axis.Add(item.name); } foreach (NameValue item2 in list_0) { reportResult.legend.Add(item2.name); object obj = null; if (!string.IsNullOrEmpty(arg.axisField) && arg.legendType != "pie") { List <object> list = new List <object>(); foreach (NameValue item3 in list_1) { FilterGroup group = GetDateTimeLegendFilter(currentDb, arg, item2.value, item3.value); FilterTranslator filterTranslator = new FilterTranslator(group); filterTranslator.Translate(); list.Add(GetCountValue(currentDb, arg.valueField, arg.valueFieldType, filterTranslator.CommandText, filterTranslator.Parms.ToArray())); } obj = list; } else { FilterGroup group = GetDateTimeLegendFilter(currentDb, arg, item2.value, null); FilterTranslator filterTranslator = new FilterTranslator(group); filterTranslator.Translate(); obj = GetCountValue(currentDb, arg.valueField, arg.valueFieldType, filterTranslator.CommandText, filterTranslator.Parms.ToArray()); } reportResult.series.Add(new { name = item2.name, value = obj }); } return(reportResult); }
public NotificationsServiceInstaller() { process = new ServiceProcessInstaller(); process.Account = ServiceAccount.LocalSystem; service = new ServiceInstaller(); Directory.SetCurrentDirectory(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)); Configuration cfg = ConfigurationManager.OpenExeConfiguration(Assembly.GetExecutingAssembly().Location); String path = cfg.AppSettings.Settings["ServicePath"].Value; ServiceConfig config = lm.Comol.Core.WinService.Configurations.Configuration <ServiceConfig> .Load(path); service.ServiceName = config.Service.ServiceName; service.StartType = ServiceStartMode.Automatic; Installers.Add(process); Installers.Add(service); }
/// <summary> /// Load the configuration. /// </summary> private void LoadConfig() { try { _config = ServiceConfig.Deserialize( Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "conf")); } catch (ConfigurationErrorsException ex) { Log.Error("Validating configuration failed: {0}", ex.Message); throw new Exception("Error validating configuration."); } catch (Exception ex) { Log.Error("Loading configuration failed: {0}", ex.Message); // this should terminate the service process: throw new Exception("Error loading configuration."); } SetupFileLogging(_config.LogLevel); }
public static void Register() { // Use this class to set configuration options for your mobile service ConfigOptions options = new ConfigOptions(); // Use this class to set WebAPI configuration options HttpConfiguration config = ServiceConfig.Initialize(new ConfigBuilder(options)); // To display errors in the browser during development, uncomment the following // line. Comment it out again when you deploy your service for production use. //config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always; //var formatters = config.Formatters; //var jsonFormatter = formatters.JsonFormatter; //var settings = jsonFormatter.SerializerSettings; //settings.Formatting = Formatting.Indented; //settings.ContractResolver = new CamelCasePropertyNamesContractResolver(); // Elastic Scale must ensure data consistency //Database.SetInitializer(new mpbdmInitializer()); Mapper.Initialize(cfg => { cfg.CreateMap <Groups, MobileGroup>().ReverseMap(); cfg.CreateMap <Favorites, MobileFavorites>().ReverseMap(); }); // sharding GLOBAL ShardingObj = new Sharding(); //ShardingObj.RegisterNewShard(server, shard1, connectionString, company1); //ShardingObj.RegisterNewShard(server, shard2, connectionString, company2); // Register the mapping of the tenant to the shard in the shard map. // After this step, DDR on the shard map can be used /* * PointMapping<int> mapping; * if (!this.ShardMap.TryGetMappingForKey(key, out mapping)) * { * this.ShardMap.CreatePointMapping(key, shard); * } * //*/ }
protected override void OnStart(string[] args) { serviceConfig = Utility.ReadFromXmlFile <ServiceConfig>("ServiceConfig.xml"); if (serviceConfig != null) { timer = new Timer(); timer = new Timer(serviceConfig.ServiceTimeInterval); timer.Elapsed += new ElapsedEventHandler(time_tick); timer.Enabled = true; ReadServiceConfig(); Logger.WriteLogs("Service", LogLevel.Information, "Service Started"); } else { Logger.WriteLogs("Service", LogLevel.Error, "Not able to read ServiceConfig.xml"); } }
public static void Register() { AppServiceExtensionConfig.Initialize(); // Use this class to set configuration options for your mobile service ConfigOptions options = new ConfigOptions(); // Use this class to set WebAPI configuration options HttpConfiguration config = ServiceConfig.Initialize(new ConfigBuilder(options)); // always send JSON values, even if they have the default value for that type config.Formatters.JsonFormatter.SerializerSettings.DefaultValueHandling = Newtonsoft.Json.DefaultValueHandling.Include; // To display errors in the browser during development, uncomment the following // line. Comment it out again when you deploy your service for production use. config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always; }
public static void AddConsul(this IServiceCollection services, IConfiguration configuration) { var name = Dns.GetHostName(); var serviceConfig = new ServiceConfig { ServiceDiscoveryAddress = configuration.GetValue <Uri>("ServiceConfig:serviceDiscoveryAddress"), ServiceAddress = new Uri($"http://{name}:80"), ServiceName = configuration.GetValue <string>("ServiceConfig:serviceName"), ServiceId = configuration.GetValue <string>("ServiceConfig:serviceId") + name }; var consulClient = CreateConsulClient(serviceConfig); services.AddSingleton(serviceConfig); services.AddSingleton <IHostedService, ServiceDiscoveryHostedService>(); services.AddSingleton <IConsulClient, ConsulClient>(p => consulClient); }
/// <summary> /// 通过Account获取首个ORG的deptID /// </summary> /// <param name="AccountId"></param> /// <returns></returns> public string GetUserDetail(string AccountId) { try { ServiceConfig userServiceConfig = ServiceHelper.GetServiceConfig("user"); var OTDB = SysContext.GetOtherDB(userServiceConfig.model.dbName); var deptId = OTDB.FirstOrDefault <long>(@"SELECT org.id FROM organization org inner join organizationuser ou on ou.OrganizationId = org.Id inner join user usr on usr.Id = ou.UserId where usr.AccountId = @0", AccountId); return(deptId.ToString()); } catch (Exception e) { return(null); } }
public async Task Subscribe(ServiceConfig serviceInfo, Action <IList <ServiceConfig> > onChange) { try { await DoSubscribe(serviceInfo, onChange); var actions = successSubscribeConfigs.GetOrAdd(serviceInfo, new ConcurrentSet <Action <IList <ServiceConfig> > >()); actions.Add(onChange); } catch (Exception e) { var failActions = successSubscribeConfigs.GetOrAdd(serviceInfo, new ConcurrentSet <Action <IList <ServiceConfig> > >()); failActions.Add(onChange); Log.Warn($"Subscribe {serviceInfo} fail.", e); } }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { /* * services.AddDbContext<ApplicationDbContext>(options => * options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))); * * services.AddIdentity<ApplicationUser, IdentityRole>() * .AddEntityFrameworkStores<ApplicationDbContext>() * .AddDefaultTokenProviders(); */ // Add application services. services.AddTransient <IEmailSender, EmailSender>(); ServiceConfig.ConfigureServices(services); services.AddMvc(); }
public static void Register() { // Use this class to set configuration options for your mobile service var options = new ConfigOptions { CorsPolicy = new System.Web.Http.Cors.EnableCorsAttribute("*", "*", "*") }; // Use this class to set WebAPI configuration options var config = ServiceConfig.Initialize(new ConfigBuilder(options)); // To display errors in the browser during development, uncomment the following // line. Comment it out again when you deploy your service for production use. config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always; Database.SetInitializer(new MobileServiceInitializer()); }
public void SetUp() { packet = new PacketInformation(new VendorInfo("00-11-22-33-44-55", "Amazon"), PhysicalAddress.Parse("00-11-22-33-44-55")); serviceConfig = new ServiceConfig(); serviceConfig.Bridges = new Dictionary <string, BridgeConfig>(); serviceConfig.Bridges["One"] = new BridgeConfig(); serviceConfig.Buttons = new Dictionary <string, ButtonConfig>(); serviceConfig.Buttons["Main"] = new ButtonConfig(); serviceConfig.Buttons["Main"].Mac = "00-11-22-33-44-55"; serviceConfig.Buttons["Main"].Actions = new[] { new ButtonAction { Groups = new[] { "TestMain" }, Type = ButtonActionType.Simple } }; mockMonitoringManager = new Mock <IMonitoringManager>(); mockLightsManagerFactory = new Mock <ILightsManagerFactory>(); scheduler = new TestScheduler(); instance = CreateService(); }
public static void Register() { // Use this class to set configuration options for your mobile service ConfigOptions options = new ConfigOptions(); // Use this class to set WebAPI configuration options HttpConfiguration config = ServiceConfig.Initialize(new ConfigBuilder(options)); // To display errors in the browser during development, uncomment the following // line. Comment it out again when you deploy your service for production use. // TODO: comment out again config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always; // Set default and null value handling to "Include" for Json Serializer config.Formatters.JsonFormatter.SerializerSettings.DefaultValueHandling = Newtonsoft.Json.DefaultValueHandling.Include; config.Formatters.JsonFormatter.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Include; // Map data transfer objects to models // using AutoMapper: https://github.com/AutoMapper/AutoMapper/wiki/Getting-started Mapper.Initialize(cfg => { //Type on the left is source type, type on the right is destination type, //thereofre CreateMap<BpCurrentRating, BusinessPartner> allows to map //from an instance to the DTO BpCurrentRating to a new instance of //the model BusinessPartner cfg.CreateMap <MobileBusinessPartner, Rating>(); //This call to ForMember maps from BpCurrentRating.BusinessPartnerId //to BusinessParnter.Id //e.g. //.ForMember(dst => dst.RatingId, map => map.MapFrom(x => x.RatingId)); cfg.CreateMap <Rating, MobileBusinessPartner>() .ForMember(dst => dst.RatingBpId, map => map.MapFrom(x => x.BusinessPartner.Id)) .ForMember(dst => dst.ShortName, map => map.MapFrom(x => x.BusinessPartner.ShortName)) .ForMember(dst => dst.BusinessPartnerId, map => map.MapFrom(x => x.BusinessPartner.BusinessPartnerId)); cfg.CreateMap <MobileRatingSheet, RatingSheetSection>() .ForMember(dst => dst.PartialRatingsInSection, map => map.MapFrom(x => x.PartialRatingsInSection)); cfg.CreateMap <RatingSheetSection, MobileRatingSheet>() .ForMember(dst => dst.PartialRatingsInSection, map => map.MapFrom(x => x.PartialRatingsInSection)) .ForMember(dst => dst.RatingGuid, map => map.MapFrom(x => x.Rating.Id)); cfg.CreateMap <MobilePartialRating, PartialRating>(); cfg.CreateMap <PartialRating, MobilePartialRating>(); }); Database.SetInitializer(new ratingtoolInitializer()); }
public ActionResult CreateEnvironment(string id, ServiceConfig model) { var item = GetConfigurationReader().GetConfiguration(id); if ((from s in item.Services where s.ServiceName == model.ServiceName select s).Any()) throw new IndexOutOfRangeException(string.Format("Service with name {0} already exists", model.ServiceName)); model.IdentitySettings = new IdentitySettings { Audiences = new List<string> { "test" }, CertificateValidationMode = "None", IssuerAddress = "test", IssuerName = "test", Realm = "test", RequireHttps = false, Thumbprint = "then" }; item.Services.Add(model); GetConfigurationReader().WriteConfigurationSet(item, id); return RedirectToAction("Index", new { id = id }); }
public static void SetBindingProperties(this Binding binding, ServiceConfig bindingProperties) { if (binding.GetType().Equals(typeof(System.ServiceModel.NetTcpBinding))) { //(binding as System.ServiceModel.NetTcpBinding).Security.Message.ClientCredentialType = bindingProperties.MessageCredentialType; //(binding as System.ServiceModel.NetTcpBinding).Security.Transport.ClientCredentialType = bindingProperties.TcpClientCredentialType; //(binding as System.ServiceModel.NetTcpBinding).Security.Transport.ProtectionLevel = bindingProperties.ProtectionLevel; (binding as System.ServiceModel.NetTcpBinding).MaxConnections = bindingProperties.NetParameter.MaxConnections; (binding as System.ServiceModel.NetTcpBinding).MaxReceivedMessageSize = bindingProperties.NetParameter.MaxReceivedMessageSize; (binding as System.ServiceModel.NetTcpBinding).MaxBufferPoolSize = bindingProperties.NetParameter.MaxBufferPoolSize; (binding as System.ServiceModel.NetTcpBinding).ReaderQuotas.MaxArrayLength = bindingProperties.NetParameter.MaxArrayLength; (binding as System.ServiceModel.NetTcpBinding).ReaderQuotas.MaxBytesPerRead = bindingProperties.NetParameter.MaxBytesPerRead; (binding as System.ServiceModel.NetTcpBinding).ReaderQuotas.MaxDepth = bindingProperties.NetParameter.MaxDepth; (binding as System.ServiceModel.NetTcpBinding).ReaderQuotas.MaxStringContentLength = bindingProperties.NetParameter.MaxStringContentLength; (binding as System.ServiceModel.NetTcpBinding).ReaderQuotas.MaxNameTableCharCount = bindingProperties.NetParameter.MaxNameTableCharCount; } //not allowed by partially trusted //tcpBinding.MaxBufferSize = 262144; //256KB default is 65,536 bytes binding.OpenTimeout = TimeSpan.FromSeconds(bindingProperties.NetParameter.OpenTimeout); binding.CloseTimeout = TimeSpan.FromSeconds(bindingProperties.NetParameter.CloseTimeout); binding.ReceiveTimeout = TimeSpan.FromSeconds(bindingProperties.NetParameter.ReceiveTimeout); binding.SendTimeout = TimeSpan.FromSeconds(bindingProperties.NetParameter.SendTimeout); CustomBinding cb = new CustomBinding(binding); TcpTransportBindingElement tcpe = new TcpTransportBindingElement(); tcpe.ConnectionBufferSize = bindingProperties.NetParameter.ConnectionBufferSize; tcpe.ConnectionPoolSettings.LeaseTimeout = TimeSpan.FromSeconds(bindingProperties.NetParameter.ConnectionLeaseTimeout); tcpe.ConnectionPoolSettings.IdleTimeout = TimeSpan.FromSeconds(bindingProperties.NetParameter.IdleTimeout); tcpe.ListenBacklog = bindingProperties.NetParameter.ListenBacklog; tcpe.ConnectionPoolSettings.MaxOutboundConnectionsPerEndpoint = bindingProperties.NetParameter.MaxOutboundConnectionsPerEndpoint; tcpe.MaxOutputDelay = TimeSpan.FromSeconds(bindingProperties.NetParameter.MaxOutputDelay); tcpe.MaxPendingAccepts = bindingProperties.NetParameter.MaxPendingAccepts; tcpe.MaxPendingConnections = bindingProperties.NetParameter.MaxPendingConnections; cb.Elements.Add(tcpe); binding = cb; }
private void initTestService() { InterfaceConfiguration iconf1 = new InterfaceConfiguration("SimpleInterface", "Simple Interface", new RuntimeInfo(typeof(ISimpleInterface), typeof(SimpleInterfaceImpl))); InterfaceConfiguration iconf2 = new InterfaceConfiguration("TestInterface", "Test Interface", new RuntimeInfo(typeof(ITestInterface), typeof(TestInterfaceImpl))); ServiceConfig sconf = new ServiceConfig("hxf_service", "HXF Service"); sconf.InterfaceConfigs.Add(iconf1); sconf.InterfaceConfigs.Add(iconf2); testService = ServiceBuilder.BuildFromServiceConf(sconf); TreeBuilder builder = new TreeBuilder(testService); TreeNode rootNode = builder.Build(); treeView.Nodes.Add(rootNode); edtJson.Text = testService.ToJson(); }
private static extern bool ChangeServiceConfig2( IntPtr hService, ServiceConfig dwInfoLevel, ref SERVICE_DESCRIPTION lpInfo);
/// <summary> /// load system configurations from DB /// </summary> private void LoadConfigurations() { FulfillmentInterval = ((int)configProxy.GetFulfillmentInterval()).ToString(); ReportInterval = ((int)configProxy.GetReportInterval()).ToString(); internalServiceConfig = configProxy.GetInternalServiceConfig(); Uri internalUri = new Uri(internalServiceConfig.ServiceHostUrl); InternalServiceHost = internalUri.Host; InternalServicePort = internalUri.Port.ToString(); IsAutoFulfillment = configProxy.GetCanAutoFulfill(); IsAutoReport = configProxy.GetCanAutoReport(); OldTimeLine = ((int)configProxy.GetOldTimeline()).ToString(); MsServiceConfig = configProxy.GetMsServiceConfig().ServiceHostUrl; DisCert cert = configProxy.GetCertificateSubject(); if (KmtConstants.IsOemCorp) CertificateSubject = cert.Subject; if (KmtConstants.IsTpiCorp && KmtConstants.CurrentHeadQuarter != null) CertificateSubject = KmtConstants.CurrentHeadQuarter.CertSubject; sourceCertSubject = CertificateSubject; sourceFulfillmentInterval = FulfillmentInterval; sourceReportInterval = ReportInterval; sourceInternalServiceHost = InternalServiceHost; sourceInternalServicePort = InternalServicePort; sourceIsAutoFulfillment = IsAutoFulfillment; sourceIsAutoReport = IsAutoReport; sourceOldTimeLine = OldTimeLine; sourceMsServiceConfig = MsServiceConfig; }
// Methods public static void Enter(ServiceConfig cfg) { }
private void LoadConfigurations() { GetKeysInterval = ((int)configProxy.GetKeysInterval()).ToString(); oemServiceConfig = configProxy.GetServiceConfig(); internalServiceConfig = configProxy.GetInternalServiceConfig(); Uri oemUri = new Uri(OemServiceConfig.ServiceHostUrl); OemServiceHost = oemUri.Host; OemServicePort = oemUri.Port.ToString(); Uri internalUri = new Uri(InternalServiceConfig.ServiceHostUrl); InternalServiceHost = internalUri.Host; InternalServicePort = internalUri.Port.ToString(); }
/// <summary> /// Notify user /// </summary> /// <param name="data">The notification view item (notiID, notiType, notiText, notiDate, ID_hrStaff, FullName, notiStatus, notiSysStatus, notiReaded, notiGroup, notiParticipiant, notiSender, notiRecipients, notiCc</param> /// <param name="staffid">user id</param> /// <returns></returns> public static bool notify(ref ServiceConfig srvcont, object data, string groupName, int? staffid = null) { try { System.Net.ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(delegate { return true; }); var request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create("https://tr-web:8080/notify"); object post_data = null; if (staffid != null) // notify a user post_data = new { staffId = staffid.Value, body = data }; else if (!string.IsNullOrEmpty(groupName)) // notify the group { var user_list = srvcont.DataContext.tbl_genNotificationGroup.Where(a => a.GroupName == groupName) .Select(a => a.ID_hrStaff); foreach (var user in user_list) // notify a user Additional.Notification.notify(ref srvcont, data, "", user); return true; } else // notify all user post_data = new { body = data }; var data_string = Newtonsoft.Json.JsonConvert.SerializeObject(post_data); request.ContentType = "application/json"; request.Method = "POST"; using (var streamWriter = new System.IO.StreamWriter(request.GetRequestStream())) { streamWriter.Write(data_string); streamWriter.Flush(); streamWriter.Close(); } var httpResponse = (System.Net.HttpWebResponse)request.GetResponse(); using (var streamReader = new System.IO.StreamReader(httpResponse.GetResponseStream())) { var result = streamReader.ReadToEnd(); } } catch (Exception ez) { return false; } return true; }
public RemoraHostConfig() { ServiceConfig = new ServiceConfig(); BindingConfigs = new IBindingConfig[0]; JobsConfig = new JobsConfig(); }
public string GetServiceDescription(ServiceConfig service) { return this.GetFacade(service.HostUri).GetServiceDescription(service); }
/// <summary> /// return SysStatus changed (bool) True: Yes, False: No /// </summary> /// <param name="srvcont"></param> /// <param name="notification_id"></param> /// <returns></returns> public static bool recalcSysStatus(ServiceConfig srvcont, int notification_id, out string sysStatus) { if (Notification.statuses_dict.Count == 0) { var dimObject = srvcont.DataContext.tbl_genDimension.FirstOrDefault(a => a.Dimension == "NotificationStatus"); int dim = dimObject.ID; var dimensionitems = srvcont.DataContext.tbl_genDimensionItem.Where(a => a.ID_genDimension == dim); foreach (var status in dimensionitems) { Notification.statuses_dict.Add(status.DimensionItem, status.ID); } } if (Notification.types.Count == 0) { var dimObject = srvcont.DataContext.tbl_genDimension.FirstOrDefault(a => a.Dimension == "NotificationType"); int dim = dimObject.ID; var dimensionitems = srvcont.DataContext.tbl_genDimensionItem.Where(a => a.ID_genDimension == dim); foreach (var status in dimensionitems) { types.Add(status.ID, status.DimensionItem); } } var notification = srvcont.DataContext.view_genNotification.Where(a => a.notiID == notification_id).ToList(); var originalNotification = srvcont.DataContext.tbl_genNofitication.FirstOrDefault(a => a.ID == notification_id); Dictionary<int, int> actual_statuses = new Dictionary<int, int>(); // int: status, int: count foreach (var noti in notification) { int status_id = Notification.statuses_dict[noti.notiStatus]; if (!actual_statuses.ContainsKey(status_id)) actual_statuses.Add(status_id, 1); else actual_statuses[status_id]++; } string newSysStatus = null; string notiType = Notification.types[originalNotification.ID_NotificationType]; switch (notiType) { case "Normal": { newSysStatus = "Finished"; } break; case "Vacation approval": { // lemondva if (actual_statuses.ContainsKey(Notification.statuses_dict["Canceled"])) newSysStatus = "Canceled"; // nincs elfogadva else if (actual_statuses.ContainsKey(Notification.statuses_dict["Rejected"])) newSysStatus = "Rejected"; // még nem történt vele semmi else if (notification.Where(a => a.notiParticipiant == "Recipient").All(a => a.notiStatus == "Waiting")) newSysStatus = "Waiting"; // folyamatban van else if (notification.Exists(a => a.notiStatus == "Approved") && (notification.Exists(a => a.notiStatus != "Approved" && a.notiParticipiant == "Recipient"))) newSysStatus = "In progress"; // elfogadva else if (notification.Where(a => a.notiParticipiant == "Recipient").All(a => a.notiStatus == "Approved")) newSysStatus = "Approved"; } break; case "PDS change": { // lemondva if (actual_statuses.ContainsKey(Notification.statuses_dict["Canceled"])) newSysStatus = "Canceled"; // még nem történt vele semmi else if (notification.Where(a => a.notiParticipiant == "Recipient").All(a => a.notiStatus == "Waiting")) newSysStatus = "Waiting"; // folyamatban van else if (notification.Exists(a => a.notiStatus == "In progress")) newSysStatus = "In progress"; // elfogadva else if (notification.Exists(a => a.notiStatus == "Finished")) newSysStatus = "Finished"; } break; } sysStatus = newSysStatus; if(newSysStatus != null) { int newSysStatus_value = Notification.statuses_dict[newSysStatus]; if(newSysStatus_value != originalNotification.SysStatus){ originalNotification.SysStatus = newSysStatus_value; srvcont.DataContext.SaveChanges(); return true; } } return false; }
public NodeService(ServiceConfig config) : base(config) { }
public static IEnumerable<object> getNotificationHistory(ServiceConfig srvcont, int notification_id) { if (Notification.statuses_dict.Count == 0) { var dimObject = srvcont.DataContext.tbl_genDimension.FirstOrDefault(a => a.Dimension == "NotificationStatus"); int dim = dimObject.ID; var dimensionitems = srvcont.DataContext.tbl_genDimensionItem.Where(a => a.ID_genDimension == dim); foreach (var status in dimensionitems) { Notification.statuses_dict.Add(status.DimensionItem, status.ID); } } var statuses = srvcont.DataContext.tbl_genNotificationUserStatus.Where(a=> a.ID_Notification == notification_id).ToList(); var stafflist = srvcont.DataContext.tbl_hrStaff; var status_list = Notification.statuses_dict.Select(a => new { id = a.Value, name = a.Key }).ToList(); var notificationHistory = from s in statuses join ls in stafflist on s.ID_hrStaff equals ls.ID join stat in status_list on s.ID_NotificationStatus equals stat.id select new { Name = ls.FullName, Status = stat.name, Comment = s.Comment, Date = s.VALID_FROM }; var ret = notificationHistory.OrderByDescending(a=> a.Date).ToList(); return ret; }
public static void LogException(string exToHandle, ServiceConfig srvcont, string message) { if (srvcont.ConfigurationParameters.ExceptionLogNeeded) { DateTime dNow = DateTime.Now; Entities.tbl_genLog logentry = new Entities.tbl_genLog(); logentry.ID_LogType = 1; logentry.LogID = "Exception"; logentry.RequestText = message; logentry.LogText = exToHandle; logentry.CREATED_BY = 2; logentry.TS_CREATE = dNow; logentry.VALID_FROM = dNow; logentry.VALID_TO = dNow; srvcont.DataContext.tbl_genLog.AddObject(logentry); try { srvcont.DataContext.SaveChanges(); } catch (Exception ex) { throw; } } }
/// <summary> /// 获取服务的定义描述文本 /// </summary> /// <param name="service"></param> /// <returns></returns> public virtual string GetServiceDescription(ServiceConfig service) { return this._endpoint.GetServiceDescription(service); }
public void Register(Uri uri, ServiceConfig[] services) { this.GetFacade(uri).Register(services); }
public ResponseItem VoidTest(RequestItem Item) { ResponseItem re = new ResponseItem(Item); re.RequestItem.RequestLog = re.RequestItem.RequestLog + "srv_start: " + DateTime.Now.ToString() + ","; ServiceConfig srvcont = new ServiceConfig(_serviceconfigparameters); decimal? TR_SubmitMinHours = null; Queries.GetQueries getQ = new Queries.GetQueries(_serviceconfigparameters); RuntimeProperties _RuntimeProperties = new RuntimeProperties(_serviceconfigparameters); _RuntimeProperties.GetPersonalProperties(Item.reqp_userid); try { TR_SubmitMinHours = getQ.tbl_hrWorkingHourTemplate_MinHoursDaily(Item.reqp_userid, Item.reqp_date, _RuntimeProperties.CalendarName.GetValue()); // TRS_PrivateGetDailyHourLimitByUser(Item.reqp_date, Item.reqp_userid); TR_SubmitMinHours = TR_SubmitMinHours == null ? Convert.ToDecimal(8.25) : TR_SubmitMinHours; HelperClasses.Serializer srl = new HelperClasses.Serializer(); string hour = srl.NTSoftJsonSerialize(TR_SubmitMinHours.ToString()); re.ResponseBody = hour.Replace(",", "."); re.RequestCompleted = true; } catch (Exception ex) { HelperClasses.ExceptionHandler.LogException(ex, srvcont, Item); //re.ResponseBody = ex.ToString(); re.RequestCompleted = false; } re.RequestItem.RequestLog = re.RequestItem.RequestLog + "srv_finish: " + DateTime.Now.ToString() + ","; return re; }
public static IEnumerable<object> getNotificationStatuses(ServiceConfig srvcont, view_genNotification noti) { if (Notification.statuses_dict.Count == 0) { var dimObject = srvcont.DataContext.tbl_genDimension.FirstOrDefault(a => a.Dimension == "NotificationStatus"); int dim = dimObject.ID; var dimensionitems = srvcont.DataContext.tbl_genDimensionItem.Where(a => a.ID_genDimension == dim); foreach (var status in dimensionitems) { Notification.statuses_dict.Add(status.DimensionItem, status.ID); } } if (Notification.types.Count == 0) { var dimObject = srvcont.DataContext.tbl_genDimension.FirstOrDefault(a => a.Dimension == "NotificationType"); int dim = dimObject.ID; var dimensionitems = srvcont.DataContext.tbl_genDimensionItem.Where(a => a.ID_genDimension == dim); foreach (var status in dimensionitems) { types.Add(status.ID, status.DimensionItem); } } if (Notification.participant.Count == 0) { var dimObject = srvcont.DataContext.tbl_genDimension.FirstOrDefault(a => a.Dimension == "NotificationParticipant"); int dim = dimObject.ID; var dimensionitems = srvcont.DataContext.tbl_genDimensionItem.Where(a => a.ID_genDimension == dim); foreach (var part in dimensionitems) { participant.Add(part.DimensionItem, part.ID); } } int participant_id = participant[noti.notiParticipiant]; var nType = types.FirstOrDefault(a=> a.Value == noti.notiType); int type_id = nType.Key; List<object> statuses = new List<object>(); foreach(var tmp in srvcont.DataContext.tbl_genNotificationStatusMap .Where(a => a.ID_NotificationType == type_id && a.ID_NotificationParticipant == participant_id).ToList()) { statuses.Add( new { ID = tmp.ID_NotificationStatus, Name = Notification.statuses_dict.ContainsValue(tmp.ID_NotificationStatus) ? Notification.statuses_dict.FirstOrDefault(b => b.Value == tmp.ID_NotificationStatus).Key : "" } ); } return statuses; }
public ServiceTest() { _serviceconfigparameters = new ServiceConfigParameters(ServiceEnvironment.BUDPS_NODE1_DEVS, true, true, true); srvcont = new ServiceConfig(_serviceconfigparameters); }
private void LoadConfigurations() { serviceConfig = configProxy.GetServiceConfig(); Uri serviceUri = new Uri(ServiceConfig.ServiceHostUrl); ServiceHost = serviceUri.Host; ServicePort = serviceUri.Port.ToString(); }
public static void createNotification(ref ServiceConfig srvcont, ref List<Notification> notis) { for (int i = 0; i < notis.Count(); i++ ) { var cnoti = notis[i]; int? nID = notis[i].notiID; var tmp = srvcont.DataContext.tbl_genNotificationItem.Where(c => c.notificationID == nID); if (tmp.Count() > 0) notis[i].additional = tmp.Select(b => new { b.Property, b.Value }).ToList(); notis[i].history = Additional.Notification.getNotificationHistory(srvcont, notis[i].notiID); var notiView = srvcont.DataContext.view_genNotification .FirstOrDefault(a => a.notiID == cnoti.notiID && a.ID_hrStaff == cnoti.ID_hrStaff); if(notiView != null) notis[i].statuses = Additional.Notification.getNotificationStatuses(srvcont, notiView); } }
public TaskService(ServiceConfig config) : base(config) { }
public UserService(ServiceConfig config) : base(config) { }
/// <summary> /// 向服务节点注册服务 /// </summary> /// <param name="services">服务配置</param> public void Register(ServiceConfig[] services) { this._endpoint.Register(services); }
public static void setNotificationReaded(ServiceConfig srvcont, int notification_id, int groupID, int staff_id, bool readed) { var notificatioGroup = srvcont.DataContext.tbl_genNotificationUserGroup .Where(a => a.ID_Notification == notification_id && a.ID == groupID); if (notificatioGroup.Count() > 0) { foreach (var noti in notificatioGroup) noti.Readed = readed; srvcont.DataContext.SaveChanges(); } }