public void CanCreateService() { var factory = new ServiceFactory(new Mock<IDependencyResolver>().Object); var service = factory.CreateService<ITestService2>(); Assert.That(service, Is.Not.Null); }
public void obtain_proxy_from_service_factory() { IServiceFactory factory = new ServiceFactory(); IOrderService proxy = factory.CreateClient<IOrderService>(); Assert.IsTrue(proxy is OrderClient); }
public void obtain_proxy_from_service_factory() { var factory = new ServiceFactory(); var proxy = factory.CreateClient<IInventoryService>(); Assert.IsTrue(proxy is InventoryClient); }
public DfsContext(IDfsConfiguration dfsConfiguration) { this.dfsConfiguration = dfsConfiguration; serviceFactory = ServiceFactory.Instance; var contextFactory = ContextFactory.Instance; serviceContext = contextFactory.NewContext(); var repositoryIdentity = new RepositoryIdentity(dfsConfiguration.Repository, dfsConfiguration.UserName, dfsConfiguration.Password, string.Empty); serviceContext.AddIdentity(repositoryIdentity); var contentTransferProfile = new ContentTransferProfile { TransferMode = ContentTransferMode.MTOM }; serviceContext.SetProfile(contentTransferProfile); // Setting the filter to ALL can cause errors if the DataObject // passed to the operation contains system properties, so to be safe // set the filter to ALL_NON_SYSTEM unless you explicitly want to update // a system property var propertyProfile = new PropertyProfile { FilterMode = PropertyFilterMode.ALL_NON_SYSTEM }; serviceContext.SetProfile(propertyProfile); serviceContext.SetRuntimeProperty("USER_TRANSACTION_HINT", "TRANSACTION_REQUIRED"); }
public void ServiceFactory_Bestaat() { //Arrange var serviceFactory = new ServiceFactory<IKlant>("BSBeheerKlant"); //Assert Assert.IsInstanceOfType(serviceFactory, typeof(ServiceFactory<IKlant>)); }
public void ServiceFactory_GebruiktFileServiceLocator() { //Arrange var serviceFactory = new ServiceFactory<IKlant>("BSBeheerKlant"); //Assert Assert.IsInstanceOfType(serviceFactory.ServiceLocator, typeof(FileServiceLocator)); }
public void CanDeserializeMetadata() { var factory = new ServiceFactory(); var provider = factory.GetService<IMetadataProviderService>(); Assert.IsNotNull(provider); var metadata = provider.LoadMetadata(); Assert.AreNotEqual(0, metadata.Entities.Length); }
// GET: Klant public ActionResult Index() { ServiceFactory<IBSKlantBeheerService> factory = new ServiceFactory<IBSKlantBeheerService>("BSKlantbeheer"); var proxy = factory.CreateAgent(); var klant = proxy.FindKlanten(); return View(klant.Klanten); }
static InvoiceApp() { ModelContext = new Context("InvoiceContext"); ServiceFactory = new ServiceFactory("InvoiceContext"); RouteManager = new RouteManager(); Application.ThreadException += Application_ThreadException; Logger = LogManager.GetLogger("ThreadExceptionLogger"); }
static ServiceRegistry() { ServiceFactoryBuilder b = new ServiceFactoryBuilder(); string path = Path.Combine(AppDomain.CurrentDomain.RelativeSearchPath ?? AppDomain.CurrentDomain.BaseDirectory, "Easy.Register.Infrastructure.dll"); Stream stream = Assembly.ReflectionOnlyLoadFrom(path).GetManifestResourceStream("Easy.Register.Infrastructure.Service.service.xml"); factory = b.Build(stream); }
private Task<ResponseData> ProcessRequestInternal(Type serviceType, string operation, object[] arguments) { var factory = new ServiceFactory(new DependencyResolver()); var service = factory.CreateService(serviceType); var requestData = new RequestData(serviceType.FullName, operation, arguments); return service.Process(requestData); }
public MainViewModel(ServiceFactory<IFooService> testServiceFactory) { Property(() => CurrentFooItem).OnChanged(x => Loaded = true); testServiceFactory .Collection(this, x => x.FooList) .Fill(x => x.GetAll()) .Completed(x => CurrentFooItem = x.First()); }
public PreAssignedCollectionViewModel( IObservableCollection<CustomerViewModel> collection, ServiceFactory<ICustomerService> customerServiceFactory) { CustomerCollection = collection; customerServiceFactory .Collection(this, x => x.CustomerCollection) .Fill(x => x.GetCustomersWithTurnoverGreatherThan(0)); }
static RemoteLog() { try { logFactory = new ServiceFactory<ILog>(ServiceConfigs.GetConfigs("LogService")); } catch (Exception e) { string msg = e.Message; } }
static SequenceService() { if (Config.SequenceServiceType == 1) { iseq = new Sequence() as ISequence; return ; } factory = new ServiceFactory<ISequence>(ServiceConfig.GetConfigs(Config.SequenceServiceName)); iseq = factory.Instance(); return; }
public void ServiceFactory_VerwachtUnknownServiceLocatorException() { //Arrange var config = new ServiceLocatorConfigSection(); config.Active = "unknownServiceLocator"; var serviceFactory = new ServiceFactory<IKlant>("BSBeheerKlant", config); //Assert Assert.IsInstanceOfType(serviceFactory.ServiceLocator, typeof(WebServiceLocator<IKlant>)); }
public MainViewModel() { serviceFactory = ViewModelController.ServiceFactory<ICustomerService>(); timerFactory = ViewModelController.TimerFactory(); MessageBroker.Register<DeleteCustomerMessage>(this, DeleteCustomer); Property(() => FullName).OnChanged(x => NameLength = x.Length); InitializeProperties(); }
public static ServiceFactoryHelper Create() { var serviceStub = new CustomerServiceStub(); var customerServiceFactory = new DemoProxyFactory<ICustomerService>(serviceStub); var serviceFactory = new ServiceFactory<ICustomerService>(() => customerServiceFactory.Create()); var factory = new ServiceFactoryHelper(serviceFactory, serviceStub); return factory; }
public static void SetUp(TestContext test) { string baseUrl = "http://localhost:8787"; disposable = WebApp.Start<Startup>(new StartOptions(baseUrl)); DirectoryFactory.Register("testServiceDirectory", new StaticDirectory(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "testServiceDirectory.config"), "testServiceDirectory")); Easy.Domain.ServiceFramework.ServiceFactoryBuilder builder = new Domain.ServiceFramework.ServiceFactoryBuilder(); factory = builder.Build(new FileInfo(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "servcies.xml"))); }
public void ServiceFactory_GebruiktWebServiceLocator() { //Arrange var config = new ServiceLocatorConfigSection(); config.Active = "webServiceLocator"; config.WebServiceLocator.Address = "http://www.test.nl"; config.WebServiceLocator.Binding = "basicHttpBinding"; var serviceFactory = new ServiceFactory<IKlant>("BSBeheerKlant", config); //Assert Assert.IsInstanceOfType(serviceFactory.ServiceLocator, typeof(WebServiceLocator<IKlant>)); }
public override Service getService(string serviceTypeId, ServiceFactory serviceFactory) { if (serviceFactory != null) { // get the identity for this service--this is a simple way to both check whether this service is supported (it // be null if not supported) and to go ahead and get the identity in case we need to load the service Identity servicePrivateProxyIdentity = (Identity) supportedServices[serviceTypeId]; if (servicePrivateProxyIdentity != null) { Service service; lock (loadedServices.SyncRoot) { // see whether we've already loaded this service service = (Service) loadedServices[serviceTypeId]; // load the service if (service == null) { Trace.TraceInformation("DEBUG: TerkServiceProvider.getService() needs to load the [" + serviceTypeId + "] service"); try { // get the proxy for this service ObjectPrx servicePrx = communicator.getPeerProxy(peerUserId, servicePrivateProxyIdentity); // create the service service = serviceFactory.createService(serviceTypeId, servicePrx); // cache this service so future calls won't have to create it loadedServices.Add(serviceTypeId, service); } catch (PeerAccessException e) { Trace.TraceError("PeerAccessException while trying to get the peer proxy: {0}", e.reason); } catch (InvalidIdentityException e) { Trace.TraceError("InvalidIdentityException while trying to get the peer proxies: {0}", e.reason); } } } return service; } } return null; }
static void DeleteUser() { ServiceFactory factory = new ServiceFactory(); IUserService uService = factory.CreateUserService(); string username = "******"; bool success = uService.Delete(username); if (!success) { Console.WriteLine("ErrorCode: " + uService.LastError.ErrorCode); Console.WriteLine("ErrorMessage: " + uService.LastError.ErrorMessage); } else { Console.WriteLine(string.Format("User {0} was deleted.", username)); } }
static void Main(string[] args) { var r = new ServiceFactory(ServicesConfiguration.LoadFromJson("services.config.json")); var host1 = r.CreateHost<ServiceA>(); host1.Open(); var host2 = r.CreateHost<ServiceB>(); host2.Open(); var cli1 = new ClientFactory(ClientsConfiguration.LoadFromJson("clients.config.json")).CreateClient<IServiceA>(); Console.WriteLine(cli1.Operation1()); Console.WriteLine("Services are created and listening. Press ENTER to terminate..."); Console.ReadLine(); host1.Close(); host2.Close(); }
public void CreateTestFile() { if (!ConfigHelper.GetAppSettingOrDefault("TestFileCreation", false)) { return; } var factory = new ServiceFactory(); using (var tmp = TempDir.Create()) { var fileName = Path.Combine(tmp.Name, Guid.NewGuid() + ".txt"); try { //factory.Add<ICustomizeCodeDomService>(new CustomizeCodeDomService(new Dictionary<string, string> //{ // { "url", @"https://allegient.api.crm.dynamics.com/XRMServices/2011/Organization.svc"}, // { "namespace", @"Test.Xrm.Entities"}, // { "out", fileName }, // {"servicecontextname", "CrmContext"}, // {"codecustomization", "DLaB.CrmSvcUtilExtensions.Entity.CustomizeCodeDomService,DLaB.CrmSvcUtilExtensions"}, // {"codegenerationservice", "DLaB.CrmSvcUtilExtensions.Entity.CustomCodeGenerationService,DLaB.CrmSvcUtilExtensions" }, // {"codewriterfilter", "DLaB.CrmSvcUtilExtensions.Entity.CodeWriterFilterService,DLaB.CrmSvcUtilExtensions"}, // {"metadataproviderservice:", "DLaB.CrmSvcUtilExtensions.Entity.MetadataProviderService,DLaB.CrmSvcUtilExtensions"}, // {"namingservice", "DLaB.CrmSvcUtilExtensions.NamingService,DLaB.CrmSvcUtilExtensions"}, // {"username", "*****@*****.**"}, // {"password", "*********"} //})); // factory.Add<ICodeGenerationService>(new CustomCodeGenerationService(factory.GetService<ICodeGenerationService>())); // factory.Add<ICodeWriterFilterService>(new CodeWriterFilterService(factory.GetService<ICodeWriterFilterService>())); // factory.Add<INamingService>(new NamingService(factory.GetService<INamingService>())); factory.GetService<ICodeGenerationService>(). Write(factory.GetMetadata(), "CS", fileName, "DLaB.CrmSvcUtilExtensions.UnitTest", factory.ServiceProvider); } catch (Exception ex) { // Line for adding a debug breakpoint var message = ex.Message; } } }
protected override void BeginProcessing() { var storeSettings = StoreSettings.DefaultSettings(); storeSettings.ConnectionString = ConnectionString ?? storeSettings.ConnectionString; storeSettings.Database = Database ?? storeSettings.Database; storeSettings.ClientCollection = ClientCollection ?? storeSettings.ClientCollection; storeSettings.ScopeCollection = ScopeCollection ?? storeSettings.ScopeCollection; storeSettings.ConsentCollection = ConsentCollection ?? storeSettings.ConsentCollection; storeSettings.AuthorizationCodeCollection = AuthorizationCodeCollection ?? storeSettings.AuthorizationCodeCollection; storeSettings.RefreshTokenCollection = RefreshTokenCollection ?? storeSettings.RefreshTokenCollection; storeSettings.TokenHandleCollection = TokenHandleCollection ?? storeSettings.TokenHandleCollection; CanCreateDatabase(storeSettings); var serviceFactory = new ServiceFactory(null, storeSettings); var factory = new Factory(serviceFactory, new AdminServiceRegistry()); _adminService = factory.Resolve<IAdminService>(); _tokenCleanupService = factory.Resolve<ICleanupExpiredTokens>(); _scopeStore = factory.Resolve<IScopeStore>(); base.BeginProcessing(); }
private void FrmPayment_Load(object sender, EventArgs e) { try { if (_CustomerService == null) { _CustomerService = ServiceFactory.GenerateServiceInstance().GenerateCustomerService(); } if (_CommonService == null) { _CommonService = ServiceFactory.GenerateServiceInstance().GenerateCommonService(); } ThreadStart threadStart = UpdateControlContent; var thread = new Thread(threadStart) { IsBackground = true }; thread.Start(); if (AppContext.ExchangeRate != null) { _exchangeRate = AppContext.ExchangeRate.ExchangeValue; } _discountCardList = new BindingList <DiscountCard>(); cmbDiscountCard.DataSource = _discountCardList; cmbDiscountCard.DisplayMember = DiscountCard.ConstDiscountCardNumber; cmbDiscountCard.ValueMember = DiscountCard.ConstDiscountCardId; _customerList = new BindingList <Customer>(); lsbCustomer.DataSource = _customerList; lsbCustomer.DisplayMember = Customer.ConstCustomerDisplayName; lsbCustomer.ValueMember = Customer.ConstCustomerId; txtExchangeRate.Text = _exchangeRate.ToString("N", AppContext.CultureInfo); txtCurrentSaleAmount.Text = _TotalAmountInt.ToString("N", AppContext.CultureInfo); CalculateDiscount(); if (UserService.AllowToPerform(Resources.PermissionSpecialDiscount)) { cmbDCountType.Enabled = true; } if (CommonService.IsIntegratedModule(Resources.ModCustomer)) { IList searchCriteria = new List <string> { "CustomerName|Retail customer" }; var customerList = _CustomerService.GetCustomers(searchCriteria); foreach (Customer customer in customerList) { _customerList.Add(customer); } //txtSearch.Enabled = false; //lsbCustomer.Enabled = false; //btnNew.Enabled = false; } } catch (Exception exception) { FrmExtendedMessageBox.UnknownErrorMessage( Resources.MsgCaptionUnknownError, exception.Message); } }
public SequentialMediator(ServiceFactory serviceFactory) : base(serviceFactory) { }
public CookieAuthenticationService(IIdentityService auth) { Auth = auth ?? ServiceFactory.Get <IIdentityService>(); }
public override void AgentReset() { Logger.Log(LogLevel.Debug, "AgentReset"); _game = ServiceFactory.GetService <GameService>().CreateNewGame(); }
internal IOrganizationService GetWorkflowService() { return(ServiceFactory.CreateOrganizationService(null, new MockupServiceSettings(false, true, MockupServiceSettings.Role.SDK))); }
void Application_Error() { ResetContext(); ServiceFactory EventLogFactory = new ServiceFactory(); Exception exception = Server.GetLastError(); if (exception != null) { Response.Clear(); HttpException httpException = new HttpException(exception.Message, exception); var cxt = new HttpContextWrapper(Context); RouteData routeData = new RouteData(); routeData.Values.Add("controller", "Home"); string ModuleNam ="/"+ Context.Request.RequestContext.RouteData.Values["controller"].ToString()+"/"; string FunctionName = Context.Request.RequestContext.RouteData.Values["action"].ToString(); string ExceptionalType = exception.Message; string ExceptionalDescription = exception.ToString(); string State = "1"; if (httpException != null) { switch (httpException.GetHttpCode()) { case 404: if (Context.Request.RequestContext.RouteData.Values["action"].ToString() == "Index") { routeData.Values.Add("action", "PageNotFound"); routeData.Values.Add("PageNotFoundLog", exception.Message); } else { routeData.Values.Add("action", "AjaxPageNotFound"); routeData.Values.Add("AjaxPageNotFoundLog", exception.Message); } break; case 500: if (Context.Request.RequestContext.RouteData.Values["action"].ToString() == "Index") { routeData.Values.Add("action", "ServerError"); routeData.Values.Add("ServerErrorLog", exception.Message); } else { routeData.Values.Add("action", "AjaxServerError"); routeData.Values.Add("AjaxServerErrorLog", exception.Message); } Trace.TraceError("Server Error occured and caught in Global.asax - {0}", exception.ToString()); break; default: if (Context.Request.RequestContext.RouteData.Values["action"].ToString() == "Index") { routeData.Values.Add("action", "Error"); routeData.Values.Add("ErrorLog", exception.Message); routeData.Values.Add("errorCode", httpException.GetHttpCode()); } else { routeData.Values.Add("action", "AjaxError"); routeData.Values.Add("AjaxErrorLog", exception.Message); routeData.Values.Add("errorCode", httpException.GetHttpCode()); } Trace.TraceError("Error occured and caught in Global.asax - {0}", exception.ToString()); break; } } EventLogFactory.GetService<IExceptionalLogService>().CreateExceptionLog(ModuleNam, FunctionName, ExceptionalType, ExceptionalDescription, State); Server.ClearError(); Response.TrySkipIisCustomErrors = true; IController errorController = new HomeController(); errorController.Execute(new RequestContext(new HttpContextWrapper(Context), routeData)); } }
public UserController(ServiceFactory service) { _service = service; }
/// <summary> /// To create a new work history details /// </summary> /// <param name="jobSeekerWorkHistoryObj">WorkHistory object</param> public string Post(EmployerMessage jobSeekerWorkHistoryObj) { jobSeekerWorkHistoryObj.JobSeekerId = SkillsmartUser.GuidStr(HttpContext.Current.User); ServiceFactory.GetEmployerMessages().Create(jobSeekerWorkHistoryObj); return(jobSeekerWorkHistoryObj.Id.ToString()); }
public TopicController() : base() { _categoryService = ServiceFactory.Get <ICategoryService>(); _topicServic = ServiceFactory.Get <ITopicService>(); _postSevice = ServiceFactory.Get <IPostSevice>(); }
public static void Register(ServiceFactory factory, bool isRegister) { factory.Register(typeof(IOrderService), new OrderService(), isRegister); /*add customized code between this region*/ /*add customized code between this region*/ }
public static string Lang(this HtmlHelper helper, string key) { var locService = ServiceFactory.Get <LocalizationService>(); return(locService.GetResourceString(key)); }
public override Process <TRequest, TResponse> BuildPipeline( ServiceFactory factory, Process <TNextRequest, TNextResponse> nextProcess ) => _tail.BuildPipeline(factory, Segments.Connect(_middleware, nextProcess));
private PositionCache() { positionService = ServiceFactory.Create <IPositionService>(); }
public CategoryService(ServiceFactory serviceFactory) { _context = serviceFactory.Context; }
/// <summary> /// Adds all services defined by the specified service layer extension point. /// </summary> /// <remarks> /// This method internally calls the <see cref="ApplyInterceptors"/> method to decorate /// the services with a set of AOP interceptors. /// </remarks> /// <param name="serviceLayer"></param> public void AddServices(IExtensionPoint serviceLayer) { IServiceFactory serviceFactory = new ServiceFactory(serviceLayer); ApplyInterceptors(serviceFactory.Interceptors); AddServices(serviceFactory); }
public ConnectedProjector(T connector, ServiceFactory serviceFactory) { _connector = connector ?? throw new ArgumentNullException(nameof(connector)); _serviceFactory = serviceFactory ?? throw new ArgumentNullException(nameof(serviceFactory)); }
/// <summary> /// To get details of a particular work history of a jobseeker /// </summary> /// <param name="id">workhistoryid</param> /// <returns>work history object</returns> public EmployerMessage Get(string id) { return(ServiceFactory.GetEmployerMessages().GetById(id)); }
public FilledViewModel(ServiceFactory<ICustomerService> customerServiceFactory) { customerServiceFactory .Collection(this, x => x.customerCollection) .Fill(x => x.GetCustomersWithTurnoverGreatherThan(0)); }
/// <summary> /// To get all jobseeker work history /// </summary> /// <returns>List of all work history of jobseeker</returns> public IEnumerable <EmployerMessage> GetAllJobSeekerMessages() { return(ServiceFactory.GetEmployerMessages().GetAllEmployerMessages(SkillsmartUser.GuidStr(HttpContext.Current.User))); }
void Session_End() { if (Session["userName"] != null) { ServiceFactory UserFactory = new ServiceFactory(); UserFactory.GetService<IUserService>().DeleteUserIp(Session["userName"].ToString()); UserFactory.GetService<ILoginLogService>().UpdateLoginLog(Session["userName"].ToString(), DateTime.Now.ToString()); } }
public RouteController(ServiceFactory serviceFactory) : base(serviceFactory) { }
// GET: Admin/Delete/5 public ActionResult Delete(int id) { Category category = ServiceFactory.GetCategoryService().Get(id); return(View(category)); }
public ActionResult Edit(Category category) { int i = ServiceFactory.GetCategoryService().Update(category); return(RedirectToAction("Index")); }
public CustomMediator(ServiceFactory serviceFactory, Func <IEnumerable <Func <INotification, CancellationToken, Task> >, INotification, CancellationToken, Task> publish) : base(serviceFactory) { _publish = publish; }
public async Task <IHttpActionResult> UpdateServiceHealthState(UpdateHealthRequest request) { var error = ""; var handler = HandlersFactory.GetProfilerHandler(TheSettingService, TheLoggerService); handler.Start(LOG_TAG, "UpdateServiceHealthState", GetServiceProperties()); try { UpdateHealthRequest.Validate(request); int ticketOrderServices = 0; int ticketOrderActors = 0; int eventActors = 0; ServiceLocationService locator = new ServiceLocationService(); UriBuilderService builder = new UriBuilderService(Constants.ContosoEventsApplicationInstance, Constants.ContosoEventsTicketOrderServiceName); ServicePartitionList partitions = await _fabricClient.QueryManager.GetPartitionListAsync(builder.ToUri()); foreach (Partition p in partitions) { long minKey = (p.PartitionInformation as Int64RangePartitionInformation).LowKey; ITicketOrderService dispenderService = locator.Create <ITicketOrderService>(builder.ToUri()); await dispenderService.UpdateHealthState(GetHealthStateFromString(request.State), request.Message); ticketOrderServices++; } ActorLocationService actorLocator = new ActorLocationService(); UriBuilderService orderActorBuilder = new UriBuilderService(Constants.ContosoEventsApplicationInstance, Constants.ContosoEventsTicketOrderActorName); ServicePartitionList orderActorPartitions = await _fabricClient.QueryManager.GetPartitionListAsync(orderActorBuilder.ToUri()); foreach (Partition p in orderActorPartitions) { string minKey = (p.PartitionInformation as Int64RangePartitionInformation).Id.ToString(); ITicketOrderActor actor = actorLocator.Create <ITicketOrderActor>(new ActorId(minKey), Constants.ContosoEventsApplicationName); await actor.UpdateHealthState(GetHealthStateFromString(request.State), request.Message); ticketOrderActors++; // May require contiunuation } IDataStoreService dataService = ServiceFactory.GetInstance().GetDataStoreService(TheSettingService, TheLoggerService); List <TicketEvent> events = await dataService.GetEvents(); UriBuilderService eventActorBuilder = new UriBuilderService(Constants.ContosoEventsApplicationInstance, Constants.ContosoEventsEventActorName); foreach (var tEvent in events) { IEventActor actor = actorLocator.Create <IEventActor>(new ActorId(tEvent.Id), Constants.ContosoEventsApplicationName); await actor.UpdateHealthState(GetHealthStateFromString(request.State), request.Message); eventActors++; // May require contiunuation } return(Ok("Done: " + ticketOrderServices + "|" + ticketOrderActors + "|" + eventActors)); } catch (Exception ex) { error = ex.Message; return(BadRequest(ex.Message)); } finally { handler.Stop(error); } }
public async Task GetForumStatsAsync_ShouldReturnCorrectResult() { // Arrange var serviceFactory = new ServiceFactory(); var userRepository = new EfDeletableEntityRepository <ApplicationUser>(serviceFactory.Context); var categoryRepository = new EfDeletableEntityRepository <Category>(serviceFactory.Context); var topicRepository = new EfDeletableEntityRepository <Topic>(serviceFactory.Context); var forumsService = new ForumsService( topicRepository, userRepository, categoryRepository, serviceFactory.UserManager); await serviceFactory.SeedRoleAsync(GlobalConstants.AdministratorRoleName); await serviceFactory.SeedRoleAsync(GlobalConstants.ModeratorRoleName); await topicRepository.AddAsync(new Topic() { Title = "TestTitle", }); await topicRepository.AddAsync(new Topic() { Title = "TestTitle", }); await topicRepository.SaveChangesAsync(); var firstUser = new ApplicationUser() { UserName = "******", }; var secondUser = new ApplicationUser() { UserName = "******", }; await userRepository.AddAsync(firstUser); await userRepository.AddAsync(secondUser); await userRepository.SaveChangesAsync(); await categoryRepository.AddAsync(new Category() { Name = "TestName", }); await categoryRepository.SaveChangesAsync(); await serviceFactory.UserManager.AddToRoleAsync(firstUser, GlobalConstants.AdministratorRoleName); await serviceFactory.UserManager.AddToRoleAsync(secondUser, GlobalConstants.ModeratorRoleName); // Act var expectedTopicsCount = 2; var expectedCategoriesCount = 1; var expectedUsersCount = 2; var expectedAdminsCount = 1; var expectedModeratorsCount = 1; var actualResult = await forumsService.GetForumStatsAsync(); // Assert Assert.Equal(expectedTopicsCount, actualResult.TotalTopicsCount); Assert.Equal(expectedCategoriesCount, actualResult.TotalCategoriesCount); Assert.Equal(expectedUsersCount, actualResult.TotalUsersCount); Assert.Equal(expectedAdminsCount, actualResult.TotalAdminsCount); Assert.Equal(expectedModeratorsCount, actualResult.TotalModeratorsCount); }
protected void btnSubmit_Click(object sender, EventArgs e) { if (this.IsValid) { IUserService service = ServiceFactory.GetService <IUserService>(); UserRole entity = null; List <UserRolePermission> rolePermissionList = new List <UserRolePermission>(); if (this.IsInsert) { entity = new UserRole() { RoleName = this.txtRoleName.Text.Trim(), DataFilter = this.ddlDataFilter.SelectedValue.ToByte(0), RoleStatus = this.ddlRoleStatus.SelectedValue.ToByte(0) }; if (service.CheckExists_Role(entity)) { this.JscriptMsg("角色名称已存在", null, "Error"); return; } } else { entity = service.GetObject_Role(this.PkId); if (entity != null) { entity.DataFilter = this.ddlDataFilter.SelectedValue.ToByte(0); entity.RoleStatus = this.ddlRoleStatus.SelectedValue.ToByte(0); } } service.Save_Role(entity); foreach (TreeNode tnOne in this.tvPermission.Nodes) { if (tnOne.Checked) { rolePermissionList.Add(new UserRolePermission() { RoleId = entity.PkId, PermCode = tnOne.Value }); } foreach (TreeNode tnTwo in tnOne.ChildNodes) { if (tnTwo.Checked) { rolePermissionList.Add(new UserRolePermission() { RoleId = entity.PkId, PermCode = tnTwo.Value }); } } } service.Delete_RolePermission(entity.PkId); service.Save_RolePermission(rolePermissionList); if (this.IsInsert && (sender as Button).CommandName == "SubmitContinue") { this.ReturnUrl = this.Request.Url.PathAndQuery; } this.JscriptMsg("数据保存成功", this.ReturnUrl, "Success"); } UserConvert.ClearCache(); }
private RunLogLocalDataToDbTask(int interval) : base("运行记录数据补录任务", interval) { FilePath = ConfigurationManager.FileConfiguration.GetString("FileDataToDbPath", @"C:\LocalDb") + "\\RunLog\\"; runLogRepositoty = ServiceFactory.Create <IJc_RRepository>(); }
/// <summary> /// Initializes a new instance of the <see cref="Mediator"/> class. /// </summary> /// <param name="serviceFactory">The single instance factory.</param> public Mediator(ServiceFactory serviceFactory) { _serviceFactory = serviceFactory; }
public string WMSBillService(string xml) { ServiceFactory factory = new ServiceFactory(); string result = null; string strResult = string.Empty; bool b = false; if (!string.IsNullOrEmpty(xml)) { XElement doc = null; try { doc = XElement.Parse(xml); bll.insert("Bill", xml); } catch (Exception) { result = ZipBase64(string.Format(returnMsg, MessageInfo("XML的数据格式不正确!"))); return result; } try { #region var heads var heads = from head in doc.Descendants("head") select new { MsgId = (head.Element("msg_id") ?? null) == null ? null : head.Element("msg_id").Value, StateCode = (head.Element("state_code") ?? null) == null ? null : head.Element("state_code").Value, StateDesc = (head.Element("state_desc") ?? null) == null ? null : head.Element("state_desc").Value, WsMark = (head.Element("ws_mark") ?? null) == null ? null : head.Element("ws_mark").Value, WsMethod = (head.Element("ws_method") ?? null) == null ? null : head.Element("ws_method").Value, WsParam = (head.Element("ws_param") ?? null) == null ? null : head.Element("ws_param").Value ?? "", CurrTime = (head.Element("curr_time") ?? null) == null ? null : head.Element("curr_time").Value ?? "", CurrUser = (head.Element("curr_user") ?? null) == null ? null : head.Element("curr_user").Value ?? "" }; #endregion #region var billMaster var billMaster = from data in doc.Descendants("data") select new { BillType = (data.Element("bb_type") ?? null) == null ? null : data.Element("bb_type").Value, UUID = (data.Element("bb_uuid") ?? null) == null ? null : data.Element("bb_uuid").Value, BillDate = (data.Element("bb_input_date") ?? null) == null ? null : data.Element("bb_input_date").Value, MakerName = (data.Element("bb_input_person") ?? null) == null ? null : data.Element("bb_input_person").Value, OperateDate = (data.Element("bb_oper_date") ?? null) == null ? null : data.Element("bb_oper_date").Value, CigaretteType = (data.Element("bb_cig_type") ?? null) == null ? null : data.Element("bb_cig_type").Value, BillCompanyCode = (data.Element("bb_commerce_code") ?? null) == null ? null : data.Element("bb_commerce_code").Value, SupplierCode = (data.Element("bb_flow_code") ?? null) == null ? null : data.Element("bb_flow_code").Value, SupplierType = (data.Element("bb_flow_type") ?? null) == null ? null : data.Element("bb_flow_type").Value, State = (data.Element("bb_state") ?? null) == null ? null : data.Element("bb_state").Value, BillDetail = from data_1 in doc.Descendants("data_1") select new { PieceCigarCode = (data_1.Element("bd_pcig_code") ?? null) == null ? null : data_1.Element("bd_pcig_code").Value, BoxCigarCode = (data_1.Element("bd_bcig_code") ?? null) == null ? null : data_1.Element("bd_bcig_code").Value, BillQuantity = (data_1.Element("bd_bill_all_num1") ?? null) == null ? null : data_1.Element("bd_bill_all_num1").Value, FixedQuantity = (data_1.Element("bd_bill_fixed_all_num1") ?? null) == null ? null : data_1.Element("bd_bill_fixed_all_num1").Value, RealQuantity = (data_1.Element("bd_bill_all_scan_num1") ?? null) == null ? null : data_1.Element("bd_bill_all_scan_num1").Value } }; #endregion #region var contract var contract = from cb1 in doc.Descendants("contract_base_1") select new { ContractCode = (cb1.Element("contract_no") ?? null) == null ? null : cb1.Element("contract_no").Value, SupplySideCode = (cb1.Element("a_no") ?? null) == null ? null : cb1.Element("a_no").Value, DemandSideCode = (cb1.Element("b_no") ?? null) == null ? null : cb1.Element("b_no").Value, ContractDate = (cb1.Element("contract_date") ?? null) == null ? null : cb1.Element("contract_date").Value, StartDade = (cb1.Element("start_date") ?? null) == null ? null : cb1.Element("start_date").Value, EndDate = (cb1.Element("start_date") ?? null) == null ? null : cb1.Element("end_date").Value, SendPlaceCode = (cb1.Element("send_code") ?? null) == null ? null : cb1.Element("send_code").Value, SendAddress = (cb1.Element("send_add") ?? null) == null ? null : cb1.Element("send_add").Value, ReceivePlaceCode = (cb1.Element("send_add") ?? null) == null ? null : cb1.Element("receive_code").Value, ReceiveAddress = (cb1.Element("receive_add") ?? null) == null ? null : cb1.Element("receive_add").Value, SaleDate = (cb1.Element("sale_date") ?? null) == null ? null : cb1.Element("sale_date").Value, State = (cb1.Element("use_state") ?? null) == null ? null : cb1.Element("use_state").Value, ContractDetail = from cd1 in doc.Descendants("contract_detail_1") select new { ContractCode = (cd1.Element("contract_no") ?? null) == null ? null : cd1.Element("contract_no").Value, BrandCode = (cd1.Element("brand_code") ?? null) == null ? null : cd1.Element("brand_code").Value, Quantity = (cd1.Element("num") ?? null) == null ? null : cd1.Element("num").Value, Price = (cd1.Element("price") ?? null) == null ? null : cd1.Element("price").Value, Amount = (cd1.Element("sum") ?? null) == null ? null : cd1.Element("sum").Value, TaxAmount = (cd1.Element("sum_tax") ?? null) == null ? null : cd1.Element("sum_tax").Value } }; #endregion #region var navicert var navicert = from zb1 in doc.Descendants("zyz_base_1") select new { NavicertCode = (zb1.Element("perm_id") ?? null) == null ? null : zb1.Element("perm_id").Value, NavicertDate = (zb1.Element("perm_date") ?? null) == null ? null : zb1.Element("perm_date").Value, TruckPlateNo = (zb1.Element("truck_no") ?? null) == null ? null : zb1.Element("truck_no").Value }; var contractCodes = from nc1 in doc.Descendants("contract_code") select new { ContractCode = nc1.Value ?? null }; #endregion var headList = heads.ToArray()[0]; if (headList.WsMethod == "BillCreate" || headList.WsMethod == "BillModify" || headList.WsMethod == "BillStart" || headList.WsMethod == "BillScan" || headList.WsMethod == "BillConfirm" || headList.WsMethod == "BillDelete") { using (var scope = new TransactionScope()) { BillMaster bm = new BillMaster(); BillDetail bd = new BillDetail(); Contract con = new Contract(); ContractDetail cd = new ContractDetail(); Navicert na = new Navicert(); Guid billMasterID = Guid.NewGuid(); #region BillMaster and BillDetail if (doc.Descendants("data") != null) { try { for (int i = 0; i < billMaster.Count(); i++) { var bmArray = billMaster.ToArray()[i]; Guid new_ID = new Guid(bmArray.UUID); bm.ID = new_ID; bm.BillType = bmArray.BillType; bm.UUID = bmArray.UUID; bm.BillDate = Convert.ToDateTime(bmArray.BillDate); bm.MakerName = bmArray.MakerName; bm.OperateDate = Convert.ToDateTime(bmArray.OperateDate == "" ? null : bmArray.OperateDate); bm.CigaretteType = bmArray.CigaretteType; bm.BillCompanyCode = bmArray.BillCompanyCode; bm.SupplierCode = bmArray.SupplierCode; bm.SupplierType = bmArray.SupplierType; bm.State = bmArray.State; if (headList.WsMethod == "BillModify" || headList.WsMethod == "BillStart" || headList.WsMethod == "BillScan" || headList.WsMethod == "BillConfirm") { b = factory.GetService<IBillMasterService>().Delete(con.ContractCode, bm.UUID, out strResult); } if (headList.WsMethod == "BillCreate" || b == true) { b = factory.GetService<IBillMasterService>().Add(bm, out strResult); } #region BillDetail if (doc.Descendants("data_1") != null) { for (int j = 0; j < bmArray.BillDetail.Count(); j++) { var bdArray = bmArray.BillDetail.ToArray()[j]; bd.ID = Guid.NewGuid(); bd.MasterID = bm.ID; bd.PieceCigarCode = bdArray.PieceCigarCode; bd.BoxCigarCode = bdArray.BoxCigarCode; bd.BillQuantity = Convert.ToDecimal(bdArray.BillQuantity); bd.FixedQuantity = Convert.ToDecimal(bdArray.FixedQuantity); bd.RealQuantity = Convert.ToDecimal(bdArray.RealQuantity); bd.BillMaster = bm; if (headList.WsMethod == "BillCreate" || headList.WsMethod == "BillModify" || headList.WsMethod == "BillStart" || headList.WsMethod == "BillScan" || headList.WsMethod == "BillConfirm") { b = factory.GetService<IBillDetailService>().Add(bd, out strResult); } if (headList.WsMethod == "BillDelete") { b = true; } } } #endregion } if (b == true) { result = ZipBase64(string.Format(returnMsg, MessageInfo("操作出入库单成功!"))); } else { result = ZipBase64(string.Format(returnMsg, MessageInfo("操作出入库单失败!"))); return result; } } catch (Exception) { result = ZipBase64(string.Format(returnMsg, MessageInfo("出入库单节点不匹配!"))); return result; } } #endregion #region Contract and ContractDetail if (doc.Descendants("contract_base_1") != null) { try { for (int k = 0; k < contract.Count(); k++) { var cArray = contract.ToArray()[k]; con.ContractCode = cArray.ContractCode; con.MasterID = bm.ID; con.SupplySideCode = cArray.SupplySideCode; con.DemandSideCode = cArray.DemandSideCode; con.ContractDate = Convert.ToDateTime(cArray.ContractDate); con.StartDade = Convert.ToDateTime(cArray.StartDade); con.EndDate = Convert.ToDateTime(cArray.EndDate); con.SendPlaceCode = cArray.SendPlaceCode; con.SendAddress = cArray.SendAddress; con.ReceivePlaceCode = cArray.ReceivePlaceCode; con.ReceiveAddress = cArray.ReceiveAddress; con.SaleDate = cArray.SaleDate; con.State = cArray.State; if (headList.WsMethod == "BillCreate" || headList.WsMethod == "BillModify" || headList.WsMethod == "BillStart" || headList.WsMethod == "BillScan" || headList.WsMethod == "BillConfirm") { b = factory.GetService<IContractService>().Add(con, out strResult); } #region ContractDetail if (doc.Descendants("contract_detail_1") != null) { for (int l = 0; l < cArray.ContractDetail.Count(); l++) { var cdArray = cArray.ContractDetail.ToArray()[l]; cd.ContractCode = cdArray.ContractCode; cd.BrandCode = cdArray.BrandCode; cd.Quantity = Convert.ToDecimal(cdArray.Quantity); cd.Price = Convert.ToDecimal(cdArray.Price); cd.Amount = Convert.ToInt32(cdArray.Amount); cd.TaxAmount = Convert.ToInt32(cdArray.TaxAmount); cd.Contract = con; if (headList.WsMethod == "BillCreate" || headList.WsMethod == "BillModify" || headList.WsMethod == "BillStart" || headList.WsMethod == "BillScan" || headList.WsMethod == "BillConfirm") { b = factory.GetService<IContractDetailService>().Add(cd, out strResult); } if (headList.WsMethod == "BillDelete") { b = true; } } } #endregion } if (b == true) { result = ZipBase64(string.Format(returnMsg, MessageInfo("操作合同表单成功!"))); } else { result = ZipBase64(string.Format(returnMsg, MessageInfo("操作合同表单失败!"))); return result; } } catch (Exception) { result = ZipBase64(string.Format(returnMsg, MessageInfo("合同表单节点不匹配!"))); return result; } } #endregion #region Navicert for contractCode if (doc.Descendants("zyz_base_1") != null && doc.Descendants("contract_code") != null) { try { for (int m = 0; m < contractCodes.Count(); m++) { var nArray = navicert.ToArray()[m]; foreach (var item in contractCodes) { na.ContractCode = item.ContractCode; na.ID = Guid.NewGuid(); na.MasterID = bm.ID; na.NavicertCode = nArray.NavicertCode; na.NavicertDate = Convert.ToDateTime(nArray.NavicertDate); na.TruckPlateNo = nArray.TruckPlateNo; na.Contract = con; if (headList.WsMethod == "BillCreate" || headList.WsMethod == "BillModify" || headList.WsMethod == "BillStart" || headList.WsMethod == "BillScan" || headList.WsMethod == "BillConfirm") { b = factory.GetService<INavicertService>().Add(na, out strResult); } if (headList.WsMethod == "BillDelete") { b = true; } } } if (b == true) { result = ZipBase64(string.Format(returnMsg, MessageInfo("操作准运证成功!"))); } else { result = ZipBase64(string.Format(returnMsg, MessageInfo("操作准运证失败!"))); return result; } } catch (Exception) { result = ZipBase64(string.Format(returnMsg, MessageInfo("准运证节点不匹配!"))); return result; } } #endregion #region Delete if (headList.WsMethod == "BillDelete") { b = factory.GetService<IBillMasterService>().Delete(con.ContractCode, bm.UUID, out strResult); } if (b == true) { scope.Complete(); result = ZipBase64(string.Format(returnMsg, headList.MsgId, headList.StateCode, headList.StateDesc, headList.WsMark, headList.WsMethod, headList.WsParam, headList.CurrTime, headList.CurrUser)); } else { result = ZipBase64(string.Format(returnMsg, MessageInfo("删除失败!"))); return result; } #endregion } } else if (headList.WsMethod == "PalletInfo") { result = WMSPalletInfo(xml); } else { result = ZipBase64(string.Format(returnMsg, MessageInfo("<ws_method></ws_method>标签内字段不匹配!"))); return result; } } catch (Exception) { result = ZipBase64(string.Format(returnMsg, MessageInfo("有几种可能性:1.XML标签不正确;2.MSDTC服务未开启;3.Hosts配置错误!"))); return result; } } else { return ZipBase64(string.Format(returnMsg, MessageInfo("XML参数是空的!"))); } return result; }
/// <summary> /// Initializes a new instance of the <see cref="ParallelMediator"/> class. /// </summary> /// <param name="serviceFactory">Service factory.</param> public ParallelMediator(ServiceFactory serviceFactory) : base(serviceFactory) { }
public EventHandlerBase() { RawHandlers = ServiceFactory.GetExportedService <IChannelMethodHandlerCollection>().AsList(); HandlerInfoCollection = ServiceFactory.GetExportedService <IInitiatedHandlersCollection>(); HandlerInfos = HandlerInfoCollection.Handlers; }
public ScheduleController(ServiceFactory serviceFactory) : base(serviceFactory) { }
public JsonResult GetCPUInfos() { return(Json(ServiceFactory.GetInstance().DBReportService.GetCPUInfos(), JsonRequestBehavior.AllowGet)); }
public void Save_Parameter(BasicParameter objBasicParameter) { var repository = ServiceFactory.GetService <IBasicParameterRepository>(); repository.Save(objBasicParameter); }