/// <summary> /// Obtiene todos los pedidos de la base de datos /// </summary> /// <param name="tk">Código del tique de autorización (Véase "Login")</param> /// <returns></returns> public virtual IEnumerable<Pedido> Get(string tk) { using (PortalProContext ctx = new PortalProContext()) { if (CntWebApiSeguridad.CheckTicket(tk, ctx)) { IEnumerable<Pedido> pedidos = (from f in ctx.Pedidos orderby f.FechaAlta descending select f).ToList<Pedido>(); // fetch estrategy, necesaria para poder devolver el grupo junto con cada usuariuo FetchStrategy fs = new FetchStrategy(); fs.LoadWith<Pedido>(x => x.Proveedor); fs.LoadWith<Pedido>(x => x.DocumentoPdf); fs.LoadWith<Pedido>(x => x.DocumentoXml); fs.LoadWith<Pedido>(x => x.Empresa); fs.LoadWith<Pedido>(x => x.Responsable); pedidos = ctx.CreateDetachedCopy<IEnumerable<Pedido>>(pedidos, fs); return pedidos; } else { throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "Se necesita tique de autorización (Pedido)")); } } }
public virtual IEnumerable<CabFactura> Get(string proveedorId, string tk) { using (PortalProContext ctx = new PortalProContext()) { if (CntWebApiSeguridad.CheckTicket(tk, ctx)) { int pId = int.Parse(proveedorId); IEnumerable<CabFactura> facturas = (from f in ctx.CabFacturas where f.Proveedor.ProveedorId == pId orderby f.FechaEmision descending select f).ToList<CabFactura>(); // fetch estrategy, necesaria para poder devolver el grupo junto con cada usuariuo FetchStrategy fs = new FetchStrategy(); fs.LoadWith<CabFactura>(x => x.Proveedor); fs.LoadWith<CabFactura>(x => x.DocumentoPdf); fs.LoadWith<CabFactura>(x => x.DocumentoXml); fs.LoadWith<CabFactura>(x => x.Empresa); fs.LoadWith<CabFactura>(x => x.Responsable); facturas = ctx.CreateDetachedCopy<IEnumerable<CabFactura>>(facturas, fs); return facturas; } else { throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "Se necesita tique de autorización (CabFactura)")); } } }
public SingleChallengeWithTrackAndCategory(int challengeId) { this.challengeId = challengeId; FetchStrategy .Include(p => p.MissionTrack) .Include(p => p.Category); }
/// <summary> /// Obtiene todos las solicitudes de la base de datos /// </summary> /// <param name="tk">Código del tique de autorización (Véase "Login")</param> /// <returns></returns> public virtual IEnumerable<SolicitudProveedor> Get(string tk) { using (PortalProContext ctx = new PortalProContext()) { if (CntWebApiSeguridad.CheckTicket(tk, ctx)) { IEnumerable<SolicitudProveedor> solProveedores = (from pr in ctx.SolicitudProveedors select pr).ToList<SolicitudProveedor>(); // fetch estrategy, necesaria para poder devolver el grupo junto con cada usuariuo FetchStrategy fs = new FetchStrategy(); fs.LoadWith<SolicitudProveedor>(x => x.GrupoProveedor); fs.LoadWith<SolicitudProveedor>(x => x.SolicitudStatus); fs.LoadWith<SolicitudProveedor>(x => x.ActividadPrincipal1); fs.LoadWith<SolicitudProveedor>(x => x.Pais1); fs.LoadWith<SolicitudProveedor>(x => x.Comunidad1); fs.LoadWith<SolicitudProveedor>(x => x.Provincia1); solProveedores = ctx.CreateDetachedCopy<IEnumerable<SolicitudProveedor>>(solProveedores, fs); return solProveedores; } else { throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "Se necesita tique de autorización (Solicitudes proveedores)")); } } }
// POST api/users public virtual HttpResponseMessage Post(User user) { if (user == null) { return Request.CreateResponse(HttpStatusCode.BadRequest); } else { using (AriUMContext ctx = new AriUMContext("AriUMDBConnection")) { if (user.UserGroup != null) { int id2 = user.UserGroup.UserGroupId; user.UserGroup = CntWebApiVerbs.GetUserGroup(id2, ctx); } User u = CntWebApiVerbs.PostUser(user, ctx); FetchStrategy fs = new FetchStrategy(); fs.LoadWith<User>(x => x.UserGroup); User ud = ctx.CreateDetachedCopy<User>(u, fs); var response = Request.CreateResponse<User>(HttpStatusCode.Created, ud); response.Headers.Location = GetUserGroupLocation(ud.UserId); return response; } } }
public MissionLevelProgress(int missionId) { this.missionId = missionId; FetchStrategy.Include(p => p.MissionLevels); FetchStrategy.Include(p => p.MissionLevels.Select(q => q.Tracks.Select(r => r.Badge))); FetchStrategy.Include(p => p.MissionLevels.Select(q => q.Tracks.Select(r => r.Challenges.Select(s => s.Category)))); }
/// <summary> /// Devuelve las líneas que corresponden a una factura determinada /// </summary> /// <param name="idFac">Identificador de la factura a la que pertencen las líneas</param> /// <param name="tk">Código del tique de autorización (Véase "Login")</param> /// <returns></returns> public virtual IEnumerable<LinFactura> GetLineas(int idFac, string tk) { using (PortalProContext ctx = new PortalProContext()) { if (CntWebApiSeguridad.CheckTicket(tk, ctx)) { // comprobamos si existe la fcatura de referencia. CabFactura factura = (from f in ctx.CabFacturas where f.CabFacturaId == idFac select f).FirstOrDefault<CabFactura>(); if (factura != null) { IEnumerable<LinFactura> lineas = factura.LinFacturas; FetchStrategy fs = new FetchStrategy(); fs.LoadWith<LinFactura>(x => x.CabFactura); lineas = ctx.CreateDetachedCopy<IEnumerable<LinFactura>>(lineas, fs); return lineas; } else { throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.NotFound, "No hay un factura con el id proporcionado (LinFactura)")); } } else { throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "Se necesita tique de autorización (LinFactura)")); } } }
public DataContext(bool defaultFetchStrategy = false) : base(ConnectionStringName, BackendConfiguration, MetadataContainer) { if (defaultFetchStrategy) { return; } FetchStrategy = new FetchStrategy { MaxFetchDepth = 1 }; }
// GET api/usergroups /// <summary> /// Get all user groups from the server /// </summary> /// <returns>A list of all user groups</returns> public HttpResponseMessage Get() { using (AriUMContext ctx = new AriUMContext("AriUMDBConnection")) { IEnumerable<UserGroup> userGroups = CntWebApiVerbs.GetUserGroups(ctx); FetchStrategy fs = new FetchStrategy(); IEnumerable<UserGroup> uGs = ctx.CreateDetachedCopy<IEnumerable<UserGroup>>(userGroups, fs); return Request.CreateResponse<IEnumerable<UserGroup>>(HttpStatusCode.OK, uGs); } }
// GET api/users public IEnumerable<User> Get() { using (AriUMContext ctx = new AriUMContext("AriUMDBConnection")) { IEnumerable<User> user = CntWebApiVerbs.GetUsers(ctx); FetchStrategy fs = new FetchStrategy(); fs.LoadWith<User>(x => x.UserGroup); IEnumerable<User> uS = ctx.CreateDetachedCopy<IEnumerable<User>>(user, fs); return uS; } }
// GET api/invoiceLines public IEnumerable<InvoiceLine> Get() { using (AriUMContext ctx = new AriUMContext("AriUMDBConnection")) { IEnumerable<InvoiceLine> invoiceLine = CntWebApiVerbs.GetInvoiceLines(ctx); FetchStrategy fs = new FetchStrategy(); fs.LoadWith<InvoiceLine>(x => x.Product, x => x.Invoice); IEnumerable<InvoiceLine> iS = ctx.CreateDetachedCopy<IEnumerable<InvoiceLine>>(invoiceLine, fs); return iS; } }
public DataContext(bool defaultFetchStrategy = false) : base(ConnectionStringName, BackendConfiguration, MetadataContainer) { if (defaultFetchStrategy) { return; } FetchStrategy = new FetchStrategy { MaxFetchDepth = 1 }; }
public static TQuery With <TQuery>(this TQuery query, FetchStrategy fetchStrategy) where TQuery : EntityQuery { if (query.QueryOptions.FetchStrategy == fetchStrategy) { return(query); } TQuery newQuery = (TQuery)query.Clone(); newQuery.QueryOptions.FetchStrategy = fetchStrategy; return(newQuery); }
// GET api/products public IEnumerable<Invoice> Get() { using (AriUMContext ctx = new AriUMContext("AriUMDBConnection")) { IEnumerable<Invoice> invoices = CntWebApiVerbs.GetInvoices(ctx); FetchStrategy fs = new FetchStrategy(); fs.LoadWith<Invoice>(x => x.Customer); IEnumerable<Invoice> cS = ctx.CreateDetachedCopy<IEnumerable<Invoice>>(invoices, fs); return cS; } }
public static void SynchronizePageTypes() { using (var context = new DataContext()) { var fetchStrategy = new FetchStrategy { MaxFetchDepth = 1 }; fetchStrategy.LoadWith <PageTypeEntity>(pt => pt.Properties); fetchStrategy.LoadWith <PropertyEntity>(p => p.PropertyType); context.FetchStrategy = fetchStrategy; var pageTypeEntities = context.PageTypes.ToList(); var pageTypes = new List <PageType>(); var typesWithAttribute = AttributeReader.GetTypesWithAttribute(typeof(PageTypeAttribute)).ToList(); foreach (var type in typesWithAttribute) { var attribute = AttributeReader.GetAttribute <PageTypeAttribute>(type); var pageTypeEntity = pageTypeEntities.SingleOrDefault(pt => pt.Name == attribute.Name); if (pageTypeEntity == null) { pageTypeEntity = new PageTypeEntity(); pageTypeEntities.Add(pageTypeEntity); } pageTypeEntity.DefaultChildSortDirection = attribute.DefaultChildSortDirection; pageTypeEntity.DefaultChildSortOrder = attribute.DefaultChildSortOrder; pageTypeEntity.DisplayName = attribute.DisplayName; pageTypeEntity.Name = attribute.Name; pageTypeEntity.PageTemplate = attribute.PageTemplate; pageTypeEntity.PageTypeDescription = attribute.PageTypeDescription; if (pageTypeEntity.PageTypeId == 0) { context.Add(pageTypeEntity); } context.SaveChanges(); var pageType = Mapper.Map <PageTypeEntity, PageType>(pageTypeEntity); pageType.Type = type; pageType.AllowedTypes = attribute.AllowedTypes; pageType.PreviewImage = attribute.PreviewImage; pageType.Instance = (CmsPage)Activator.CreateInstance(type); pageTypes.Add(pageType); SynchronizeProperties(context, pageType, type, pageTypeEntity.Properties); } PageType.PageTypes = pageTypes; } }
public IEnumerable<InvoiceLine> GetLinesFromInvoice(int InvoiceId) { using (AriUMContext ctx = new AriUMContext("AriUMDBConnection")) { IEnumerable<InvoiceLine> invoiceLine = (from il in ctx.InvoiceLines where il.Invoice.InvoiceId == InvoiceId select il).ToList<InvoiceLine>(); FetchStrategy fs = new FetchStrategy(); fs.LoadWith<InvoiceLine>(x => x.Product, x => x.Invoice); IEnumerable<InvoiceLine> iS = ctx.CreateDetachedCopy<IEnumerable<InvoiceLine>>(invoiceLine, fs); return iS; } }
public static void SynchronizePageTypes() { using (var context = new DataContext()) { var fetchStrategy = new FetchStrategy {MaxFetchDepth = 1}; fetchStrategy.LoadWith<PageTypeEntity>(pt => pt.Properties); fetchStrategy.LoadWith<PropertyEntity>(p => p.PropertyType); context.FetchStrategy = fetchStrategy; var pageTypeEntities = context.PageTypes.ToList(); var pageTypes = new List<PageType>(); var typesWithAttribute = AttributeReader.GetTypesWithAttribute(typeof(PageTypeAttribute)).ToList(); foreach (var type in typesWithAttribute) { var attribute = AttributeReader.GetAttribute<PageTypeAttribute>(type); var pageTypeEntity = pageTypeEntities.SingleOrDefault(pt => pt.Name == attribute.Name); if (pageTypeEntity == null) { pageTypeEntity = new PageTypeEntity(); pageTypeEntities.Add(pageTypeEntity); } pageTypeEntity.DefaultChildSortDirection = attribute.DefaultChildSortDirection; pageTypeEntity.DefaultChildSortOrder = attribute.DefaultChildSortOrder; pageTypeEntity.DisplayName = attribute.DisplayName; pageTypeEntity.Name = attribute.Name; pageTypeEntity.PageTemplate = attribute.PageTemplate; pageTypeEntity.PageTypeDescription = attribute.PageTypeDescription; if (pageTypeEntity.PageTypeId == 0) { context.Add(pageTypeEntity); } context.SaveChanges(); var pageType = Mapper.Map<PageTypeEntity, PageType>(pageTypeEntity); pageType.Type = type; pageType.AllowedTypes = attribute.AllowedTypes; pageType.PreviewImage = attribute.PreviewImage; pageType.Instance = (CmsPage)Activator.CreateInstance(type); pageTypes.Add(pageType); SynchronizeProperties(context, pageType, type, pageTypeEntity.Properties); } PageType.PageTypes = pageTypes; } }
/// <summary> /// Get an individual user group /// </summary> /// <param name="id">User groups' id you want</param> /// <returns>Use group object (XML/JSON)</returns> public virtual UserGroup Get(int id) { using (AriUMContext ctx = new AriUMContext("AriUMDBConnection")) { UserGroup userGroup = CntWebApiVerbs.GetUserGroup(id, ctx); if (userGroup == null) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.NotFound)); } else { FetchStrategy fs = new FetchStrategy(); UserGroup uG = ctx.CreateDetachedCopy<UserGroup>(userGroup, fs); return uG; } } }
// GET api/invoiceLines/5 public virtual InvoiceLine Get(int id) { using (AriUMContext ctx = new AriUMContext("AriUMDBConnection")) { InvoiceLine invoiceLine = CntWebApiVerbs.GetInvoiceLine(id, ctx); if (invoiceLine == null) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.NotFound)); } else { FetchStrategy fs = new FetchStrategy(); fs.LoadWith<InvoiceLine>(x => x.Product, x => x.Invoice); InvoiceLine il = ctx.CreateDetachedCopy<InvoiceLine>(invoiceLine, fs); return il; } } }
/// <summary> /// Se obtienen todos los documentos pertenecientes a un proveedor. /// Los documentos se copian al directorio de descarga y se proporciona su enlace en la propiedad "DescargaUrl" /// </summary> /// <param name="tk">Tique de autorización</param> /// <param name="codigoProveedor">Código del proveedor del que se solcitan los documentos.</param> /// <returns></returns> public virtual IEnumerable<Documento> GetFromProveedor(string tk, string codigoProveedor) { using (PortalProContext ctx = new PortalProContext()) { if (CntWebApiSeguridad.CheckTicket(tk, ctx)) { // comprobamos que el proveedor pasado existe int id = 0; bool res = int.TryParse(codigoProveedor, out id); Proveedor proveedor = (from p in ctx.Proveedors where p.ProveedorId == id select p).FirstOrDefault<Proveedor>(); if (proveedor == null) { throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "Debe proporcionar un proveedor existente [GetFromProveedor]")); } IEnumerable<Documento> documentos = (from d in ctx.Documentos where d.Proveedor.ProveedorId == id select d).ToList<Documento>(); // por cada documento hay que copiarlo al directorio de descarga // y proporcionar el enlace foreach (Documento doc in documentos) { string root = System.Web.HttpContext.Current.Server.MapPath("~/downloads"); string resultado = PortalProWebUtility.ObtenerUrlDeDocumento(root, tk, doc, ctx); if (resultado != "") { throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, resultado)); } } // fetch estrategy, necesaria para poder devolver el grupo junto con cada usuariuo FetchStrategy fs = new FetchStrategy(); fs.LoadWith<Documento>(x => x.Proveedor); fs.LoadWith<Documento>(x => x.TipoDocumento); documentos = ctx.CreateDetachedCopy<IEnumerable<Documento>>(documentos, fs); return documentos; } else { throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "Se necesita tique de autorización (Documentos)")); } } }
/// <summary> /// Obtiene todos los Responsables de la base de datos /// </summary> /// <param name="tk">Código del tique de autorización (Véase "Login")</param> /// <returns></returns> public virtual IEnumerable<Responsable> Get(string tk) { using (PortalProContext ctx = new PortalProContext()) { if (CntWebApiSeguridad.CheckTicket(tk, ctx) || tk=="solicitud") { IEnumerable<Responsable> responsables = (from gu in ctx.Responsables select gu).ToList<Responsable>(); FetchStrategy fs = new FetchStrategy(); fs.LoadWith<Responsable>(x => x.Usuario); responsables = ctx.CreateDetachedCopy<IEnumerable<Responsable>>(responsables,fs); return responsables; } else { throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "Se necesita tique de autorización (Responsables)")); } } }
/// <summary> /// Fetches the individual element /// </summary> /// <param name="key">The key of the element to fetch.</param> /// <returns>The fetched element, or null if not found</returns> public override Telerik.Bencher.Model.SalesOrderHeader FetchIndividual(int key) { Telerik.Bencher.Model.SalesOrderHeader toReturn = null; try { using (var dbFactory = new Telerik.Bencher.Model.DomainModel(ConnectionStringToUse)) { FetchStrategy fetchStrategy = new FetchStrategy(); fetchStrategy.LoadWith <Telerik.Bencher.Model.SalesOrderHeader>(c => c.CreditCard); dbFactory.FetchStrategy = fetchStrategy; toReturn = dbFactory.SalesOrderHeaders.First <Telerik.Bencher.Model.SalesOrderHeader>(p => p.SalesOrderID == key); } } catch (TypeInitializationException ex) { throw new Exception("Error initializing context. See README.txt in Telerik.Bencher.Model project", ex); } return(toReturn); }
protected void Page_Load(object sender, EventArgs e) { if (!TeamScheduleID.HasValue) { return; } lnkEdit.NavigateUrl = string.Format(lnkEdit.NavigateUrl, TeamScheduleID.Value); using (TeamSchedulesController tsc = new TeamSchedulesController()) { FetchStrategy fetch = new FetchStrategy() { MaxFetchDepth = 6 }; fetch.LoadWith<TeamSchedule>(i => i.Team); fetch.LoadWith<Team>(i => i.TeamPlayers); fetch.LoadWith<TeamPlayer>(i => i.Player); fetch.LoadWith<Player>(i => i.Person); fetch.LoadWith<TeamSchedule>(i => i.Attendances); fetch.LoadWith<TeamPlayer>(i => i.PlayerPass); fetch.LoadWith<PlayerPass>(i => i.Player); TeamSchedule schedule = tsc.GetWhere(i => i.TeamScheduleID == TeamScheduleID.Value, fetch).First(); EventName = schedule.EventName; TeamName = schedule.Team.TeamName; Starts = schedule.StartDate; Ends = schedule.EndDate; var knownAttendances = schedule.Attendances.ToList(); var data = schedule.Team.TeamPlayers.Select(i => new PlayerAttendance() { FirstName = i.PlayerID.HasValue ? i.Player.Person.FName : i.PlayerPass.Player.Person.FName, LastName = i.PlayerID.HasValue ? i.Player.Person.LName : i.PlayerPass.Player.Person.LName, Present = knownAttendances.Where(j => j.PlayerID == i.PlayerID).Count() > 0, PlayerID = i.PlayerID.HasValue ? i.PlayerID.Value : i.PlayerPass.PlayerID }); rptPlayer.DataSource = data; rptPlayer.DataBind(); } }
/// <summary> /// Obtiene todos los usuarios ligados a proveedores de la base de datos /// </summary> /// <param name="tk">Código del tique de autorización (Véase "Login")</param> /// <returns></returns> public virtual IEnumerable<UsuarioProveedor> Get(string tk) { using (PortalProContext ctx = new PortalProContext()) { if (CntWebApiSeguridad.CheckTicket(tk, ctx)) { IEnumerable<UsuarioProveedor> UsuarioProveedor = (from up in ctx.UsuarioProveedors select up).ToList<UsuarioProveedor>(); // fetch estrategy, necesaria para poder devolver el grupo junto con cada usuariuo FetchStrategy fs = new FetchStrategy(); fs.LoadWith<UsuarioProveedor>(x => x.Proveedor); UsuarioProveedor = ctx.CreateDetachedCopy<IEnumerable<UsuarioProveedor>>(UsuarioProveedor, fs); return UsuarioProveedor; } else { throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "Se necesita tique de autorización (UsuarioProveedor)")); } } }
private void Populate(int teamScheduleID) { using (TeamSchedulesController tsc = new TeamSchedulesController()) { FetchStrategy fetch = new FetchStrategy(); fetch.LoadWith<TeamSchedule>(i => i.Team); TeamSchedule teamSchedule = tsc.GetWhere(i => i.TeamScheduleID == TeamScheduleID.Value, fetch).First(); txtStartDate.Text = teamSchedule.StartDate.ToLocalTime().ToString("yyyy-MM-ddTHH:mm"); txtEndDate.Text = teamSchedule.EndDate.ToLocalTime().ToString("yyyy-MM-ddTHH:mm"); txtRSVPBy.Text = teamSchedule.RSVPBy.HasValue ? teamSchedule.RSVPBy.Value.ToLocalTime().ToString("yyyy-MM-ddTHH:mm") : null; txtEventName.Text = teamSchedule.EventName; chkEnableRSVP.Checked = teamSchedule.RSVPBy.HasValue; chkEnableRSVP_CheckedChanged(null, null); // set program/team ptpPicker.SelectedProgramID = teamSchedule.Team.ProgramID; ptpPicker.SelectedTeamID = teamSchedule.TeamID; ptpPicker.Populate(); } }
/// <summary> /// Obtiene todos los documentos de la base de datos. Lo que se devuelven los objetos tal cual /// sin haber sido copiados a su directorio de descarga y sin haber propocionado el enlace para hacerla /// </summary> /// <param name="tk">Código del tique de autorización (Véase "Login")</param> /// <returns></returns> public virtual IEnumerable<Documento> Get(string tk) { using (PortalProContext ctx = new PortalProContext()) { if (CntWebApiSeguridad.CheckTicket(tk, ctx) || tk == "solicitud") { IEnumerable<Documento> documentos = (from gu in ctx.Documentos select gu).ToList<Documento>(); // fetch estrategy, necesaria para poder devolver el grupo junto con cada usuariuo FetchStrategy fs = new FetchStrategy(); fs.LoadWith<Documento>(x => x.Proveedor); fs.LoadWith<Documento>(x => x.TipoDocumento); documentos = ctx.CreateDetachedCopy<IEnumerable<Documento>>(documentos, fs); return documentos; } else { throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "Se necesita tique de autorización (Documentos)")); } } }
private static void LinqWithFetchStrategy(EntitiesModel context) { Console.WriteLine("With fetch optimization:"); FetchStrategy strategy = new FetchStrategy(); strategy.LoadWith<Car>(c => c.Category); strategy.LoadWith<Category>(cat => cat.RentalRates); // set the strategy to the context context.FetchStrategy = strategy; var query2 = context.Cars//.Include(c => c.Category) //.Include(c => c.Category.RentalRates.Select(r=>r.SubRates)) .Where(c => c.CarYear < 2000).ToList(); Console.WriteLine("Car\tCategory"); foreach (var car in query2) { Console.WriteLine("{0}\t{1}", car.CarID, car.Category.CategoryName); } // remove the strategy context.FetchStrategy = null; }
/// <summary> /// Fetches the complete set of elements and returns this set as an IEnumerable. /// </summary> /// <returns>the set fetched</returns> public override IEnumerable <Telerik.Bencher.Model.SalesOrderHeader> FetchSet() { List <Telerik.Bencher.Model.SalesOrderHeader> headers; try { using (var dbFactory = new Telerik.Bencher.Model.DomainModel(ConnectionStringToUse)) { dbFactory.ContextOptions.IsolationLevel = System.Data.IsolationLevel.ReadCommitted; FetchStrategy fetchStrategy = new FetchStrategy(); fetchStrategy.LoadWith <Telerik.Bencher.Model.SalesOrderHeader>(c => c.CreditCard); dbFactory.FetchStrategy = fetchStrategy; headers = dbFactory.SalesOrderHeaders.ToList <Telerik.Bencher.Model.SalesOrderHeader>(); } } catch (TypeInitializationException ex) { throw new Exception("Error initializing context. See README.txt in Telerik.Bencher.Model project", ex); } return(headers); }
/// <summary> /// Using FetchStrategy is the way in OpenAccess /// to perform Include(). /// </summary> private static void SelectEmployeesWithStrategy() { using (var context = new TelerikAcademyEntities()) { var strategy = new FetchStrategy(); strategy.LoadWith<Employee>(e => e.Department); strategy.LoadWith<Employee>(e => e.Address); strategy.LoadWith<Address>(a => a.Town); context.FetchStrategy = strategy; foreach (var employee in context.Employees) { Console.WriteLine( "Name: {0} {1}\nDepartment: {2}\nTown: {3}", employee.FirstName, employee.LastName, employee.Department.Name, employee.Address.Town.Name); } } }
/// <summary> /// Using FetchStrategy is the way in OpenAccess /// to perform Include(). /// </summary> private static void SelectEmployeesWithStrategy() { using (var context = new TelerikAcademyEntities()) { var strategy = new FetchStrategy(); strategy.LoadWith <Employee>(e => e.Department); strategy.LoadWith <Employee>(e => e.Address); strategy.LoadWith <Address>(a => a.Town); context.FetchStrategy = strategy; foreach (var employee in context.Employees) { Console.WriteLine( "Name: {0} {1}\nDepartment: {2}\nTown: {3}", employee.FirstName, employee.LastName, employee.Department.Name, employee.Address.Town.Name); } } }
/// <summary> /// Obtiene todos los log de solicitudes de la base de datos /// </summary> /// <param name="tk">Código del tique de autorización (Véase "Login")</param> /// <returns></returns> public virtual IEnumerable<SolicitudLog> Get(string tk) { using (PortalProContext ctx = new PortalProContext()) { if (CntWebApiSeguridad.CheckTicket(tk, ctx)) { IEnumerable<SolicitudLog> solog = (from gu in ctx.SolicitudLogs select gu).ToList<SolicitudLog>(); // fetch estrategy, necesaria para poder devolver el grupo junto con cada usuariuo FetchStrategy fs = new FetchStrategy(); fs.LoadWith<SolicitudLog>(x => x.Usuario); fs.LoadWith<SolicitudLog>(x => x.SolicitudProveedor); fs.LoadWith<SolicitudLog>(x => x.SolicitudStatusInicial); fs.LoadWith<SolicitudLog>(x => x.SolicitudStatusFinal); solog = ctx.CreateDetachedCopy<IEnumerable<SolicitudLog>>(solog, fs); return solog; } else { throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "Se necesita tique de autorización (SolicitudLogs)")); } } }
static void Main(string[] args) { Console.WriteLine("-- Program starts --"); KendoContext ctx = new KendoContext("KendomodelConnection"); Cliente c = ctx.Clientes.FirstOrDefault<Cliente>(); if (c.GrupoCliente != null) { Console.WriteLine("ID:{0} N:{1} GC:{2}", c.Id, c.Nombre, c.GrupoCliente.Nombre); //Console.ReadLine(); } else { Console.WriteLine("ID:{0} N:{1}", c.Id, c.Nombre); //Console.ReadLine(); } FetchStrategy fs = new FetchStrategy(); fs.LoadWith<Cliente>(x => x.GrupoCliente); Cliente c2 = ctx.CreateDetachedCopy<Cliente>(c,fs); Console.WriteLine("That's all folks"); Console.ReadLine(); }
public DefaultRelation(string attributeName, string relationshipName, Type sourceObjectType, Type relatedObjectType, RelationColumnMapping[] tableColumnMappings, ReferentialRuleType updateRule, ReferentialRuleType deleteRule, bool reverseRelationship, bool nonIdentifyingRelation, FetchStrategy fetchStrategy, bool nullable) : base(attributeName, relationshipName, sourceObjectType, relatedObjectType, tableColumnMappings, updateRule, deleteRule, reverseRelationship, nonIdentifyingRelation, fetchStrategy, nullable) { }
protected AbstractRelation(String attributeName, string relationshipName, Type sourceObjectType, Type relatedObjectType, RelationColumnMapping[] tableColumnMappings, ReferentialRuleType updateRule, ReferentialRuleType deleteRule, bool reverseRelationship, bool nonIdentifyingRelation, FetchStrategy fetchStrategy, bool nullable) { AttributeName = attributeName; RelationShipName = relationshipName; SourceObjectType = sourceObjectType; RelatedObjectType = relatedObjectType; TableColumnMappings = tableColumnMappings; UpdateRule = updateRule; DeleteRule = deleteRule; ReverseRelationship = reverseRelationship; NonIdentifyingRelation = nonIdentifyingRelation; FetchStrategy = fetchStrategy; Nullable = nullable; }
public SingleObservationWithChallengeAndUser(int observationId) { this.observationId = observationId; FetchStrategy.Include(p => p.Challenge); FetchStrategy.Include(p => p.User); }
public SingleUserWithBadges(string userId) { this.userId = userId; FetchStrategy.Include(p => p.Badges); }
private List<MyLink> GetPermissionedLinksFromDB() { using(UserManagement um = new UserManagement()) using (WebUsersController wuc = new WebUsersController()) using(LinksController lc = new LinksController()) { FetchStrategy fetch = new FetchStrategy(); fetch.LoadWith<Link>(i => i.LinkGroup); fetch.LoadWith<Link>(i => i.Glyphicon); fetch.LoadWith<LinkGroup>(i => i.Glyphicon); fetch.LoadWith<Link>(i => i.LinkPermissions); IEnumerable<ScopeAssignment> assignedScopes = um.ScopeAssignments.Where(i => i.UserID == CurrentUser.UserID); // if user has even one allowed permission, then we need to add it. need to do it by permission then by role var allowedByPermission = assignedScopes.Where(i => i.PermissionID.HasValue && !i.IsDeny).Select(i => i.PermissionID.Value); var allowedByRole = assignedScopes.Where(i => i.RoleID.HasValue && !i.IsDeny).Select(i => i.Role).SelectMany(i => i.Permissions).Select(i => i.PermissionID); List<int> allowed = allowedByPermission.Union(allowedByRole).Distinct().ToList(); // now get the links var links = lc.GetWhere(i => i.LinkPermissions.Count() == 0 || i.LinkPermissions.Where(j => !j.IsDeny && allowed.Contains(j.PermissionID)).Count() > 0, fetch); var noGroups = links.Where(i => !i.LinkGroupID.HasValue) .OrderBy(i => i.SortOrder) .Select(i => new MyLink() { IsGroup = false, Glyphicon = i.GlyphiconID.HasValue ? i.Glyphicon.Glyphicon1 : null, Name = i.LinkName, CurrentModulePattern = i.CurrentModulePattern, LinkURL = i.LinkURL, Tooltip = i.LinkTitle, ShowInMobileNav = i.ShowInMobileNav }).ToList(); var groups = links.Where(i => i.LinkGroupID.HasValue) .GroupBy(i => i.LinkGroupID) .OrderBy(i => i.First().LinkGroup.SortOrder) .Select(i => new MyLink() { IsGroup = true, Name = i.First().LinkGroup.LinkGroupName, Glyphicon = i.First().LinkGroup.GlyphiconID.HasValue ? i.First().LinkGroup.Glyphicon.Glyphicon1 : null, CurrentModulePattern = i.First().LinkGroup.CurrentModulePattern, Tooltip = i.First().LinkGroup.LinkGroupName, ShowInMobileNav = i.First().LinkGroup.ShowInMobileNav, MyLinks = i.OrderBy(j => j.SortOrder).Select(j => new MyLink() { Glyphicon = j.GlyphiconID.HasValue ? j.Glyphicon.Glyphicon1 : null, IsGroup = false, Name = j.LinkName, CurrentModulePattern = j.CurrentModulePattern, Tooltip = j.LinkTitle, LinkURL = j.LinkURL, ShowInMobileNav = j.ShowInMobileNav }).ToList() }).ToList(); List<MyLink> myLinks = new List<MyLink>(); myLinks.AddRange(noGroups); myLinks.AddRange(groups); return myLinks; } }
public virtual IEnumerable<Documento> GetDocumentos(int idPro, string userId, string tk) { using (PortalProContext ctx = new PortalProContext()) { if (CntWebApiSeguridad.CheckTicket(tk, ctx)) { Proveedor proveedor = (from p in ctx.Proveedors where p.ProveedorId == idPro select p).FirstOrDefault<Proveedor>(); if (proveedor != null) { IEnumerable<Documento> docs = (from d in ctx.Documentos where d.Proveedor.ProveedorId == idPro select d).ToList<Documento>(); // La aplicación ahora depende del comienzo del usuario string application = "PortalPro"; switch (userId.Substring(0, 1)) { case "U": application = "PortalPro2"; break; case "G": application = "PortalPro"; break; } foreach (Documento d in docs) { d.DescargaUrl = PortalProWebUtility.CargarUrlDocumento(application, d, tk); } FetchStrategy fs = new FetchStrategy(); fs.LoadWith<Documento>(x => x.TipoDocumento); IEnumerable<Documento> documentos = ctx.CreateDetachedCopy<IEnumerable<Documento>>(docs, fs); return documentos; } else { throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.NotFound, "No hay un proveedor con el id proporcionado (Proveedores)")); } } else { throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "Se necesita tique de autorización (Proveedores)")); } } }
public MissionProgressSummary() { FetchStrategy.Include(p => p.MissionLevels); FetchStrategy.Include(p => p.MissionLevels.Select(t => t.Tracks.Select(c => c.Challenges))); }
/// <summary> /// Gets the user group with a given name /// </summary> /// <param name="name">The name of the object</param> /// <returns>User group object</returns> public virtual UserGroup GetByName(string name) { using (AriUMContext ctx = new AriUMContext("AriUMDBConnection")) { UserGroup userGroup = (from ug in ctx.UserGroups where ug.Name == name select ug).FirstOrDefault<UserGroup>(); if (userGroup == null) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.NotFound)); } else { FetchStrategy fs = new FetchStrategy(); UserGroup uG = ctx.CreateDetachedCopy<UserGroup>(userGroup, fs); return uG; } } }
public virtual IEnumerable<Documento> GetDocumentos(int idPro, string userId, string tk) { using (PortalProContext ctx = new PortalProContext()) { if (CntWebApiSeguridad.CheckTicket(tk, ctx)) { Proveedor proveedor = (from p in ctx.Proveedors where p.ProveedorId == idPro select p).FirstOrDefault<Proveedor>(); if (proveedor != null) { IEnumerable<Documento> docs = (from d in ctx.Documentos where d.Proveedor.ProveedorId == idPro select d).ToList<Documento>(); FetchStrategy fs = new FetchStrategy(); fs.LoadWith<Documento>(x => x.TipoDocumento); IEnumerable<Documento> documentos = ctx.CreateDetachedCopy<IEnumerable<Documento>>(docs, fs); return documentos; } else { throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.NotFound, "No hay un proveedor con el id proporcionado (Proveedores)")); } } else { throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "Se necesita tique de autorización (Proveedores)")); } } }
/// <summary> /// Creates a new user group /// </summary> /// <param name="userGroup">The user group that yo want to create</param> /// <returns>Url related to the new object</returns> public virtual HttpResponseMessage Post(UserGroup userGroup) { if (userGroup == null) { return Request.CreateResponse(HttpStatusCode.BadRequest); } else { using (AriUMContext ctx = new AriUMContext("AriUMDBConnection")) { UserGroup uG = CntWebApiVerbs.PostUserGroup(userGroup, ctx); FetchStrategy fs = new FetchStrategy(); UserGroup uGd = ctx.CreateDetachedCopy<UserGroup>(uG, fs); var response = Request.CreateResponse<UserGroup>(HttpStatusCode.Created, uGd); response.Headers.Location = GetUserGroupLocation(uGd.UserGroupId); return response; } } }
/// <summary> /// Get all user groups ordered alphabetically /// </summary> /// <param name="order">Indicates what order you want , so far it orders by name only</param> /// <returns></returns> public IEnumerable<UserGroup> GetOrdered(string order) { using (AriUMContext ctx = new AriUMContext("AriUMDBConnection")) { IEnumerable<UserGroup> userGroups = (from ug in ctx.UserGroups orderby ug.Name select ug).ToList<UserGroup>(); FetchStrategy fs = new FetchStrategy(); IEnumerable<UserGroup> uGs = ctx.CreateDetachedCopy<IEnumerable<UserGroup>>(userGroups, fs); return uGs; } }
/// <summary> /// Returns a new QueryOptions based on this QueryOptions but with the specified FetchStrategy /// </summary> /// <param name="fetchStrategy"></param> /// <returns></returns> public QueryOptions With(FetchStrategy fetchStrategy) { return(new QueryOptions(fetchStrategy, this.MergeStrategy)); }
public QueryOptions(FetchStrategy fetchStrategy, MergeStrategy mergeStrategy) { FetchStrategy = fetchStrategy; MergeStrategy = mergeStrategy; }
public MissionTrackWithBadgeAndLevel() { FetchStrategy.Include(p => p.Badge); FetchStrategy.Include(p => p.MissionLevel); }
public SingleUserWithProfileInformation(string userId) { this.userId = userId; FetchStrategy.Include(p => p.Badges); FetchStrategy.Include(p => p.Observations); }
public SingleUserWithObservations(string userId) { requestedUserId = userId; FetchStrategy.Include(p => p.Observations.Select(q => q.Challenge)); }
public ObservationsForUserMission(string userId, int missionId) { this.userId = userId; this.missionId = missionId; FetchStrategy.Include(p => p.Challenge.MissionTrack); }