public void IsValidForRequest_CurrentRenderingIDMatch_ShouldReturnTrue(ValidateRenderingIdAttribute attribute, ControllerContext controllerContext, Guid id) { //arrange InitControllerContext(controllerContext); controllerContext.HttpContext.Request.Form.Add("uid", id.ToString()); ContextService.Get().Push(new RenderingContext { Rendering = new Rendering { UniqueId = id } }); //act and assert attribute.IsValidForRequest(controllerContext, null).Should().BeTrue(); }
public void Get_NoRenderingContextNoItemSiteContextNoDefaultSearchQuery_ShouldReturnNull() { var context = new RenderingContext { Rendering = new Rendering { Item = null } }; ContextService.Get().Push(context); var repository = new SearchContextRepository(); var searchContext = repository.Get(); searchContext.Should().BeNull(); }
public void Render(object model, RenderingContext context) { using (ContextService.Get().Push(context)) { var renderingModel = model as RenderingModel; if (renderingModel != null) { var renderingParameters = renderingModel.Rendering.Parameters.ToDictionary(k => k.Key, k => k.Value); _adaptee.Render(JObject.FromObject(renderingParameters), context); } else { _adaptee.Render(model, context); } } }
private async void OnMessage(ViewModelBase sender, string message, object args) { switch (message) { case "NewItemSaved": case "ItemDeleted": case "ItemsDeleted": case "ItemRangesDeleted": await ContextService.RunAsync(async() => { await RefreshAsync(); }); break; } }
public void IsValidForRequest_RenderingIdInFormNotGuid_ShouldReturnFalse(ValidateRenderingIdAttribute attribute, ControllerContext controllerContext, string formId, Guid id) { //arrange InitControllerContext(controllerContext); controllerContext.HttpContext.Request.Form.Add("uid", formId); ContextService.Get().Push(new RenderingContext { Rendering = new Rendering { UniqueId = id } }); //act and assert attribute.IsValidForRequest(controllerContext, null).Should().BeFalse(); }
public static List <InformeTrazabilidad> GenerateInformeTrazabilidad(ContextService db, bool insert = false, int?IdAgente = null, DateTime?FechaInicio = null, DateTime?FechaFin = null, bool?totalizar = false) { if (FechaInicio == null) { FechaFin = DateTime.Now.AddDays(-1).Date.AddDays(1).Date.AddSeconds(-1); FechaInicio = DateTime.Now.AddDays(-1).Date; } List <InformeTrazabilidad> model = new List <InformeTrazabilidad>(); model.AddRange(TrazabilidadUbicacionesProcess(db, insert, IdAgente, FechaInicio, FechaFin, totalizar)); model.AddRange(TrazabilidadAgendasProcess(db, insert, IdAgente, FechaInicio, FechaFin)); model.AddRange(TrazabilidadMarcacionesProcess(db, insert, IdAgente, FechaInicio, FechaFin, totalizar)); return(model); }
public UserKeyImportPubCommands() { IsCommand("user-key-import-pub", "Import public key for user"); HasRequiredOption("u|user="******"Enter user that exists already", arg => { if (string.IsNullOrEmpty(arg)) { throw new ConsoleHelpAsException($" *** No user name given ***"); } _conf = (IConfiguration) new ConfigurationBuilder() .AddJsonFile("clisettings.json", optional: false, reloadOnChange: true) .Build(); var instance = new ContextService(InstanceContext.DeployedOrLocal); _uow = new UnitOfWork(_conf["Databases:AuroraEntities"], instance); _user = _uow.Users.Get(QueryExpressionFactory.GetQueryExpression <tbl_User>() .Where(x => x.IdentityAlias == arg).ToLambda(), new List <Expression <Func <tbl_User, object> > >() { x => x.tbl_PrivateKey, x => x.tbl_PublicKey, }).SingleOrDefault(); if (_user == null) { throw new ConsoleHelpAsException($" *** Invalid user '{arg}' ***"); } }); HasRequiredOption("f|file=", "Enter file for import", arg => { _path = new FileInfo(arg); }); HasOption("c|comment=", "Enter public key comment", arg => { _pubKeyComment = arg; }); HasOption("b|base64=", "Is base64 \"authorized_keys\" format?", arg => { _base64 = bool.Parse(arg); }); }
public AudienceCreateCommand() { _conf = (IConfiguration) new ConfigurationBuilder() .AddJsonFile("clisettings.json", optional: false, reloadOnChange: true) .Build(); _map = new MapperConfiguration(x => x.AddProfile <AutoMapperProfile_EF6>()) .CreateMapper(); var env = new ContextService(InstanceContext.DeployedOrLocal); _uow = new UnitOfWork(_conf["Databases:IdentityEntities_EF6"], env); _service = new AdminService(_conf) { Grant = new ResourceOwnerGrantV2(_conf) }; IsCommand("audience-create", "Create audience"); HasRequiredOption("i|issuer=", "Enter existing issuer", arg => { if (string.IsNullOrEmpty(arg)) { throw new ConsoleHelpAsException($" *** No issuer given ***"); } _issuer = _uow.Issuers.Get(QueryExpressionFactory.GetQueryExpression <E_Issuer>() .Where(x => x.Name == arg).ToLambda()) .SingleOrDefault(); if (_issuer == null) { throw new ConsoleHelpAsException($" *** No issuer '{arg}' ***"); } }); HasRequiredOption("a|audience=", "Enter new audience", arg => { if (string.IsNullOrEmpty(arg)) { throw new ConsoleHelpAsException($" *** No audience given ***"); } _audienceName = arg; }); }
public void should_get_server_api() { // given var connectionService = new Mock <IConnectionService>(); var remoteServiceFactory = new Mock <IRemoteServiceFactory>(); var service = new ContextService(connectionService.Object, remoteServiceFactory.Object); var sedovCreds = Credentials.GetConnectionCredentials("sedov", "passwrd1"); var smithCreds = Credentials.GetConnectionCredentials("smith", "passwrd2"); var sedovHttpClient = new HttpPilotClient(""); var smithHttpClient = new HttpPilotClient(""); connectionService.Setup(cs => cs.Connect(sedovCreds)).Returns(sedovHttpClient); connectionService.Setup(cs => cs.Connect(smithCreds)).Returns(smithHttpClient); var sedovApi = new Mock <IRemoteService>(); var sedovServerApi = new Mock <IServerApiService>(); sedovApi.Setup(sa => sa.IsActive).Returns(true); sedovApi.Setup(sa => sa.GetServerApi()).Returns(sedovServerApi.Object); var smithApi = new Mock <IRemoteService>(); var smithServerApi = new Mock <IServerApiService>(); smithApi.Setup(sma => sma.IsActive).Returns(true); smithApi.Setup(sma => sma.GetServerApi()).Returns(smithServerApi.Object); remoteServiceFactory.Setup(rsf => rsf.CreateRemoteService(sedovHttpClient)).Returns(sedovApi.Object); remoteServiceFactory.Setup(rsf => rsf.CreateRemoteService(smithHttpClient)).Returns(smithApi.Object); service.CreateContext(sedovCreds); service.CreateContext(smithCreds); // when var api = service.GetServerApi("sedov"); // then Assert.NotNull(api); Assert.AreEqual(sedovServerApi.Object, api); // when var sapi = service.GetServerApi("smith"); // then Assert.NotNull(sapi); Assert.AreEqual(smithServerApi.Object, sapi); }
public void Setup() { route = new Mock <RouteBase>(); route .Setup(r => r.GetVirtualPath(It.IsAny <RequestContext>(), It.IsAny <RouteValueDictionary>())) .Returns(() => virtualPathData); virtualPathData = new VirtualPathData(route.Object, "~/VirtualPath"); routes = new RouteCollection(); routes.Add(route.Object); originalRouteData = new RouteData(); string returnValue = ""; httpContext = new Mock <HttpContextBase>(); httpContext .Setup(hc => hc.Request.ApplicationPath).Returns("~"); httpContext .Setup(hc => hc.Response.ApplyAppPathModifier(It.IsAny <string>())) .Callback <string>(s => returnValue = s) .Returns(() => returnValue); httpContext .Setup(hc => hc.Server.Execute(It.IsAny <IHttpHandler>(), It.IsAny <TextWriter>(), It.IsAny <bool>())); viewContext = new ViewContext { RequestContext = new RequestContext(httpContext.Object, originalRouteData) }; viewDataContainer = new Mock <IViewDataContainer>(); htmlHelper = new Mock <HtmlHelper>(viewContext, viewDataContainer.Object, routes); var requestContext = new RequestContext(httpContext.Object, originalRouteData); ContextService.Get().Push <PageContext>(new PageContext() { RequestContext = requestContext }); pageContext = new Mock <IPageContext>(); pageContext .Setup(x => x.RequestContext) .Returns(requestContext); }
public UserNetCreateCommands() { IsCommand("user-net-create", "Create allow/deny for user network"); HasRequiredOption("u|user="******"Enter user that already exists", arg => { if (string.IsNullOrEmpty(arg)) { throw new ConsoleHelpAsException($" *** No user name given ***"); } _conf = (IConfiguration) new ConfigurationBuilder() .AddJsonFile("clisettings.json", optional: false, reloadOnChange: true) .Build(); var instance = new ContextService(InstanceContext.DeployedOrLocal); _uow = new UnitOfWork(_conf["Databases:AuroraEntities"], instance); _user = _uow.Users.Get(QueryExpressionFactory.GetQueryExpression <tbl_User>() .Where(x => x.IdentityAlias == arg).ToLambda(), new List <Expression <Func <tbl_User, object> > >() { x => x.tbl_UserMount, }).SingleOrDefault(); if (_user == null) { throw new ConsoleHelpAsException($" *** Invalid user '{arg}' ***"); } }); HasRequiredOption("c|cidr=", "Enter CIDR address to use", arg => { if (!IPNetwork.TryParse(arg, out _cidr)) { throw new ConsoleHelpAsException($"*** Invalid cidr address ***"); } }); HasRequiredOption("a|action=", "Enter type of action to use", arg => { if (!Enum.TryParse(arg, out _actionType)) { throw new ConsoleHelpAsException($"*** Invalid auth type. Options are '{_actionTypeList}' ***"); } }); }
public override void GenerateEmployeePayslip() { try { // Configuration Validation if (!ContextService.IsValidDataContextSettings()) { return; } // Get Payment Summary List LogService.LogInfo("Load Data..."); var paymentSummaries = ContextService.GetPaymentSummaries(); if (paymentSummaries == null) { return; } // Generate Payslip LogService.LogInfo("Generate Payslip..."); var paySlipSummaries = new List <PayslipSummary>(); foreach (var payment in paymentSummaries) { var payslip = CreatePayslipSummary(payment); if (payslip != null) { paySlipSummaries.Add(payslip); } } if (paySlipSummaries.Count == 0) { return; } // Insert into Data Context LogService.LogInfo("Write Result..."); if (ContextService.SavePayslips(paySlipSummaries)) { LogService.LogInfo("Payslip Created..."); } } catch (Exception ex) { LogService.LogError(ex); } }
public CrmUnitOfWork() { var serviceUri = new Uri(Kipon.PluginRegistration.Security.Configuration.ConfigurationSingleton.Section.XrmServiceUrl); var orgServiceManagement = ServiceConfigurationFactory.CreateManagement <IOrganizationService>(serviceUri); var credentials = Kipon.PluginRegistration.Security.Xrm.AuthenticationHelper.GetCredentials(orgServiceManagement, Kipon.PluginRegistration.Security.Configuration.ConfigurationSingleton.Section.XrmAuthenticationProviderType); var orgService = Kipon.PluginRegistration.Security.Xrm.AuthenticationHelper.GetProxy <IOrganizationService, OrganizationServiceProxy>(orgServiceManagement, credentials); orgService.Timeout = new TimeSpan(0, 15, 0); orgService.EnableProxyTypes(typeof(ContextService).Assembly); Service = (IOrganizationService)orgService; this.context = new ContextService(Service); }
public void DatasourceString_EmptyDatasource_ContextItemAsLocationRoot([Content] Item renderingItem, [Greedy] QueryableDatasourceRenderingModel renderingModel) { //arrange ContextService.Get().Push(new PageContext()); PageContext.Current.Item = renderingItem; //act renderingModel.Initialize(new Rendering { DataSource = string.Empty, RenderingItem = new RenderingItem(renderingItem) }); //assert renderingModel.DatasourceString.Should().Be("+location:" + PageContext.Current.Item.ID); }
public void DatasourceString_EmptyDatasource_ContextItemAsLocationRoot([ResolvePipeline("getRenderingDatasource")] EmptyPipeline processor, [Content] Item renderingItem) { //arrange ContextService.Get().Push(new PageContext()); PageContext.Current.Item = renderingItem; var renderingModel = new QueryableDatasourceRenderingModel(); //act renderingModel.Initialize(new Rendering { DataSource = string.Empty, RenderingItem = new RenderingItem(renderingItem) }); //assert renderingModel.DatasourceString.Should().Be("+location:" + PageContext.Current.Item.ID); }
public AccountController( UserManager <DynamoIdentityUser> userManager, SignInManager <DynamoIdentityUser> signInManager, ContextService contextService, ISesService sesService, ClanAndPeopleService clanAndPeopleService, DynamoRoleUsersStore <DynamoIdentityRole, DynamoIdentityUser> roleManager, ILogger <AccountController> logger) : base("Accounts", "accounts") { _userManager = userManager; _signInManager = signInManager; _contextService = contextService; _sesService = sesService; _clanAndPeopleService = clanAndPeopleService; _roleManager = roleManager; _logger = logger; }
public void DemoContent_RenderingContextItemInitialized_ShouldReturnDemoContentView(Db db, IContactProfileProvider contact, IProfileProvider profile, ITracker tracker) { //arrange var itemID = ID.NewID; db.Add(new DbItem("ctx", itemID, Templates.DemoContent.ID)); var controller = new DemoController(contact, profile); var context = new RenderingContext(); context.ContextItem = db.GetItem(itemID); ContextService.Get().Push(context); using (new TrackerSwitcher(tracker)) { controller.DemoContent().As <ViewResult>().Model.Should().BeOfType <DemoContent>(); } }
public ActionResult KillStatAjax(string channel) { ViewBag.channel = channel; var killStats = new KillStat(); try { var user = ContextService.GetUserFromChannelname(channel); var bcs = ContextService.GetBotChannelSettings(user); return(Json(new { kills = bcs.KillStats.Kills, deaths = bcs.KillStats.Deaths, squad = bcs.KillStats.SquadKills }, JsonRequestBehavior.AllowGet)); } catch (Exception e) { ViewBag.Error = e.Message; return(Json(new { kills = killStats.Kills, deaths = killStats.Deaths, squad = killStats.SquadKills }, JsonRequestBehavior.AllowGet)); } }
/// <summary> /// main addin entry method /// </summary> /// <param name="Application"></param> /// <param name="ConnectMode"></param> /// <param name="AddInInst"></param> /// <param name="custom"></param> public void OnConnection(object Application, ext_ConnectMode ConnectMode, object AddInInst, ref Array custom) { try { /* Microsoft.SqlServer.Management.UI.VSIntegration.ServiceCache * is from SqlPackageBase.dll and not from Microsoft.SqlServer.SqlTools.VSIntegration.dll * the code below just throws null exception if you have wrong reference */ objExplorerService = (ObjectExplorerService)ServiceCache.ServiceProvider.GetService(typeof(IObjectExplorerService)); cs = (ContextService)objExplorerService.Container.Components[0]; cs.ObjectExplorerContext.CurrentContextChanged += new NodesChangedEventHandler(ObjectExplorerContext_CurrentContextChanged); } catch (Exception ex) { debug_message("OnConnection::ERROR " + ex.Message); } }
public List <GeopoliticalStructure> GetEstructuraGeopolitica(int?geopoliticalStructureTypeId = null, int?parentGeopoliticalStructureId = null, int?geopoliticalStructureId = null) { try { List <GeopoliticalStructure> returnList = new List <GeopoliticalStructure>(); if (System.Web.HttpContext.Current != null) { Rp3.Security.Cryptography.KeyFileName = System.Web.HttpContext.Current.Server.MapPath("~/key"); } else { Rp3.Security.Cryptography.KeyFileName = Path.Combine(Path.GetDirectoryName(System.Reflection.Assembly.GetAssembly(typeof(General)).Location), "Key"); } ContextService db = new ContextService(); var list = db.GeopoliticalStructures.Get(p => (geopoliticalStructureId == null || p.GeopoliticalStructureId == geopoliticalStructureId) && (parentGeopoliticalStructureId == null || p.ParentGeopoliticalStructureId == parentGeopoliticalStructureId) && (geopoliticalStructureTypeId == null || p.GeopoliticalStructureTypeId == geopoliticalStructureTypeId)); foreach (var item in list) { GeopoliticalStructure det = new GeopoliticalStructure(); Rp3.Data.Service.CopyTo(item, det, includeProperties: new string[] { "GeopoliticalStructureId", "GeopoliticalStructureTypeId", "IsoCode", "Name", "Latitude", "Longitude", "ParentGeopoliticalStructureId" }); returnList.Add(det); } return(returnList); } catch (Exception e) { return(null); } }
public SysCredDeleteCommands() { IsCommand("sys-cred-delete", "Delete system credential"); HasOption("i|id=", "Enter GUID of credential to delete", arg => { _credID = Guid.Parse(arg); }); _conf = (IConfiguration) new ConfigurationBuilder() .AddJsonFile("clisettings.json", optional: false, reloadOnChange: true) .Build(); var instance = new ContextService(InstanceContext.DeployedOrLocal); _uow = new UnitOfWork(_conf["Databases:AuroraEntities"], instance); }
public void LatestNews_ShouldReturnViewResult(Db db, string itemName, ID itemId, INewsRepositoryFactory factory) { //Arrange var controller = new NewsController(factory); db.Add(new DbItem(itemName, itemId, Templates.NewsFolder.ID)); var contextItem = db.GetItem(itemId); var context = new RenderingContext(); context.Rendering = new Rendering(); context.Rendering.Item = contextItem; ContextService.Get().Push(context); //Act var list = controller.LatestNews(); //Assert list.Should().BeOfType <ViewResult>(); }
public void DatasourceString_IdAsDatasource_IDSetAsLocationRoot([Content] Item renderingItem, [Greedy] QueryableDatasourceRenderingModel renderingModel) { //arrange ContextService.Get().Push(new PageContext()); PageContext.Current.Item = renderingItem; var dataSource = ID.NewID.ToString(); //act renderingModel.Initialize(new Rendering { DataSource = dataSource, RenderingItem = new RenderingItem(renderingItem) }); //assert renderingModel.DatasourceString.Should().Be("+location:" + dataSource); }
public void AddUniqueFormId_CurrentRenderingNotNull_ShouldReturnHiddenInput(HtmlHelper helper) { var id = Guid.NewGuid(); ContextService.Get().Push(new RenderingContext() { Rendering = new Rendering() { UniqueId = id } }); helper.Sitecore().CurrentRendering.Should().NotBeNull(); var xml = XDocument.Parse(helper.AddUniqueFormId().ToString()); xml.Root.Name.LocalName.Should().Be("input"); xml.Root.GetAttributeValue("name").Should().Be("uid"); Guid.Parse(xml.Root.GetAttributeValue("value")).Should().Be(id); }
public ActionResult KillStat(string channel, bool?dark = false) { ViewBag.channel = channel; ViewBag.DarkCss = dark; var killStats = new KillStat(); try { var user = ContextService.GetUserFromChannelname(channel); var bcs = ContextService.GetBotChannelSettings(user); return(View(bcs.KillStats)); } catch (Exception e) { ViewBag.Error = e.Message; return(View(killStats)); } }
public override void Render(TextWriter writer) { var current = ContextService.Get().GetCurrent <ViewContext>(); var currentWriter = current.Writer; try { current.Writer = writer; // in itemvisualization.getrenderings, the context is swithed to shell#lang cookie??? // so if you're logged in into sitecore cms, you'll get the renderings in an incorrect language! HttpContext.Current.Request.Cookies.Remove("shell#lang"); new SitecorePlaceholder(Rendering.RenderingItem).RenderView(current, Rendering); } finally { current.Writer = currentWriter; } }
public static void NotificacionOportunidadesAtrasadas(ContextService db) { var oportunidades = db.Oportunidades.Get(p => p.Estado == Rp3.AgendaComercial.Models.Constantes.EstadoOportunidad.Abierta).ToList(); foreach (Oportunidad opt in oportunidades) { var etapa = opt.OportunidadEtapas.FirstOrDefault(p => p.IdEtapa == opt.IdEtapa); if (etapa.Etapa.Dias != 0 && etapa.Etapa.Dias != null) { var dias = (etapa.FechaInicio.Value - DateTime.Now).TotalDays; dias = dias * -1; if (dias > etapa.Etapa.Dias) { db.Oportunidades.NotificaciónAtrasada(opt.IdOportunidad); } } } }
public ActionResult Empresa(string database, EmpresaModel model) { ViewBag.database = database; if (ModelState.IsValid) { var context = new ContextService(); context.BaseDatos = database; using (var service = new StartupService(context, database)) { try { if (model != null) { var nModel = Helper.fModel.GetModel <EmpresaModel>(context, service.Db); model.Paises = nModel.Paises; model.PlanesGenerales = nModel.PlanesGenerales; var aux = Helper.fModel.GetModel <EmpresaModel>(context, service.Db); model.PlanesGenerales = aux.PlanesGenerales; model.Paises = aux.Paises; model.LstTarifasVentas = aux.LstTarifasVentas; model.LstTarifasCompras = aux.LstTarifasCompras; service.CreateEmpresa(model); using (var loginService = new LoginService()) { HttpCookie securityCookie; FormsAuthentication.SignOut(); loginService.Forzardesconexion(database, ApplicationHelper.UsuariosAdministrador); loginService.SetEmpresaUserAdmin(_dominio, database, model.Id, string.Empty, string.Empty, Guid.NewGuid(), out securityCookie); Response.Cookies.Add(securityCookie); } } return(RedirectToAction("Index", "Home")); } catch (Exception ex) { ModelState.AddModelError("", ex.Message); } } } return(View(model)); }
/* * Handle external messages ****************************************************************/ private async void OnDetailsMessage(RoleDetailsViewModel sender, string message, RoleModel changed) { var current = Item; if (current != null) { if (changed != null && changed.RoleId == current?.RoleId) { switch (message) { case "ItemChanged": await ContextService.RunAsync(async() => { try { var item = await RoleService.GetRoleAsync(current.RoleId); item = item ?? new RoleModel { RoleId = current.RoleId, IsEmpty = true }; current.Merge(item); current.NotifyChanges(); NotifyPropertyChanged(nameof(Title)); if (IsEditMode) { StatusMessage("WARNING: This Role has been modified externally"); } } catch (Exception ex) { LogException("Role", "Handle Changes", ex); } }); break; case "ItemDeleted": await OnItemDeletedExternally(); break; } } } }
public UserShowCommand() { _conf = (IConfiguration) new ConfigurationBuilder() .AddJsonFile("clisettings.json", optional: false, reloadOnChange: true) .Build(); _map = new MapperConfiguration(x => x.AddProfile <AutoMapperProfile_EF6>()) .CreateMapper(); var env = new ContextService(InstanceContext.DeployedOrLocal); _uow = new UnitOfWork(_conf["Databases:IdentityEntities_EF6"], env); _service = new AdminService(_conf) { Grant = new ResourceOwnerGrantV2(_conf) }; IsCommand("user-show", "Show user"); HasRequiredOption("u|user="******"Enter existing user", arg => { if (string.IsNullOrEmpty(arg)) { throw new ConsoleHelpAsException($" *** No user given ***"); } _user = _uow.Users.Get(QueryExpressionFactory.GetQueryExpression <E_User>() .Where(x => x.UserName == arg).ToLambda(), new List <Expression <Func <E_User, object> > >() { x => x.UserClaims, x => x.UserLogins, x => x.UserRoles, }) .SingleOrDefault(); if (_user == null) { throw new ConsoleHelpAsException($" *** No user '{arg}' ***"); } }); }