Search Results

Search found 720 results on 29 pages for 'tolist'.

Page 17/29 | < Previous Page | 13 14 15 16 17 18 19 20 21 22 23 24  | Next Page >

  • How to get a List ordered by the List it's filtered by?

    - by DaveDev
    I have a method as follows. It returns a list of MyTypes which appear to be ordered by myType.Id ascending by default. public List<MyType> GetMyTypes(List<int> ids) { return (from myType in db.MyTypes where ids.Contains(myType.Id) select new MyType { MyValue = myType.MyValue }).ToList(); } So if ids contains 302 300 301 the List returned contains items in ascending order. What do I need to do to return List<MyType> in the order of ids? Thanks edit: I've tried orderby ids.IndexOf(myType.Id) but it throws the exception Method 'Int32 IndexOf(Int32)' has no supported translation to SQL.

    Read the article

  • Why does my WCF service return and ARRAY instead of a List <T> ?

    - by user193189
    In the web servce I say public List<Customer> GetCustomers() { PR1Entities dc = new PR1Entities(); var q = (from x in dc.Customers select x).ToList(); return q; } (customer is a entity object) Then I generate the proxy when I add the service.. and in the reference.cd it say public wcf1.ServiceReference1.Customer[] GetCustomers() { return base.Channel.GetCustomers(); } WHY IS IT AN ARRAY? I asked for a List. help.

    Read the article

  • Get width of DataGridView Column When AutoGenerateColumns = true And It added dynomically?

    - by n H
    I want to get width of each column of DataGridView in codeBehinde after setting DataSource and before showing it to user: DataGridView dgv = new DataGridView(); dgv.AutoGenerateColumns = true; dgv.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells; dgv.AutoSize = true; dgv.DataSource = dc.Branches.ToList(); this.Controls.Add(dgv); //How to get Width of each Column Here?? var ColCount = dgv.Columns.Count; //return 0 ??

    Read the article

  • What is wrong with the below statement(C#3.0 / Lambda)

    - by Newbie
    what is wrong in the below Enumerable.Range(0, objEntityCode.Count - 1).Select(i => { options.Attributes[i] = new EntityCodeKey { EntityCode = objEntityCode[i].EntityCodes , OrganizationCode = Constants.ORGANIZATION_CODE }; }) .ToArray(); Throwing error The type arguments for method 'System.Linq.Enumerable.Select(System.Collections.Generic.IEnumerable, System.Func)' cannot be inferred from the usage. Try specifying the type arguments explicitly. But this works Enumerable.Range(0, objEntityCode.Count - 1).ToList().ForEach(i => { options.Attributes[i] = new EntityCodeKey { EntityCode = objEntityCode[i].EntityCodes , OrganizationCode = Constants.ORGANIZATION_CODE }; } ); Using C#3.0. Purpose: I am learning LINQ / LAMBDA and trying to do the same program in different way. Thanks.

    Read the article

  • Create MVC 5 Combo Box from CRM Entities?

    - by SpaceCowboy74
    I am working on an MVC 5 App that pulls data from Dynamics CRM 5. The Data I am getting back is an IQueryable of type Account (The CRM Entity class auto generated by CrmSvcUtil). I am retrieving all of the items and can loop through them with code like this: @foreach (var item in Model.ToList()) { <tr> <td> @item.AccountId </td> <td> @Html.DisplayFor(modelItem => item.Name) </td> </tr> } The problem is, I would like to instead put them in a drop down list. I can't figure out what the syntax is to put these in a DropDown is. Any suggestions?

    Read the article

  • How to get an item value of json using C#?

    - by user3487837
    How to get an item value of json using C#? json: [{ ID: '6512', fd: [{ titie: 'Graph-01', type: 'graph', views: { graph: { show: true, state: { group: 'DivisionName', series: ['FieldWeight', 'FactoryWeight', 'Variance'], graphType: 'lines-and-points' } } } }, { titie: 'Graph-02', type: 'Graph', views: { graph: { show: true, state: { group: 'DivisionName', series: ['FieldWeight', 'FactoryWeight', 'Variance'], graphType: 'lines-and-points' } } } }] }, { ID: '6506', fd: [{ titie: 'Map-01', type: 'map', views: { map: { show: true, state: { kpiField: 'P_BudgetAmount', kpiSlabs: [{ id: 'P_BudgetAmount', hues: ['#0fff03', '#eb0707'], scales: '10' }] } } } }] }] Above mentioned one is json, Here titie value will be get in a list please help me... my code is: string dashletsConfigPath = Url.Content("~/Content/Dashlets/Dashlets.json"); string jArray = System.IO.File.ReadAllText(Server.MapPath(dashletsConfigPath)) List<string> lists = new List<string>(); JArray list = JArray.Parse(jArray); var ll = list.Select(j => j["dashlets"]).ToList();

    Read the article

  • Can we avoid multiple if''s(C#3.0)

    - by Newbie
    I tried my level best to write an improved version but failed. inFiles.ToList().ForEach(i => { filePath = inFolder + "\\" + i.Value; if (i.Key.Equals(replacementFile)) { replacementCollection = GetReplacementDataFromFile(filePath); } else if (i.Key.Equals(standardizationFile)) { standardizationCollection = GetStandardizationDataFromFile(filePath); } }); The problem is that I cannot use a switch case over here because the comparison variables are not constant. Kindly help to improve this code. I am using C#(3.0). Thanks

    Read the article

  • problem with Expression not equal types

    - by user428547
    class first { private int? firstID; } class second { private int secondID; private int secondField; } public override Expression<Func<first, bool>> FirstFilter() { Contex db = new Contex(); List<second> list = (from p in db.second select p).ToList(); return b => list.Select(p => p.secondID).Contains(b.firstID); } and i have error: cannot convert from 'System.Collections.Generic.IEnumerable' to 'System.Collections.Generic.IEnumerable' i have tried many diferent ways, but i just don't know how can i fix it.

    Read the article

  • Dynamic Paging and Sorting

    - by Ricardo Peres
    Since .NET 3.5 brought us LINQ and expressions, I became a great fan of these technologies. There are times, however, when strong typing cannot be used - for example, when you are developing an ObjectDataSource and you need to do paging having just a column name, a page index and a page size, so I set out to fix this. Yes, I know about Dynamic LINQ, and even talked on it previously, but there's no need to add this extra assembly. So, without further delay, here's the code, in both generic and non-generic versions: public static IList ApplyPagingAndSorting(IEnumerable enumerable, Type elementType, Int32 pageSize, Int32 pageIndex, params String [] orderByColumns) { MethodInfo asQueryableMethod = typeof(Queryable).GetMethods(BindingFlags.Static | BindingFlags.Public).Where(m = (m.Name == "AsQueryable") && (m.ContainsGenericParameters == false)).Single(); IQueryable query = (enumerable is IQueryable) ? (enumerable as IQueryable) : asQueryableMethod.Invoke(null, new Object [] { enumerable }) as IQueryable; if ((orderByColumns != null) && (orderByColumns.Length 0)) { PropertyInfo orderByProperty = elementType.GetProperty(orderByColumns [ 0 ]); MemberExpression member = Expression.MakeMemberAccess(Expression.Parameter(elementType, "n"), orderByProperty); LambdaExpression orderBy = Expression.Lambda(member, member.Expression as ParameterExpression); MethodInfo orderByMethod = typeof(Queryable).GetMethods(BindingFlags.Public | BindingFlags.Static).Where(m = m.Name == "OrderBy").ToArray() [ 0 ].MakeGenericMethod(elementType, orderByProperty.PropertyType); query = orderByMethod.Invoke(null, new Object [] { query, orderBy }) as IQueryable; if (orderByColumns.Length 1) { MethodInfo thenByMethod = typeof(Queryable).GetMethods(BindingFlags.Public | BindingFlags.Static).Where(m = m.Name == "ThenBy").ToArray() [ 0 ].MakeGenericMethod(elementType, orderByProperty.PropertyType); PropertyInfo thenByProperty = null; MemberExpression thenByMember = null; LambdaExpression thenBy = null; for (Int32 i = 1; i 0) { MethodInfo takeMethod = typeof(Queryable).GetMethod("Take", BindingFlags.Public | BindingFlags.Static).MakeGenericMethod(elementType); MethodInfo skipMethod = typeof(Queryable).GetMethod("Skip", BindingFlags.Public | BindingFlags.Static).MakeGenericMethod(elementType); query = skipMethod.Invoke(null, new Object [] { query, pageSize * pageIndex }) as IQueryable; query = takeMethod.Invoke(null, new Object [] { query, pageSize }) as IQueryable; } MethodInfo toListMethod = typeof(Enumerable).GetMethod("ToList", BindingFlags.Static | BindingFlags.Public).MakeGenericMethod(elementType); IList list = toListMethod.Invoke(null, new Object [] { query }) as IList; return (list); } public static List ApplyPagingAndSorting(IEnumerable enumerable, Int32 pageSize, Int32 pageIndex, params String [] orderByColumns) { return (ApplyPagingAndSorting(enumerable, typeof(T), pageSize, pageIndex, orderByColumns) as List); } List list = new List { new DateTime(2010, 1, 1), new DateTime(1999, 1, 12), new DateTime(1900, 10, 10), new DateTime(1900, 2, 20), new DateTime(2012, 5, 5), new DateTime(2012, 1, 20) }; List sortedList = ApplyPagingAndSorting(list, 3, 0, "Year", "Month", "Day"); SyntaxHighlighter.config.clipboardSwf = 'http://alexgorbatchev.com/pub/sh/2.0.320/scripts/clipboard.swf'; SyntaxHighlighter.brushes.CSharp.aliases = ['c#', 'c-sharp', 'csharp']; SyntaxHighlighter.all();

    Read the article

  • Dependency injection with n-tier Entity Framework solution

    - by Matthew
    I am currently designing an n-tier solution which is using Entity Framework 5 (.net 4) as its data access strategy, but am concerned about how to incorporate dependency injection to make it testable / flexible. My current solution layout is as follows (my solution is called Alcatraz): Alcatraz.WebUI: An asp.net webform project, the front end user interface, references projects Alcatraz.Business and Alcatraz.Data.Models. Alcatraz.Business: A class library project, contains the business logic, references projects Alcatraz.Data.Access, Alcatraz.Data.Models Alcatraz.Data.Access: A class library project, houses AlcatrazModel.edmx and AlcatrazEntities DbContext, references projects Alcatraz.Data.Models. Alcatraz.Data.Models: A class library project, contains POCOs for the Alcatraz model, no references. My vision for how this solution would work is the web-ui would instantiate a repository within the business library, this repository would have a dependency (through the constructor) of a connection string (not an AlcatrazEntities instance). The web-ui would know the database connection strings, but not that it was an entity framework connection string. In the Business project: public class InmateRepository : IInmateRepository { private string _connectionString; public InmateRepository(string connectionString) { if (connectionString == null) { throw new ArgumentNullException("connectionString"); } EntityConnectionStringBuilder connectionBuilder = new EntityConnectionStringBuilder(); connectionBuilder.Metadata = "res://*/AlcatrazModel.csdl|res://*/AlcatrazModel.ssdl|res://*/AlcatrazModel.msl"; connectionBuilder.Provider = "System.Data.SqlClient"; connectionBuilder.ProviderConnectionString = connectionString; _connectionString = connectionBuilder.ToString(); } public IQueryable<Inmate> GetAllInmates() { AlcatrazEntities ents = new AlcatrazEntities(_connectionString); return ents.Inmates; } } In the Web UI: IInmateRepository inmateRepo = new InmateRepository(@"data source=MATTHEW-PC\SQLEXPRESS;initial catalog=Alcatraz;integrated security=True;"); List<Inmate> deathRowInmates = inmateRepo.GetAllInmates().Where(i => i.OnDeathRow).ToList(); I have a few related questions about this design. 1) Does this design even make sense in terms of Entity Frameworks capabilities? I heard that Entity framework uses the Unit-of-work pattern already, am I just adding another layer of abstract unnecessarily? 2) I don't want my web-ui to directly communicate with Entity Framework (or even reference it for that matter), I want all database access to go through the business layer as in the future I will have multiple projects using the same business layer (web service, windows application, etc.) and I want to have it easy to maintain / update by having the business logic in one central area. Is this an appropriate way to achieve this? 3) Should the Business layer even contain repositories, or should that be contained within the Access layer? If where they are is alright, is passing a connection string a good dependency to assume? Thanks for taking the time to read!

    Read the article

  • Dynamic Filtering

    - by Ricardo Peres
    Continuing my previous posts on dynamic LINQ, now it's time for dynamic filtering. For now, I'll focus on string matching. There are three standard operators for string matching, which both NHibernate, Entity Framework and LINQ to SQL recognize: Equals Contains StartsWith EndsWith So, if we want to apply filtering by one of these operators on a string property, we can use this code: public enum MatchType { StartsWith = 0, EndsWith = 1, Contains = 2, Equals = 3 } public static List Filter(IEnumerable enumerable, String propertyName, String filter, MatchType matchType) { return (Filter(enumerable, typeof(T), propertyName, filter, matchType) as List); } public static IList Filter(IEnumerable enumerable, Type elementType, String propertyName, String filter, MatchType matchType) { MethodInfo asQueryableMethod = typeof(Queryable).GetMethods(BindingFlags.Static | BindingFlags.Public).Where(m = (m.Name == "AsQueryable") && (m.ContainsGenericParameters == false)).Single(); IQueryable query = (enumerable is IQueryable) ? (enumerable as IQueryable) : asQueryableMethod.Invoke(null, new Object [] { enumerable }) as IQueryable; MethodInfo whereMethod = typeof(Queryable).GetMethods(BindingFlags.Public | BindingFlags.Static).Where(m = m.Name == "Where").ToArray() [ 0 ].MakeGenericMethod(elementType); MethodInfo matchMethod = typeof(String).GetMethod ( (matchType == MatchType.StartsWith) ? "StartsWith" : (matchType == MatchType.EndsWith) ? "EndsWith" : (matchType == MatchType.Contains) ? "Contains" : "Equals", new Type [] { typeof(String) } ); PropertyInfo displayProperty = elementType.GetProperty(propertyName, BindingFlags.Public | BindingFlags.Instance); MemberExpression member = Expression.MakeMemberAccess(Expression.Parameter(elementType, "n"), displayProperty); MethodCallExpression call = Expression.Call(member, matchMethod, Expression.Constant(filter)); LambdaExpression where = Expression.Lambda(call, member.Expression as ParameterExpression); query = whereMethod.Invoke(null, new Object [] { query, where }) as IQueryable; MethodInfo toListMethod = typeof(Enumerable).GetMethod("ToList", BindingFlags.Static | BindingFlags.Public).MakeGenericMethod(elementType); IList list = toListMethod.Invoke(null, new Object [] { query }) as IList; return (list); } var list = new [] { new { A = "aa" }, new { A = "aabb" }, new { A = "ccaa" }, new { A = "ddaadd" } }; var contains = Filter(list, "A", "aa", MatchType.Contains); var endsWith = Filter(list, "A", "aa", MatchType.EndsWith); var startsWith = Filter(list, "A", "aa", MatchType.StartsWith); var equals = Filter(list, "A", "aa", MatchType.Equals); Perhaps I'll write some more posts on this subject in the near future. SyntaxHighlighter.config.clipboardSwf = 'http://alexgorbatchev.com/pub/sh/2.0.320/scripts/clipboard.swf'; SyntaxHighlighter.brushes.CSharp.aliases = ['c#', 'c-sharp', 'csharp']; SyntaxHighlighter.all();

    Read the article

  • Increase application performance

    - by Prayos
    I'm writing a program for a company that will generate a daily report for them. All of the data that they use for this report is stored in a local SQLite database. For this report, the utilize pretty much every bit of the information in the database. So currently, when I query the datbase, I retrieve everything, and store the information in lists. Here's what I've got: using (var dataReader = _connection.Select(query)) { if (dataReader.HasRows) { while (dataReader.Read()) { _date.Add(Convert.ToDateTime(dataReader["date"])); _measured.Add(Convert.ToDouble(dataReader["measured_dist"])); _bit.Add(Convert.ToDouble(dataReader["bit_loc"])); _psi.Add(Convert.ToDouble(dataReader["pump_press"])); _time.Add(Convert.ToDateTime(dataReader["timestamp"])); _fob.Add(Convert.ToDouble(dataReader["force_on_bit"])); _torque.Add(Convert.ToDouble(dataReader["torque"])); _rpm.Add(Convert.ToDouble(dataReader["rpm"])); _pumpOneSpm.Add(Convert.ToDouble(dataReader["pump_1_strokes_pm"])); _pumpTwoSpm.Add(Convert.ToDouble(dataReader["pump_2_strokes_pm"])); _pullForce.Add(Convert.ToDouble(dataReader["pull_force"])); _gpm.Add(Convert.ToDouble(dataReader["flow"])); } } } I then utilize these lists for the calculations. Obviously, the more information that is in this database, the longer the initial query will take. I'm curious if there is a way to increase the performance of the query at all? Thanks for any and all help. EDIT One of the report rows is called Daily Drilling Hours. For this calculation, I use this method: // Retrieves the timestamps where measured depth == bit depth and PSI >= 50 public double CalculateDailyProjectDrillingHours(DateTime date) { var dailyTimeStamps = _time.Where((t, i) => _date[i].Equals(date) && _measured[i].Equals(_bit[i]) && _psi[i] >= 50).ToList(); return _dailyDrillingHours = Convert.ToDouble(Math.Round(TimeCalculations(dailyTimeStamps).TotalHours, 2, MidpointRounding.AwayFromZero)); } // Checks that the interval is less than 10, then adds the interval to the total time private static TimeSpan TimeCalculations(IList<DateTime> timeStamps) { var interval = new TimeSpan(0, 0, 10); var totalTime = new TimeSpan(); TimeSpan timeDifference; for (var j = 0; j < timeStamps.Count - 1; j++) { if (timeStamps[j + 1].Subtract(timeStamps[j]) <= interval) { timeDifference = timeStamps[j + 1].Subtract(timeStamps[j]); totalTime = totalTime.Add(timeDifference); } } return totalTime; }

    Read the article

  • RemoveAll Dictionary Extension Method

    - by João Angelo
    Removing from a dictionary all the elements where the keys satisfy a set of conditions is something I needed to do more than once so I implemented it as an extension method to the IDictionary<TKey, TValue> interface. Here’s the code: public static class DictionaryExtensions { /// <summary> /// Removes all the elements where the key match the conditions defined by the specified predicate. /// </summary> /// <typeparam name="TKey"> /// The type of the dictionary key. /// </typeparam> /// <typeparam name="TValue"> /// The type of the dictionary value. /// </typeparam> /// <param name="dictionary"> /// A dictionary from which to remove the matched keys. /// </param> /// <param name="match"> /// The <see cref="Predicate{T}"/> delegate that defines the conditions of the keys to remove. /// </param> /// <exception cref="ArgumentNullException"> /// dictionary is null /// <br />-or-<br /> /// match is null. /// </exception> /// <returns> /// The number of elements removed from the <see cref="IDictionary{TKey, TValue}"/>. /// </returns> public static int RemoveAll<TKey, TValue>( this IDictionary<TKey, TValue> dictionary, Predicate<TKey> match) { if (dictionary == null) throw new ArgumentNullException("dictionary"); if (match == null) throw new ArgumentNullException("match"); var keysToRemove = dictionary.Keys.Where(k => match(k)).ToList(); if (keysToRemove.Count == 0) return 0; foreach (var key in keysToRemove) { dictionary.Remove(key); } return keysToRemove.Count; } }

    Read the article

  • How to join two collections with LINQ

    - by JustinGreenwood
    Here is a simple and complete example of how to perform joins on two collections with LINQ. I wrote it for a friend to show him, in one simple file, the power of LINQ queries and anonymous objects. In the file below, there are two simple data classes defined: Person and Item. In the beginning of the main method, two collections are created. Note that the Item's OwnerId field reference the PersonId of a Person object. The effect of the LINQ query below is equivalent to a SQL statement looking like this: select Person.PersonName as OwnerName, Item.ItemName as OwnedItem from Person inner join Item on Item.OwnerId = Person.PersonId order by Item.ItemName desc; using System; using System.Collections.Generic; using System.Linq; namespace LinqJoinAnonymousObjects { class Program { class Person { public int PersonId { get; set; } public string PersonName { get; set; } } class Item { public string ItemName { get; set; } public int OwnerId { get; set; } } static void Main(string[] args) { // Create two collections: one of people, and another with their possessions. var people = new List<Person> { new Person { PersonId=1, PersonName="Justin" }, new Person { PersonId=2, PersonName="Arthur" }, new Person { PersonId=3, PersonName="Bob" } }; var items = new List<Item> { new Item { OwnerId=1, ItemName="Armor" }, new Item { OwnerId=1, ItemName="Book" }, new Item { OwnerId=2, ItemName="Chain Mail" }, new Item { OwnerId=2, ItemName="Excalibur" }, new Item { OwnerId=3, ItemName="Bubbles" }, new Item { OwnerId=3, ItemName="Gold" } }; // Create a new, anonymous composite result for person id=2. var compositeResult = from p in people join i in items on p.PersonId equals i.OwnerId where p.PersonId == 2 orderby i.ItemName descending select new { OwnerName = p.PersonName, OwnedItem = i.ItemName }; // The query doesn't evaluate until you iterate through the query or convert it to a list Console.WriteLine("[" + compositeResult.GetType().Name + "]"); // Convert to a list and loop through it. var compositeList = compositeResult.ToList(); Console.WriteLine("[" + compositeList.GetType().Name + "]"); foreach (var o in compositeList) { Console.WriteLine("\t[" + o.GetType().Name + "] " + o.OwnerName + " - " + o.OwnedItem); } Console.ReadKey(); } } } The output of the program is below: [WhereSelectEnumerableIterator`2] [List`1] [<>f__AnonymousType1`2] Arthur - Excalibur [<>f__AnonymousType1`2] Arthur - Chain Mail

    Read the article

  • Rendering My Fault Message

    - by onefloridacoder
    My coworkers setup  a nice way to get the fault messages from our service layer all the way back to the client’s service proxy layer.  This is what I needed to work on this afternoon.  Through a series of trials and errors I finally figured this out. The confusion was how I was looking at the exception in the quick watch viewer.  It appeared as though the EventArgs from the service call had somehow magically been cast back to FaultException(), not FaultException<T>.  I drilled into the EventArgs object with the quick watch and I copied this code to figure out where the Fault message was hiding.  Further, when I copied this quick watch code into the IDE I got squigglies.  Poop. 1: ((System 2: .ServiceModel 3: .FaultException<UnhandledExceptionFault>)(((System.Exception)(e.Result)).InnerException)).Detail.FaultMessage I wont bore you with the details but here’s how it turned out.   EventArgs which I’m calling “e” is not the result such as some collection of items you’re expecting.  It’s actually a FaultException, or in my case FaultException<T>.  Below is the calling code and the callback to handle the expected response or the fault from the completed event. 1: public void BeginRetrieveItems(Action<ObservableCollection<Model.Widget>> FindItemsCompleteCallback, Model.WidgetLocation location) 2: { 3: var proxy = new MyServiceContractClient(); 4:  5: proxy.RetrieveWidgetsCompleted += (s, e) => FindWidgetsCompleteCallback(FindWidgetsCompleted(e)); 6:  7: RetrieveWidgetsRequest request = new RetrieveWidgetsRequest { location.Id }; 8:  9: proxy.RetrieveWidgetsAsync(request); 10: } 11:  12: private ObservableCollection<Model.Widget> FindItemsCompleted(RetrieveWidgetsCompletedEventArgs e) 13: { 14: if (e.Error is FaultException<UnhandledExceptionFault>) 15: { 16: var fault = (FaultException<UnhandledExceptionFault>)e.Error; 17: var faultDetailMessage = fault.Detail.FaultMessage; 18:  19: UIMessageControlDuJour.Show(faultDetailMessage); 20: return new ObservableCollection<BinInventoryItemCountInfo>(); 21: } 22:  23: var widgets = new ObservableCollection<Model.Widget>(); 24:  25: if (e.Result.Widgets != null) 26: { 27: e.Result.Widgets.ToList().ForEach(w => widgets.Add(this.WidgetMapper.Map(w))); 28: } 29:  30: return widgets; 31: }

    Read the article

  • Are there any concerns with using a static read-only unit of work so that it behaves like a cache?

    - by Rowan Freeman
    Related question: How do I cache data that rarely changes? I'm making an ASP.NET MVC4 application. On every request the security details about the user will need to be checked with the area/controller/action that they are accessing to see if they are allowed to view it. The security information is stored in the database. For example: User Permission UserPermission Action ActionPermission A "Permission" is a token that is applied to an MVC action to indicate that the token is required in order to access the action. Once a user is given the permission (via the UserPermission table) then they have the token and can therefore access the action. I've been looking in to how to cache this data (since it rarely changes) so that I'm only querying in-memory data and not hitting a database (which is a considerable performance hit at the moment). I've tried storing things in lists, using a caching provider but I either run in to problems or performance doesn't improve. One problem that I constantly run in to is that I'm using lazy loading and dynamic proxies with EntityFramework. This means that even if I ToList() everything and store them somewhere static, the relationships are never populated. For example, User.Permissions is an ICollection but it's always null. I don't want to Include() everything because I'm trying to keep things simple and generic (and easy to modify). One thing I know is that an EntityFramework DbContext is a unit of work that acts with 1st-level caching. That is, for the duration of the unit of work, everything that is accessed is cached in memory. I want to create a read-only DbContext that will exist indefinitely and will only be used to read about permission data. Upon testing this it worked perfectly; my page load times went from 200ms+ to 20ms. I can easily force the data to refresh at certain intervals or simply leave it to refresh when the application pool is recycled. Basically it will behave like a cache. Note that the rest of the application will interact with other contexts that exist per request as normal. Is there any disadvantage to this approach? Could I be doing something different?

    Read the article

  • What are the best practices to use NHiberante sessions in asp.net (mvc/web api) ?

    - by mrt181
    I have the following setup in my project: public class WebApiApplication : System.Web.HttpApplication { public static ISessionFactory SessionFactory { get; private set; } public WebApiApplication() { this.BeginRequest += delegate { var session = SessionFactory.OpenSession(); CurrentSessionContext.Bind(session); }; this.EndRequest += delegate { var session = SessionFactory.GetCurrentSession(); if (session == null) { return; } session = CurrentSessionContext.Unbind(SessionFactory); session.Dispose(); }; } protected void Application_Start() { AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); var assembly = Assembly.GetCallingAssembly(); SessionFactory = new NHibernateHelper(assembly, Server.MapPath("/")).SessionFactory; } } public class PositionsController : ApiController { private readonly ISession session; public PositionsController() { this.session = WebApiApplication.SessionFactory.GetCurrentSession(); } public IEnumerable<Position> Get() { var result = this.session.Query<Position>().Cacheable().ToList(); if (!result.Any()) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.NotFound)); } return result; } public HttpResponseMessage Post(PositionDataTransfer dto) { //TODO: Map dto to model IEnumerable<Position> positions = null; using (var transaction = this.session.BeginTransaction()) { this.session.SaveOrUpdate(positions); try { transaction.Commit(); } catch (StaleObjectStateException) { if (transaction != null && transaction.IsActive) { transaction.Rollback(); } } } var response = this.Request.CreateResponse(HttpStatusCode.Created, dto); response.Headers.Location = new Uri(this.Request.RequestUri.AbsoluteUri + "/" + dto.Name); return response; } public void Put(int id, string value) { //TODO: Implement PUT throw new NotImplementedException(); } public void Delete(int id) { //TODO: Implement DELETE throw new NotImplementedException(); } } I am not sure if this is the recommended way to insert the session into the controller. I was thinking about using DI but i am not sure how to inject the session that is opened and binded in the BeginRequest delegate into the Controllers constructor to get this public PositionsController(ISession session) { this.session = session; } Question: What is the recommended way to use NHiberante sessions in asp.net mvc/web api ?

    Read the article

  • bulk insert and update with ADO.NET Entity Framework

    - by Keith Barrows
    I am writing a small application that does a lot of feed processing. I want to use LINQ EF for this as speed is not an issue, it is a single user app and, in the end, will only be used once a month. My questions revolves around the best way to do bulk inserts using LINQ EF. After parsing the incoming data stream I end up with a List of values. Since the end user may end up trying to import some duplicate data I would like to "clean" the data during insert rather than reading all the records, doing a for loop, rejecting records, then finally importing the remainder. This is what I am currently doing: DateTime minDate = dataTransferObject.Min(c => c.DoorOpen); DateTime maxDate = dataTransferObject.Max(c => c.DoorOpen); using (LabUseEntities myEntities = new LabUseEntities()) { var recCheck = myEntities.ImportDoorAccess.Where(a => a.DoorOpen >= minDate && a.DoorOpen <= maxDate).ToList(); if (recCheck.Count > 0) { foreach (ImportDoorAccess ida in recCheck) { DoorAudit da = dataTransferObject.Where(a => a.DoorOpen == ida.DoorOpen && a.CardNumber == ida.CardNumber).First(); if (da != null) da.DoInsert = false; } } ImportDoorAccess newIDA; foreach (DoorAudit newDoorAudit in dataTransferObject) { if (newDoorAudit.DoInsert) { newIDA = new ImportDoorAccess { CardNumber = newDoorAudit.CardNumber, Door = newDoorAudit.Door, DoorOpen = newDoorAudit.DoorOpen, Imported = newDoorAudit.Imported, RawData = newDoorAudit.RawData, UserName = newDoorAudit.UserName }; myEntities.AddToImportDoorAccess(newIDA); } } myEntities.SaveChanges(); } I am also getting this error: System.Data.UpdateException was unhandled Message="Unable to update the EntitySet 'ImportDoorAccess' because it has a DefiningQuery and no element exists in the element to support the current operation." Source="System.Data.SqlServerCe.Entity" What am I doing wrong? Any pointers are welcome.

    Read the article

  • Namespace not found in MVC 3 Razor view

    - by PlTaylor
    I am adding a PagedList to my view and loosely following this Tutorial. I have installed the PagedList reference using Nuget, set up my controller as follows public ViewResult Index(int page = 1) { List<Part> model = this.db.Parts.ToList(); const int pageSize = 20; return View(model.ToPagedList(page, pageSize)); } And written my view with the following model at the top @model PagedList.IPagedList<RIS.Models.Part> When I run the page I get the following error Compiler Error Message: CS0246: The type or namespace name 'PagedList' could not be found (are you missing a using directive or an assembly reference?) Source Error: Line 27: Line 28: Line 29: public class _Page_Areas_Parts_Views_Part_Index_cshtml : System.Web.Mvc.WebViewPage<PagedList.IPagedList<RIS.Models.Part>> { The PagedList dll is being properly loaded in my controller because when I take it out of my view everything works as expected. The CopyLocal property is set to 'True' and I have tried including the namespace in the Views\Web.Config in my specific Area. What else can I do to make the View see the Namespace?

    Read the article

  • Could not determine metatable error binding list to asp.net datagridview

    - by Scott Vercuski
    I am working with the following block of code ... List<ThemeObject> themeList = (from theme in database.Themes join image in database.DBImages on theme.imageID equals image.imageID into resultSet from item in resultSet select new ThemeObject { Name = theme.Name, ImageID = item.imageID}).ToList(); dgvGridView.DataSource = themeList; dgvGridView.DataBind(); The list object populates fine. The datagrid is setup with 2 columns. A textbox column for the "Name" which is bound to "Name" An image column which is bound to the "ImageID" field When I execute the code I receive the following error on the DataBind() Could not determine a MetaTable. A MetaTable could not be determined for the data source '' and one could not be inferred from the request URL. Make sure that the table is mapped to the dats source, or that the data source is configured with a valid context type and table name, or that the request is part of a registered DynamicDataRoute. I'm not using any dynamicdataroutes as far as I can tell. Has anyone experienced this error before?

    Read the article

  • Why LINQ to Entities won't let me initialize just some properties of an Entity?

    - by emzero
    So I've started to add Entity Framework 4 into a legacy web application (ASP.NET WebForms). As a start I have auto-generated some entities from the database. Also I want to apply Repository Pattern. There is an entity called Visitor and its repository VisitorRepository In VisitorRepository I have the following method: public IEnumerable<Visitor> GetActiveVisitors() { var visitors = from v in _context.Visitors where v.IsActive select new Visitor { VisitorID = v.VisitorID, EmailAddress = v.EmailAddress, RegisterDate = v.RegisterDate, Company = v.Company, Position = v.Position, FirstName = v.FirstName, LastName = v.LastName }; return visitors.ToList(); } That List is then bound to a repeater and when trying to do <%# Eval('EmailAddress') #%> it throws the following exception. The entity or complex type 'Model.Visitor' cannot be constructed in a LINQ to Entities query. A) Why is this happening? How I can workaround this? Do I need to select an anonymous type and then use that to initialize my entities??? B) Why every example I've seen makes use of 'select new' (anonymous object) instead of initializing a known type? Anonymous types are useless unless you are retrieving the data and showing it in the same layer. As far as I know anonymous types cannot be returned from methods? So what's the real point of them??? Thank you all

    Read the article

  • DataSet does not support System.Nullable<>

    - by a_m0d
    I'm trying to set the DataSource for a Crystal Reports report, but I've run into a few problems. I've been following a guide written by Mohammad Mahdi Ramezanpour, and have managed to get all the way to the last part now (setting the DataSource). However, I have a problem that Mohammad does not seem to have - when I pass the results of my query to the report, I end up with the following exception: DataSet does not support System.Nullable< This is the query I am using: public IQueryable<Part> GetPartsToDisplayOnStockReport() { return from part in db.Parts where part.showOnStockReport == true select part; } and the way I pass it to the Report: public ActionResult ViewStockReport() { StockReport stockReport = new StockReport(); var parts = ordersRepository.GetPartsToDisplayOnStockReport().ToList(); stockReport.SetDataSource(parts); Stream stream = stockReport.ExportToStream(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat); return File(stream, "application/pdf"); } I have also tried changing my query to this code, in the hope that it would fix my problem: return (from part in db.Parts where part.showOnStockReport == true select part) ?? db.Parts.DefaultIfEmpty(); but it still complained about the same problem. How can I pass the results of this query to my report, to use it as a data source? Also, if each of my Parts object contains other objects / collections of other objects, will I be able to reference them in the report with a datasource like this?

    Read the article

  • How to retrieve value from DropDownListFor html helper in ASP>NET MVC2?

    - by Eedoh
    Hello I know there was few similar questions here about DropDownListFor, but neither helped me... I use Entity Framework as ORM in my project. There's EF model called "Stete". Stete has Foreign on EF model called "Drustva" Now I'm trying to make a form for editing the data, for Stete model. I managed to display everything, including Stete.Drustva.Naziv property, but I can't get this last property in my handler method [HttpPost]. It always return 0, no matter what I select in drop down list. Here's the code: DrustvaController: public static IEnumerable<SelectListItem> DrustvaToSelectListItemsById(this KnjigaStetnikaEntities pEntities, int Id) { IEnumerable<Drustva> drustva = (from d in pEntities.Drustva select d).ToList(); return drustva.OrderBy(drustvo => drustvo.Naziv).Select(drustvo => new SelectListItem { Text = drustvo.Naziv, Value = drustvo.Id.ToString(), Selected = (drustvo.Id == Id)? true : false }); } SteteController: private IEnumerable<SelectListItem> privremenaListaDrustava(int Id) { using (var ctx = new KnjigaStetnikaEntities()) { return ctx.DrustvaToSelectListItemsById(Id); } } public ActionResult IzmijeniPodatkeStete(Int32 pBrojStete) { PretragaStetaModel psm = new PretragaStetaModel(); ViewData["drustva"] = privremenaListaDrustava(psm.VratiStetuPoBrojuStete(pBrojStete).Drustva.Id); ViewData.Model = new Models.Stete(); return View("EditView", (Stete.Models.Stete)psm.GetSteta(pBrojStete)); } EditView: <div class="editor-label"> <%: Html.Label("Društvo") %> </div> <div class="editor-field"> <%: Html.DropDownListFor(m => m.Drustva.Naziv, ViewData["drustva"] as IEnumerable<SelectListItem>) %> <%: Html.ValidationMessageFor(model => model.FKDrustvo) %> </div> I am sorry for not translating names of the objects into english, but they hardly have appropriate translation. If necessary, I can try creating similar example...

    Read the article

  • JavaScriptSerializer().Serialize(Entity Framework object)

    - by loviji
    May be, it is not so problematic for you. but i'm trying first time with json serialization. and also read other articles in stackowerflow. I have created Entity Framework data model. then by method get all data from object: private uqsEntities _db = new uqsEntities(); //get all data from table sysMainTableColumns where tableName=paramtableName public List<sysMainTableColumns> getDataAboutMainTable(string tableName) { return (from column in _db.sysMainTableColumns where column.TableName==tableName select column).ToList(); } my webservice: public string getDataAboutMainTable() { penta.DAC.Tables dictTable = new penta.DAC.Tables(); var result = dictTable.getDataAboutMainTable("1"); return new JavaScriptSerializer().Serialize(result); } and jQuery ajax method $('#loadData').click(function() { $.ajax({ type: "POST", url: "WS/ConstructorWS.asmx/getDataAboutMainTable", data: "{}", contentType: "application/json; charset=utf-8", dataType: "json", success: function(msg) { $("#jsonResponse").html(msg); var data = eval("(" + msg + ")"); //do something with data }, error: function(msg) { } }); }); problem with data, code fails there. and i think i'm not use JavaScriptSerializer().Serialize() method very well. Please, tell me, what a big mistake I made in C# code?

    Read the article

  • entity framework 4 POCO's stored procedure error - "The FunctionImport could not be found in the container"

    - by user331884
    Entity Framework with POCO Entities generated by T4 template. Added Function Import named it "procFindNumber" specified complex collection named it "NumberResult". Here's what got generated in Context.cs file: public ObjectResult<NumberResult> procFindNumber(string lookupvalue) { ObjectParameter lookupvalueParameter; if (lookupvalue != null) { lookupvalueParameter = new ObjectParameter("lookupvalue", lookupvalue); } else { lookupvalueParameter = new ObjectParameter("lookupvalue", typeof(string)); } return base.ExecuteFunction<NumberResult>("procFindNumber", lookupvalueParameter); } Here's the stored procedure: ALTER PROCEDURE [dbo].[procFindNumber] @lookupvalue varchar(255) AS BEGIN SET NOCOUNT ON; DECLARE @sql nvarchar(MAX); IF @lookupvalue IS NOT NULL AND @lookupvalue <> '' BEGIN SELECT @sql = 'SELECT dbo.HBM_CLIENT.CLIENT_CODE, dbo.HBM_MATTER.MATTER_NAME, dbo.HBM_MATTER.CLIENT_MAT_NAME FROM dbo.HBM_MATTER INNER JOIN dbo.HBM_CLIENT ON dbo.HBM_MATTER.CLIENT_CODE = dbo.HBM_CLIENT.CLIENT_CODE LEFT OUTER JOIN dbo.HBL_CLNT_CAT ON dbo.HBM_CLIENT.CLNT_CAT_CODE = dbo.HBL_CLNT_CAT.CLNT_CAT_CODE LEFT OUTER JOIN dbo.HBL_CLNT_TYPE ON dbo.HBM_CLIENT.CLNT_TYPE_CODE = dbo.HBL_CLNT_TYPE.CLNT_TYPE_CODE WHERE (LTRIM(RTRIM(dbo.HBM_MATTER.CLIENT_CODE)) <> '''')' SELECT @sql = @sql + ' AND (dbo.HBM_MATTER.MATTER_NAME like ''%' + @lookupvalue + '%'')' SELECT @sql = @sql + ' OR (dbo.HBM_MATTER.CLIENT_MAT_NAME like ''%' + @lookupvalue + '%'')' SELECT @sql = @sql + ' ORDER BY dbo.HBM_MATTER.MATTER_NAME' -- Execute the SQL query EXEC sp_executesql @sql END END In my WCF service I try to execute the stored procedure: [WebGet(UriTemplate = "number/{value}/?format={format}")] public IEnumerable<NumberResult> GetNumber(string value, string format) { if (string.Equals("json", format, StringComparison.OrdinalIgnoreCase)) { WebOperationContext.Current.OutgoingResponse.Format = WebMessageFormat.Json; } using (var ctx = new MyEntities()) { ctx.ContextOptions.ProxyCreationEnabled = false; var results = ctx.procFindNumber(value); return results.ToList(); } } Error message says "The FunctionImport ... could not be found in the container ..." What am I doing wrong?

    Read the article

< Previous Page | 13 14 15 16 17 18 19 20 21 22 23 24  | Next Page >