Search Results

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

Page 7/29 | < Previous Page | 3 4 5 6 7 8 9 10 11 12 13 14  | Next Page >

  • Composable FLinq expressions

    - by Daniel
    When doing linq-to-sql in c#, you could do something like this: var data = context.MyTable.Where(x => x.Parameter > 10); var q1 = data.Take(10); var q2 = data.Take(3); q1.ToArray(); q2.ToArray(); This would generate 2 separate SQL queries, one with TOP 10, and the other with TOP 3. In playing around with Flinq, I see that: let data = query <@ seq { for i in context.MyTable do if x.Parameter > 10 then yield i } @> data |> Seq.take 10 |> Seq.toList data |> Seq.take 3 |> Seq.toList is not doing the same thing. Here it seems to do one full query, and then do the "take" calls on the client side. An alternative that I see used is: let q1 = query <@ for i in context.MyTable do if x.Param > 10 then yield i } |> Seq.take 10 @> let q2 = query <@ for i in context.MyTable do if x.Param > 10 then yield i } |> Seq.take 3 @> These 2 generate the SQL with the appropriate TOP N filter. My problem with this is that it doesn't seem composable. I'm basically having to duplicate the "where" clause, and potentially would have to duplicate other other subqueries that I might want to run on a base query. Is there a way to have F# give me something more composable? (I originally posted this question to hubfs, where I have gotten a few answers, dealing with the fact that C# performs the query transformation "at the end", i.e. when the data is needed, where F# is doing that transformation eagerly.)

    Read the article

  • LINQ Expression - Dynamic From & Where Clause

    - by chillydk147
    I have the following list of integers that I need to extract varying lists of integers containing numbers from say 2-4 numbers in count. The code below will extract lists with only 2 numbers. var numList = new List<int> { 5, 20, 1, 7, 19, 3, 15, 60, 3, 21, 57, 9 }; var selectedNums = (from n1 in numList from n2 in numList where (n1 > 10) && (n2 > 10) select new { n1, n2 }).ToList(); Is there any way to build up this Linq expression dynamically so that if I wanted lists of 3 numbers it would be compiled as below, this would save me having to package the similar expression inside a different method. var selectedNums = (from n1 in numList from n2 in numList from n3 in numList where (n1 > 10) && (n2 > 10) && (n3 > 10) select new { n1, n2, n3 }).ToList();

    Read the article

  • why the exception is not caught?

    - by Álvaro García
    I have the following code: List<MyEntity> lstAllMyRecords = miDbContext.MyEntity.ToList<MyEntity>(); foreach MyEntity iterator in lstMainRecord) { tasks.Add( TaskEx.Run(() => { try { checkData(lstAllMyRecords.Where(n => n.IDReference == iterator.IDReference).ToList<MyEntity>()); } catch CustomRepository ex) { //handle my custom repository } catch (Exception) { throw; } }) ); }//foreach Task.WaitAll(tasks.ToArray()); I get all the records from my data base and in the foreach loop, I group all the records that have the same IDReference. Thenk I check if the data is correct with the method chekData. The checkData method throw a custom exception if something is wrong. I would like to catch this exception to handle it. But the problem is that with this code the exceptions are not caught and all seem to work without errors, but I know that this is not true. I try to check only one group of records that I know that has problems. If I check only one group of registrers, the loop is execute once and then only task is created. In this case the exception is caught, but if I have many groups, then any exception s thrwon. Why when I only have one task the exception is caught and with many groups are not? Thanks.

    Read the article

  • ASP.NET MVC Search

    - by Cameron
    Hi I'm building a very simple search system using ASP.NET MVC. I had it originally work by doing all the logic inside the controller but I am now moving the code piece by piece into a repository. Can anyone help me do this. Thanks. Here is the original Action Result that was in the controller. public ActionResult Index(String query) { var ArticleQuery = from m in _db.ArticleSet select m; if (!string.IsNullOrEmpty(query)) { ArticleQuery = ArticleQuery.Where(m => m.headline.Contains(query) orderby m.posted descending); } return View(ArticleQuery.ToList()); } As you can see, the Index method is used for both the initial list of articles and also for the search results (they use the same view). In the new system the code in the controller is as follows: public ActionResult Index() { return View(_repository.ListAll()); } The Repository has the following code: public IList<Article> ListAll() { var ArticleQuery = (from m in _db.ArticleSet orderby m.posted descending select m); return ArticleQuery.ToList(); } and the Interface has the following code: public interface INewsRepository { IList<Article> ListAll(); } So what I need to do is now add in the search query stuff into the repository/controller methods using this new way. Can anyone help? Thanks.

    Read the article

  • child objects in linq

    - by gangt
    I checked before I posted but couldn't find a solution. I'm new to linq and it is draining my brain to understand it. I have an xml and want to use linq to fill object that has a child object. the xml and my linq is below. My issue is on this line TaskItems = t.Elements("taskdetail").ToList<TaskItem>() //this line doesn't work how do I fill this child object? var task1 = from t in xd.Descendants("taskheader") select new { Id = t.Element("id").Value, Name = t.Element("name").Value, IsActive = Convert.ToBoolean(Convert.ToInt16(t.Element("isactive").Value)) TaskItems = t.Elements("taskdetail").ToList<TaskItem>() }; <tasks> <taskheader> <id>1</id> <name>some task</name> <isactive>1</isactive> <taskdetail> <taskid>1</taskid> <name>action1</name> <value>some action</value> </taskdetail> <taskdetail> <taskid>1</taskid> <name>action2</name> <value>some other action</value> </taskdetail> </taskheader> </tasks> public class Task { public int Id; public string Name; public bool IsActive; public List<TaskItem> TaskItems = new List<TaskItem>(); } public class TaskItem { public int TaskId; public string Name; public string Value; }

    Read the article

  • Strangest LINQ to SQL case I have ever seen

    - by kubaw
    OK, so this is the strangest issue in .net programming I have ever seen. It seems that object fields are serialized in .net web services in order of field initialization. It all started with Flex not accepting SOAP response from .net web service. I have found out that it was due to the order of serialized fields was statisfying the order of fields in declared serializable class. It had something to do with generic lists and LINQ to SQL but I can't find out what. This one is really hard to reproduce. Example to get the idea: [Serializable] public class SomeSample { public int A; public int B; public int C; } I was querying some data tables within asmx web service using linq and returning list of SomeSample objects: var r = (from ...... select new SomeSample { A = 1, C = 3 }).ToList(); Now the list was once more iterated and B field was applied some value (ex. 2). However the returned soap envelope contained following excerpt: <A>1</A><C>3</C><B>2</B> Please notice the order of serialization. If I initially initialized all fields: var r = (from ...... select new SomeSample { A = 1, B = 2, C = 3 }).ToList(); object was serialized in correct order. I must add, that in both cases the debugger shows exactly the same content of "r" variable. Am I losing my mind or is this normal behavior? Thanks in advance.

    Read the article

  • Overly accessible and incredibly resource hungry relationships between business objects. How can I f

    - by Mike
    Hi, Firstly, This might seem like a long question. I don't think it is... The code is just an overview of what im currently doing. It doesn't feel right, so I am looking for constructive criticism and warnings for pitfalls and suggestions of what I can do. I have a database with business objects. I need to access properties of parent objects. I need to maintain some sort of state through business objects. If you look at the classes, I don't think that the access modifiers are right. I don't think its structured very well. Most of the relationships are modelled with public properties. SubAccount.Account.User.ID <-- all of those are public.. Is there a better way to model a relationship between classes than this so its not so "public"? The other part of this question is about resources: If I was to make a User.GetUserList() function that returns a List, and I had 9000 users, when I call the GetUsers method, it will make 9000 User objects and inside that it will make 9000 new AccountCollection objects. What can I do to make this project not so resource hungry? Please find the code below and rip it to shreds. public class User { public string ID {get;set;} public string FirstName {get; set;} public string LastName {get; set;} public string PhoneNo {get; set;} public AccountCollection accounts {get; set;} public User { accounts = new AccountCollection(this); } public static List<Users> GetUsers() { return Data.GetUsers(); } } public AccountCollection : IEnumerable<Account> { private User user; public AccountCollection(User user) { this.user = user; } public IEnumerable<Account> GetEnumerator() { return Data.GetAccounts(user); } } public class Account { public User User {get; set;} //This is public so that the subaccount can access its Account's User's ID public int ID; public string Name; public Account(User user) { this.user = user; } } public SubAccountCollection : IEnumerable<SubAccount> { public Account account {get; set;} public SubAccountCollection(Account account) { this.account = account; } public IEnumerable<SubAccount> GetEnumerator() { return Data.GetSubAccounts(account); } } public class SubAccount { public Account account {get; set;} //this is public so that my Data class can access the account, to get the account's user's ID. public SubAccount(Account account) { this.account = account; } public Report GenerateReport() { Data.GetReport(this); } } public static class Data { public static List<Account> GetSubAccounts(Account account) { using (var dc = new databaseDataContext()) { List<SubAccount> query = (from a in dc.Accounts where a.UserID == account.User.ID //this is getting the account's user's ID select new SubAccount(account) { ID = a.ID, Name = a.Name, }).ToList(); } } public static List<Account> GetAccounts(User user) { using (var dc = new databaseDataContext()) { List<Account> query = (from a in dc.Accounts where a.UserID == User.ID //this is getting the user's ID select new Account(user) { ID = a.ID, Name = a.Name, }).ToList(); } } public static Report GetReport(SubAccount subAccount) { Report report = new Report(); //database access code here //need to get the user id of the subaccount's account for data querying. //i've got the subaccount, but how should i get the user id. //i would imagine something like this: int accountID = subAccount.Account.User.ID; //but this would require the subaccount's Account property to be public. //i do not want this to be accessible from my other project (UI). //reading up on internal seems to do the trick, but within my code it still feels //public. I could restrict the property to read, and only private set. return report; } public static List<User> GetUsers() { using (var dc = new databaseDataContext()) { var query = (from u in dc.Users select new User { ID = u.ID, FirstName = u.FirstName, LastName = u.LastName, PhoneNo = u.PhoneNo }).ToList(); return query; } } }

    Read the article

  • Why SELECT N + 1 with no foreign keys and LINQ?

    - by Daniel Flöijer
    I have a database that unfortunately have no real foreign keys (I plan to add this later, but prefer not to do it right now to make migration easier). I have manually written domain objects that map to the database to set up relationships (following this tutorial http://www.codeproject.com/Articles/43025/A-LINQ-Tutorial-Mapping-Tables-to-Objects), and I've finally gotten the code to run properly. However, I've noticed I now have the SELECT N + 1 problem. Instead of selecting all Product's they're selected one by one with this SQL: SELECT [t0].[id] AS [ProductID], [t0].[Name], [t0].[info] AS [Description] FROM [products] AS [t0] WHERE [t0].[id] = @p0 -- @p0: Input Int (Size = -1; Prec = 0; Scale = 0) [65] Controller: public ViewResult List(string category, int page = 1) { var cat = categoriesRepository.Categories.SelectMany(c => c.LocalizedCategories).Where(lc => lc.CountryID == 1).First(lc => lc.Name == category).Category; var productsToShow = cat.Products; var viewModel = new ProductsListViewModel { Products = productsToShow.Skip((page - 1) * PageSize).Take(PageSize).ToList(), PagingInfo = new PagingInfo { CurrentPage = page, ItemsPerPage = PageSize, TotalItems = productsToShow.Count() }, CurrentCategory = cat }; return View("List", viewModel); } Since I wasn't sure if my LINQ expression was correct I tried to just use this but I still got N+1: var cat = categoriesRepository.Categories.First(); Domain objects: [Table(Name = "products")] public class Product { [Column(Name = "id", IsPrimaryKey = true, IsDbGenerated = true, AutoSync = AutoSync.OnInsert)] public int ProductID { get; set; } [Column] public string Name { get; set; } [Column(Name = "info")] public string Description { get; set; } private EntitySet<ProductCategory> _productCategories = new EntitySet<ProductCategory>(); [System.Data.Linq.Mapping.Association(Storage = "_productCategories", OtherKey = "productId", ThisKey = "ProductID")] private ICollection<ProductCategory> ProductCategories { get { return _productCategories; } set { _productCategories.Assign(value); } } public ICollection<Category> Categories { get { return (from pc in ProductCategories select pc.Category).ToList(); } } } [Table(Name = "products_menu")] class ProductCategory { [Column(IsPrimaryKey = true, Name = "products_id")] private int productId; private EntityRef<Product> _product = new EntityRef<Product>(); [System.Data.Linq.Mapping.Association(Storage = "_product", ThisKey = "productId")] public Product Product { get { return _product.Entity; } set { _product.Entity = value; } } [Column(IsPrimaryKey = true, Name = "products_types_id")] private int categoryId; private EntityRef<Category> _category = new EntityRef<Category>(); [System.Data.Linq.Mapping.Association(Storage = "_category", ThisKey = "categoryId")] public Category Category { get { return _category.Entity; } set { _category.Entity = value; } } } [Table(Name = "products_types")] public class Category { [Column(Name = "id", IsPrimaryKey = true, IsDbGenerated = true, AutoSync = AutoSync.OnInsert)] public int CategoryID { get; set; } private EntitySet<ProductCategory> _productCategories = new EntitySet<ProductCategory>(); [System.Data.Linq.Mapping.Association(Storage = "_productCategories", OtherKey = "categoryId", ThisKey = "CategoryID")] private ICollection<ProductCategory> ProductCategories { get { return _productCategories; } set { _productCategories.Assign(value); } } public ICollection<Product> Products { get { return (from pc in ProductCategories select pc.Product).ToList(); } } private EntitySet<LocalizedCategory> _LocalizedCategories = new EntitySet<LocalizedCategory>(); [System.Data.Linq.Mapping.Association(Storage = "_LocalizedCategories", OtherKey = "CategoryID")] public ICollection<LocalizedCategory> LocalizedCategories { get { return _LocalizedCategories; } set { _LocalizedCategories.Assign(value); } } } [Table(Name = "products_types_localized")] public class LocalizedCategory { [Column(Name = "id", IsPrimaryKey = true, IsDbGenerated = true, AutoSync = AutoSync.OnInsert)] public int LocalizedCategoryID { get; set; } [Column(Name = "products_types_id")] private int CategoryID; private EntityRef<Category> _Category = new EntityRef<Category>(); [System.Data.Linq.Mapping.Association(Storage = "_Category", ThisKey = "CategoryID")] public Category Category { get { return _Category.Entity; } set { _Category.Entity = value; } } [Column(Name = "country_id")] public int CountryID { get; set; } [Column] public string Name { get; set; } } I've tried to comment out everything from my View, so nothing there seems to influence this. The ViewModel is as simple as it looks, so shouldn't be anything there. When reading this ( http://www.hookedonlinq.com/LinqToSQL5MinuteOVerview.ashx) I started suspecting it might be because I have no real foreign keys in the database and that I might need to use manual joins in my code. Is that correct? How would I go about it? Should I remove my mapping code from my domain model or is it something that I need to add/change to it? Note: I've stripped parts of the code out that I don't think is relevant to make it cleaner for this question. Please let me know if something is missing.

    Read the article

  • Programmatically reuse Dynamics CRM 4 icons

    - by gperera
    The team that wrote the dynamics crm sdk help rocks! I wanted to display the same crm icons on our time tracking application for consistency, so I opened up the sdk help file, searched for 'icon', ignored all the sitemap/isv config entries since I know I want to get these icons programatically, about half way down the search results I see 'organizationui', sure enough that contains the 16x16 (gridicon), 32x32 (outlookshortcuticon) and 66x48 (largeentityicon) icons!To get all the entities, execute a retrieve multiple request. RetrieveMultipleRequest request = new RetrieveMultipleRequest{    Query = new QueryExpression    {        EntityName = "organizationui",        ColumnSet = new ColumnSet(new[] { "objecttypecode", "formxml", "gridicon" }),    }}; var response = sdk.Execute(request) as RetrieveMultipleResponse;Now you have all the entities and icons, here's the tricky part, all the custom entities in crm store the icons inside gridicon, outlookshortcuticon and largeentityicon attributes, the built-in entity icons are stored inside the /_imgs/ folder with the format of /_imgs/ico_16_xxxx.gif (gridicon), with xxxx being the entity type code. The entity type code is not stored inside an attribute of organizationui, however you can get it by looking at the formxml attribute objecttypecode xml attribute. response.BusinessEntityCollection.BusinessEntities.ToList()    .Cast<organizationui>().ToList()    .ForEach(a =>    {        try        {            // easy way to check if it's a custom entity            if (!string.IsNullOrEmpty(a.gridicon))            {                byte[] gif = Convert.FromBase64String(a.gridicon);            }            else            {                // built-in entity                if (!string.IsNullOrEmpty(a.formxml))                {                    int start = a.formxml.IndexOf("objecttypecode=\"") + 16;                    int end = a.formxml.IndexOf("\"", start);                     // found the entity type code                    string code = a.formxml.Substring(start, end - start);                    string url = string.Format("/_imgs/ico_16_{0}.gif", code);Enjoy!

    Read the article

  • How to find and fix performance problems in ORM powered applications

    - by FransBouma
    Once in a while we get requests about how to fix performance problems with our framework. As it comes down to following the same steps and looking into the same things every single time, I decided to write a blogpost about it instead, so more people can learn from this and solve performance problems in their O/R mapper powered applications. In some parts it's focused on LLBLGen Pro but it's also usable for other O/R mapping frameworks, as the vast majority of performance problems in O/R mapper powered applications are not specific for a certain O/R mapper framework. Too often, the developer looks at the wrong part of the application, trying to fix what isn't a problem in that part, and getting frustrated that 'things are so slow with <insert your favorite framework X here>'. I'm in the O/R mapper business for a long time now (almost 10 years, full time) and as it's a small world, we O/R mapper developers know almost all tricks to pull off by now: we all know what to do to make task ABC faster and what compromises (because there are almost always compromises) to deal with if we decide to make ABC faster that way. Some O/R mapper frameworks are faster in X, others in Y, but you can be sure the difference is mainly a result of a compromise some developers are willing to deal with and others aren't. That's why the O/R mapper frameworks on the market today are different in many ways, even though they all fetch and save entities from and to a database. I'm not suggesting there's no room for improvement in today's O/R mapper frameworks, there always is, but it's not a matter of 'the slowness of the application is caused by the O/R mapper' anymore. Perhaps query generation can be optimized a bit here, row materialization can be optimized a bit there, but it's mainly coming down to milliseconds. Still worth it if you're a framework developer, but it's not much compared to the time spend inside databases and in user code: if a complete fetch takes 40ms or 50ms (from call to entity object collection), it won't make a difference for your application as that 10ms difference won't be noticed. That's why it's very important to find the real locations of the problems so developers can fix them properly and don't get frustrated because their quest to get a fast, performing application failed. Performance tuning basics and rules Finding and fixing performance problems in any application is a strict procedure with four prescribed steps: isolate, analyze, interpret and fix, in that order. It's key that you don't skip a step nor make assumptions: these steps help you find the reason of a problem which seems to be there, and how to fix it or leave it as-is. Skipping a step, or when you assume things will be bad/slow without doing analysis will lead to the path of premature optimization and won't actually solve your problems, only create new ones. The most important rule of finding and fixing performance problems in software is that you have to understand what 'performance problem' actually means. Most developers will say "when a piece of software / code is slow, you have a performance problem". But is that actually the case? If I write a Linq query which will aggregate, group and sort 5 million rows from several tables to produce a resultset of 10 rows, it might take more than a couple of milliseconds before that resultset is ready to be consumed by other logic. If I solely look at the Linq query, the code consuming the resultset of the 10 rows and then look at the time it takes to complete the whole procedure, it will appear to me to be slow: all that time taken to produce and consume 10 rows? But if you look closer, if you analyze and interpret the situation, you'll see it does a tremendous amount of work, and in that light it might even be extremely fast. With every performance problem you encounter, always do realize that what you're trying to solve is perhaps not a technical problem at all, but a perception problem. The second most important rule you have to understand is based on the old saying "Penny wise, Pound Foolish": the part which takes e.g. 5% of the total time T for a given task isn't worth optimizing if you have another part which takes a much larger part of the total time T for that same given task. Optimizing parts which are relatively insignificant for the total time taken is not going to bring you better results overall, even if you totally optimize that part away. This is the core reason why analysis of the complete set of application parts which participate in a given task is key to being successful in solving performance problems: No analysis -> no problem -> no solution. One warning up front: hunting for performance will always include making compromises. Fast software can be made maintainable, but if you want to squeeze as much performance out of your software, you will inevitably be faced with the dilemma of compromising one or more from the group {readability, maintainability, features} for the extra performance you think you'll gain. It's then up to you to decide whether it's worth it. In almost all cases it's not. The reason for this is simple: the vast majority of performance problems can be solved by implementing the proper algorithms, the ones with proven Big O-characteristics so you know the performance you'll get plus you know the algorithm will work. The time taken by the algorithm implementing code is inevitable: you already implemented the best algorithm. You might find some optimizations on the technical level but in general these are minor. Let's look at the four steps to see how they guide us through the quest to find and fix performance problems. Isolate The first thing you need to do is to isolate the areas in your application which are assumed to be slow. For example, if your application is a web application and a given page is taking several seconds or even minutes to load, it's a good candidate to check out. It's important to start with the isolate step because it allows you to focus on a single code path per area with a clear begin and end and ignore the rest. The rest of the steps are taken per identified problematic area. Keep in mind that isolation focuses on tasks in an application, not code snippets. A task is something that's started in your application by either another task or the user, or another program, and has a beginning and an end. You can see a task as a piece of functionality offered by your application.  Analyze Once you've determined the problem areas, you have to perform analysis on the code paths of each area, to see where the performance problems occur and which areas are not the problem. This is a multi-layered effort: an application which uses an O/R mapper typically consists of multiple parts: there's likely some kind of interface (web, webservice, windows etc.), a part which controls the interface and business logic, the O/R mapper part and the RDBMS, all connected with either a network or inter-process connections provided by the OS or other means. Each of these parts, including the connectivity plumbing, eat up a part of the total time it takes to complete a task, e.g. load a webpage with all orders of a given customer X. To understand which parts participate in the task / area we're investigating and how much they contribute to the total time taken to complete the task, analysis of each participating task is essential. Start with the code you wrote which starts the task, analyze the code and track the path it follows through your application. What does the code do along the way, verify whether it's correct or not. Analyze whether you have implemented the right algorithms in your code for this particular area. Remember we're looking at one area at a time, which means we're ignoring all other code paths, just the code path of the current problematic area, from begin to end and back. Don't dig in and start optimizing at the code level just yet. We're just analyzing. If your analysis reveals big architectural stupidity, it's perhaps a good idea to rethink the architecture at this point. For the rest, we're analyzing which means we collect data about what could be wrong, for each participating part of the complete application. Reviewing the code you wrote is a good tool to get deeper understanding of what is going on for a given task but ultimately it lacks precision and overview what really happens: humans aren't good code interpreters, computers are. We therefore need to utilize tools to get deeper understanding about which parts contribute how much time to the total task, triggered by which other parts and for example how many times are they called. There are two different kind of tools which are necessary: .NET profilers and O/R mapper / RDBMS profilers. .NET profiling .NET profilers (e.g. dotTrace by JetBrains or Ants by Red Gate software) show exactly which pieces of code are called, how many times they're called, and the time it took to run that piece of code, at the method level and sometimes even at the line level. The .NET profilers are essential tools for understanding whether the time taken to complete a given task / area in your application is consumed by .NET code, where exactly in your code, the path to that code, how many times that code was called by other code and thus reveals where hotspots are located: the areas where a solution can be found. Importantly, they also reveal which areas can be left alone: remember our penny wise pound foolish saying: if a profiler reveals that a group of methods are fast, or don't contribute much to the total time taken for a given task, ignore them. Even if the code in them is perhaps complex and looks like a candidate for optimization: you can work all day on that, it won't matter.  As we're focusing on a single area of the application, it's best to start profiling right before you actually activate the task/area. Most .NET profilers support this by starting the application without starting the profiling procedure just yet. You navigate to the particular part which is slow, start profiling in the profiler, in your application you perform the actions which are considered slow, and afterwards you get a snapshot in the profiler. The snapshot contains the data collected by the profiler during the slow action, so most data is produced by code in the area to investigate. This is important, because it allows you to stay focused on a single area. O/R mapper and RDBMS profiling .NET profilers give you a good insight in the .NET side of things, but not in the RDBMS side of the application. As this article is about O/R mapper powered applications, we're also looking at databases, and the software making it possible to consume the database in your application: the O/R mapper. To understand which parts of the O/R mapper and database participate how much to the total time taken for task T, we need different tools. There are two kind of tools focusing on O/R mappers and database performance profiling: O/R mapper profilers and RDBMS profilers. For O/R mapper profilers, you can look at LLBLGen Prof by hibernating rhinos or the Linq to Sql/LLBLGen Pro profiler by Huagati. Hibernating rhinos also have profilers for other O/R mappers like NHibernate (NHProf) and Entity Framework (EFProf) and work the same as LLBLGen Prof. For RDBMS profilers, you have to look whether the RDBMS vendor has a profiler. For example for SQL Server, the profiler is shipped with SQL Server, for Oracle it's build into the RDBMS, however there are also 3rd party tools. Which tool you're using isn't really important, what's important is that you get insight in which queries are executed during the task / area we're currently focused on and how long they took. Here, the O/R mapper profilers have an advantage as they collect the time it took to execute the query from the application's perspective so they also collect the time it took to transport data across the network. This is important because a query which returns a massive resultset or a resultset with large blob/clob/ntext/image fields takes more time to get transported across the network than a small resultset and a database profiler doesn't take this into account most of the time. Another tool to use in this case, which is more low level and not all O/R mappers support it (though LLBLGen Pro and NHibernate as well do) is tracing: most O/R mappers offer some form of tracing or logging system which you can use to collect the SQL generated and executed and often also other activity behind the scenes. While tracing can produce a tremendous amount of data in some cases, it also gives insight in what's going on. Interpret After we've completed the analysis step it's time to look at the data we've collected. We've done code reviews to see whether we've done anything stupid and which parts actually take place and if the proper algorithms have been implemented. We've done .NET profiling to see which parts are choke points and how much time they contribute to the total time taken to complete the task we're investigating. We've performed O/R mapper profiling and RDBMS profiling to see which queries were executed during the task, how many queries were generated and executed and how long they took to complete, including network transportation. All this data reveals two things: which parts are big contributors to the total time taken and which parts are irrelevant. Both aspects are very important. The parts which are irrelevant (i.e. don't contribute significantly to the total time taken) can be ignored from now on, we won't look at them. The parts which contribute a lot to the total time taken are important to look at. We now have to first look at the .NET profiler results, to see whether the time taken is consumed in our own code, in .NET framework code, in the O/R mapper itself or somewhere else. For example if most of the time is consumed by DbCommand.ExecuteReader, the time it took to complete the task is depending on the time the data is fetched from the database. If there was just 1 query executed, according to tracing or O/R mapper profilers / RDBMS profilers, check whether that query is optimal, uses indexes or has to deal with a lot of data. Interpret means that you follow the path from begin to end through the data collected and determine where, along the path, the most time is contributed. It also means that you have to check whether this was expected or is totally unexpected. My previous example of the 10 row resultset of a query which groups millions of rows will likely reveal that a long time is spend inside the database and almost no time is spend in the .NET code, meaning the RDBMS part contributes the most to the total time taken, the rest is compared to that time, irrelevant. Considering the vastness of the source data set, it's expected this will take some time. However, does it need tweaking? Perhaps all possible tweaks are already in place. In the interpret step you then have to decide that further action in this area is necessary or not, based on what the analysis results show: if the analysis results were unexpected and in the area where the most time is contributed to the total time taken is room for improvement, action should be taken. If not, you can only accept the situation and move on. In all cases, document your decision together with the analysis you've done. If you decide that the perceived performance problem is actually expected due to the nature of the task performed, it's essential that in the future when someone else looks at the application and starts asking questions you can answer them properly and new analysis is only necessary if situations changed. Fix After interpreting the analysis results you've concluded that some areas need adjustment. This is the fix step: you're actively correcting the performance problem with proper action targeted at the real cause. In many cases related to O/R mapper powered applications it means you'll use different features of the O/R mapper to achieve the same goal, or apply optimizations at the RDBMS level. It could also mean you apply caching inside your application (compromise memory consumption over performance) to avoid unnecessary re-querying data and re-consuming the results. After applying a change, it's key you re-do the analysis and interpretation steps: compare the results and expectations with what you had before, to see whether your actions had any effect or whether it moved the problem to a different part of the application. Don't fall into the trap to do partly analysis: do the full analysis again: .NET profiling and O/R mapper / RDBMS profiling. It might very well be that the changes you've made make one part faster but another part significantly slower, in such a way that the overall problem hasn't changed at all. Performance tuning is dealing with compromises and making choices: to use one feature over the other, to accept a higher memory footprint, to go away from the strict-OO path and execute queries directly onto the RDBMS, these are choices and compromises which will cross your path if you want to fix performance problems with respect to O/R mappers or data-access and databases in general. In most cases it's not a big issue: alternatives are often good choices too and the compromises aren't that hard to deal with. What is important is that you document why you made a choice, a compromise: which analysis data, which interpretation led you to the choice made. This is key for good maintainability in the years to come. Most common performance problems with O/R mappers Below is an incomplete list of common performance problems related to data-access / O/R mappers / RDBMS code. It will help you with fixing the hotspots you found in the interpretation step. SELECT N+1: (Lazy-loading specific). Lazy loading triggered performance bottlenecks. Consider a list of Orders bound to a grid. You have a Field mapped onto a related field in Order, Customer.CompanyName. Showing this column in the grid will make the grid fetch (indirectly) for each row the Customer row. This means you'll get for the single list not 1 query (for the orders) but 1+(the number of orders shown) queries. To solve this: use eager loading using a prefetch path to fetch the customers with the orders. SELECT N+1 is easy to spot with an O/R mapper profiler or RDBMS profiler: if you see a lot of identical queries executed at once, you have this problem. Prefetch paths using many path nodes or sorting, or limiting. Eager loading problem. Prefetch paths can help with performance, but as 1 query is fetched per node, it can be the number of data fetched in a child node is bigger than you think. Also consider that data in every node is merged on the client within the parent. This is fast, but it also can take some time if you fetch massive amounts of entities. If you keep fetches small, you can use tuning parameters like the ParameterizedPrefetchPathThreshold setting to get more optimal queries. Deep inheritance hierarchies of type Target Per Entity/Type. If you use inheritance of type Target per Entity / Type (each type in the inheritance hierarchy is mapped onto its own table/view), fetches will join subtype- and supertype tables in many cases, which can lead to a lot of performance problems if the hierarchy has many types. With this problem, keep inheritance to a minimum if possible, or switch to a hierarchy of type Target Per Hierarchy, which means all entities in the inheritance hierarchy are mapped onto the same table/view. Of course this has its own set of drawbacks, but it's a compromise you might want to take. Fetching massive amounts of data by fetching large lists of entities. LLBLGen Pro supports paging (and limiting the # of rows returned), which is often key to process through large sets of data. Use paging on the RDBMS if possible (so a query is executed which returns only the rows in the page requested). When using paging in a web application, be sure that you switch server-side paging on on the datasourcecontrol used. In this case, paging on the grid alone is not enough: this can lead to fetching a lot of data which is then loaded into the grid and paged there. Keep note that analyzing queries for paging could lead to the false assumption that paging doesn't occur, e.g. when the query contains a field of type ntext/image/clob/blob and DISTINCT can't be applied while it should have (e.g. due to a join): the datareader will do DISTINCT filtering on the client. this is a little slower but it does perform paging functionality on the data-reader so it won't fetch all rows even if the query suggests it does. Fetch massive amounts of data because blob/clob/ntext/image fields aren't excluded. LLBLGen Pro supports field exclusion for queries. You can exclude fields (also in prefetch paths) per query to avoid fetching all fields of an entity, e.g. when you don't need them for the logic consuming the resultset. Excluding fields can greatly reduce the amount of time spend on data-transport across the network. Use this optimization if you see that there's a big difference between query execution time on the RDBMS and the time reported by the .NET profiler for the ExecuteReader method call. Doing client-side aggregates/scalar calculations by consuming a lot of data. If possible, try to formulate a scalar query or group by query using the projection system or GetScalar functionality of LLBLGen Pro to do data consumption on the RDBMS server. It's far more efficient to process data on the RDBMS server than to first load it all in memory, then traverse the data in-memory to calculate a value. Using .ToList() constructs inside linq queries. It might be you use .ToList() somewhere in a Linq query which makes the query be run partially in-memory. Example: var q = from c in metaData.Customers.ToList() where c.Country=="Norway" select c; This will actually fetch all customers in-memory and do an in-memory filtering, as the linq query is defined on an IEnumerable<T>, and not on the IQueryable<T>. Linq is nice, but it can often be a bit unclear where some parts of a Linq query might run. Fetching all entities to delete into memory first. To delete a set of entities it's rather inefficient to first fetch them all into memory and then delete them one by one. It's more efficient to execute a DELETE FROM ... WHERE query on the database directly to delete the entities in one go. LLBLGen Pro supports this feature, and so do some other O/R mappers. It's not always possible to do this operation in the context of an O/R mapper however: if an O/R mapper relies on a cache, these kind of operations are likely not supported because they make it impossible to track whether an entity is actually removed from the DB and thus can be removed from the cache. Fetching all entities to update with an expression into memory first. Similar to the previous point: it is more efficient to update a set of entities directly with a single UPDATE query using an expression instead of fetching the entities into memory first and then updating the entities in a loop, and afterwards saving them. It might however be a compromise you don't want to take as it is working around the idea of having an object graph in memory which is manipulated and instead makes the code fully aware there's a RDBMS somewhere. Conclusion Performance tuning is almost always about compromises and making choices. It's also about knowing where to look and how the systems in play behave and should behave. The four steps I provided should help you stay focused on the real problem and lead you towards the solution. Knowing how to optimally use the systems participating in your own code (.NET framework, O/R mapper, RDBMS, network/services) is key for success as well as knowing what's going on inside the application you built. I hope you'll find this guide useful in tracking down performance problems and dealing with them in a useful way.  

    Read the article

  • C#/.NET Little Wonders: A Redux

    - by James Michael Hare
    I gave my Little Wonders presentation to the Topeka Dot Net Users' Group today, so re-posting the links to all the previous posts for them. The Presentation: C#/.NET Little Wonders: A Presentation The Original Trilogy: C#/.NET Five Little Wonders (part 1) C#/.NET Five More Little Wonders (part 2) C#/.NET Five Final Little Wonders (part 3) The Subsequent Sequels: C#/.NET Little Wonders: ToDictionary() and ToList() C#/.NET Little Wonders: DateTime is Packed With Goodies C#/.NET Little Wonders: Fun With Enum Methods C#/.NET Little Wonders: Cross-Calling Constructors C#/.NET Little Wonders: Constraining Generics With Where Clause C#/.NET Little Wonders: Comparer<T>.Default C#/.NET Little Wonders: The Useful (But Overlooked) Sets The Concurrent Wonders: C#/.NET Little Wonders: The Concurrent Collections (1 of 3) - ConcurrentQueue and ConcurrentStack C#/.NET Little Wonders: The Concurrent Collections (2 of 3) - ConcurrentDictionary Tweet   Technorati Tags: .NET,C#,Little Wonders

    Read the article

  • Entity Framework Batch Update and Future Queries

    - by pwelter34
    Entity Framework Extended Library A library the extends the functionality of Entity Framework. Features Batch Update and Delete Future Queries Audit Log Project Package and Source NuGet Package PM> Install-Package EntityFramework.Extended NuGet: http://nuget.org/List/Packages/EntityFramework.Extended Source: http://github.com/loresoft/EntityFramework.Extended Batch Update and Delete A current limitations of the Entity Framework is that in order to update or delete an entity you have to first retrieve it into memory. Now in most scenarios this is just fine. There are however some senerios where performance would suffer. Also, for single deletes, the object must be retrieved before it can be deleted requiring two calls to the database. Batch update and delete eliminates the need to retrieve and load an entity before modifying it. Deleting //delete all users where FirstName matches context.Users.Delete(u => u.FirstName == "firstname"); Update //update all tasks with status of 1 to status of 2 context.Tasks.Update( t => t.StatusId == 1, t => new Task {StatusId = 2}); //example of using an IQueryable as the filter for the update var users = context.Users .Where(u => u.FirstName == "firstname"); context.Users.Update( users, u => new User {FirstName = "newfirstname"}); Future Queries Build up a list of queries for the data that you need and the first time any of the results are accessed, all the data will retrieved in one round trip to the database server. Reducing the number of trips to the database is a great. Using this feature is as simple as appending .Future() to the end of your queries. To use the Future Queries, make sure to import the EntityFramework.Extensions namespace. Future queries are created with the following extension methods... Future() FutureFirstOrDefault() FutureCount() Sample // build up queries var q1 = db.Users .Where(t => t.EmailAddress == "[email protected]") .Future(); var q2 = db.Tasks .Where(t => t.Summary == "Test") .Future(); // this triggers the loading of all the future queries var users = q1.ToList(); In the example above, there are 2 queries built up, as soon as one of the queries is enumerated, it triggers the batch load of both queries. // base query var q = db.Tasks.Where(t => t.Priority == 2); // get total count var q1 = q.FutureCount(); // get page var q2 = q.Skip(pageIndex).Take(pageSize).Future(); // triggers execute as a batch int total = q1.Value; var tasks = q2.ToList(); In this example, we have a common senerio where you want to page a list of tasks. In order for the GUI to setup the paging control, you need a total count. With Future, we can batch together the queries to get all the data in one database call. Future queries work by creating the appropriate IFutureQuery object that keeps the IQuerable. The IFutureQuery object is then stored in IFutureContext.FutureQueries list. Then, when one of the IFutureQuery objects is enumerated, it calls back to IFutureContext.ExecuteFutureQueries() via the LoadAction delegate. ExecuteFutureQueries builds a batch query from all the stored IFutureQuery objects. Finally, all the IFutureQuery objects are updated with the results from the query. Audit Log The Audit Log feature will capture the changes to entities anytime they are submitted to the database. The Audit Log captures only the entities that are changed and only the properties on those entities that were changed. The before and after values are recorded. AuditLogger.LastAudit is where this information is held and there is a ToXml() method that makes it easy to turn the AuditLog into xml for easy storage. The AuditLog can be customized via attributes on the entities or via a Fluent Configuration API. Fluent Configuration // config audit when your application is starting up... var auditConfiguration = AuditConfiguration.Default; auditConfiguration.IncludeRelationships = true; auditConfiguration.LoadRelationships = true; auditConfiguration.DefaultAuditable = true; // customize the audit for Task entity auditConfiguration.IsAuditable<Task>() .NotAudited(t => t.TaskExtended) .FormatWith(t => t.Status, v => FormatStatus(v)); // set the display member when status is a foreign key auditConfiguration.IsAuditable<Status>() .DisplayMember(t => t.Name); Create an Audit Log var db = new TrackerContext(); var audit = db.BeginAudit(); // make some updates ... db.SaveChanges(); var log = audit.LastLog;

    Read the article

  • Different ways of solving problems in code.

    - by Erin
    I now program in C# for a living but before that I programmed in python for 5 years. I have found that I write C# very differently than most examples I see on the web. Rather then writing things like: foreach (string bar in foo) { //bar has something doen to it here } I write code that looks like this. foo.ForEach( c => c.someActionhere() ) Or var result = foo.Select( c => { //Some code here to transform the item. }).ToList(); I think my using code like above came from my love of map and reduce in python - while not exactly the same thing, the concepts are close. Now it's time for my question. What concepts do you take and move with you from language to language; that allow you to solve a problem in a way that is not the normal accepted solution in that language?

    Read the article

  • Deferent ways of solving problems in code.

    - by Erin
    I now program in C# for a living but before that I programmed in python for 5 years. I have found that I write C# very that most examples I see on the web. Rather then writing things like: foreach (string bar in foo) { //bar has something doen to it here } I write code that looks like this. foo.ForEach( c => c.someActionhere() ) Or var result = foo.Select( c => { //Some code here to transform the item. }).ToList(); I think my using code like above came form my love of map and reduce in python while not exactly the same thing the concepts are close. Now it's time for my question. What concepts do you take and move with you from language to language. That allow you to solve a problem in a way that is not the normal accepted solution in that language?

    Read the article

  • IF adding new Entity gives error me : EntityCommandCompilationException was unhandled bu user code

    - by programmerist
    i have 5 tables in started projects. if i adds new table (Urun enttiy) writing below codes: project.BAL : public static List<Urun> GetUrun() { using (GenoTipSatisEntities genSatisUrunCtx = new GenoTipSatisEntities()) { ObjectQuery<Urun> urun = genSatisUrunCtx.Urun; return urun.ToList(); } } if i receive data form BAL in UI.aspx: using project.BAL; namespace GenoTip.Web.ContentPages.Satis { public partial class SatisUrun : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { FillUrun(); } } void FillUrun() { ddlUrun.DataSource = SatisServices.GetUrun(); ddlUrun.DataValueField = "ID"; ddlUrun.DataTextField = "Ad"; ddlUrun.DataBind(); } } } i added URun later. error appears ToList method: EntityCommandCompilationException was unhandled bu user code error Detail: Error 1 Error 3007: Problem in Mapping Fragments starting at lines 659, 873: Non-Primary-Key column(s) [UrunID] are being mapped in both fragments to different conceptual side properties - data inconsistency is possible because the corresponding conceptual side properties can be independently modified. C:\Users\pc\Desktop\GenoTip.Satis\GenoTip.DAL\ModelSatis.edmx 660 15 GenoTip.DAL Error 2 Error 3012: Problem in Mapping Fragments starting at lines 659, 873: Data loss is possible in FaturaDetay.UrunID. An Entity with Key (PK) will not round-trip when: (PK does NOT play Role 'FaturaDetay' in AssociationSet 'FK_FaturaDetay_Urun' AND PK is in 'FaturaDetay' EntitySet) C:\Users\pc\Desktop\GenoTip.Satis\GenoTip.DAL\ModelSatis.edmx 874 11 GenoTip.DAL Error 3 Error 3012: Problem in Mapping Fragments starting at lines 659, 873: Data loss is possible in FaturaDetay.UrunID. An Entity with Key (PK) will not round-trip when: (PK is in 'FaturaDetay' EntitySet AND PK does NOT play Role 'FaturaDetay' in AssociationSet 'FK_FaturaDetay_Urun' AND Entity.UrunID is not NULL) C:\Users\pc\Desktop\GenoTip.Satis\GenoTip.DAL\ModelSatis.edmx 660 15 GenoTip.DAL Error 4 Error 3007: Problem in Mapping Fragments starting at lines 748, 879: Non-Primary-Key column(s) [UrunID] are being mapped in both fragments to different conceptual side properties - data inconsistency is possible because the corresponding conceptual side properties can be independently modified. C:\Users\pc\Desktop\GenoTip.Satis\GenoTip.DAL\ModelSatis.edmx 749 15 GenoTip.DAL Error 5 Error 3012: Problem in Mapping Fragments starting at lines 748, 879: Data loss is possible in Satis.UrunID. An Entity with Key (PK) will not round-trip when: (PK does NOT play Role 'Satis' in AssociationSet 'FK_Satis_Urun' AND PK is in 'Satis' EntitySet) C:\Users\pc\Desktop\GenoTip.Satis\GenoTip.DAL\ModelSatis.edmx 880 11 GenoTip.DAL Error 6 Error 3012: Problem in Mapping Fragments starting at lines 748, 879: Data loss is possible in Satis.UrunID. An Entity with Key (PK) will not round-trip when: (PK is in 'Satis' EntitySet AND PK does NOT play Role 'Satis' in AssociationSet 'FK_Satis_Urun' AND Entity.UrunID is not NULL) C:\Users\pc\Desktop\GenoTip.Satis\GenoTip.DAL\ModelSatis.edmx 749 15 GenoTip.DAL

    Read the article

  • NHibernate Linq Timeout

    - by DarrenMcD
    How do I increase the timeout in NHibernate Linq To Sql? Not the Connection Timeout but the ado command timeout. using (ISession session = NHibernateHelper.OpenSession(NHibernateHelper.Databases.CarrierCDR)) using (session.BeginTransaction(IsolationLevel.ReadUncommitted)) { lCdrs = (from verizon in session.Linq<Domain.Verizon>() where verizon.Research == true && verizon.ReferenceTable == null orderby verizon.CallBillingDate descending select verizon).ToList(); }

    Read the article

  • Cross-table linq query with EF4/POCO

    - by Basiclife
    Hi All, I'm new to EF(any version) and POCO. I'm trying to use POCO entities with a generic repository in a "code-first" mode(?) I've got some POCO Entities (no proxies, no lazy loading, nothing). I have a repository(of T as Entity) which provides me with basic get/getsingle/getfirst functionality which takes a lambda as a parameter (specifically a System.Func(Of T, Boolean)) Now as I'm returning the simplest possible POCO object, none of the relationship parameters work once they've been retrieved from the database (as I would expect). However, I had assumed (wrongly) that my lambda query passed to the repository would be able to use the links between entities as it would be executed against the DB before the simple POCO entities are generated. The flow is: GUI calls: Public Function GetAllTypesForCategory(ByVal CategoryID As Guid) As IEnumerable(Of ItemType) Return ItemTypeRepository.Get(Function(x) x.Category.ID = CategoryID) End Function Get is defined in Repository(of T as Entity): Public Function [Get](ByVal Query As System.Func(Of T, Boolean)) As IEnumerable(Of T) Implements Interfaces.IRepository(Of T).Get Return ObjectSet.Where(Query).ToList() End Function The code doesn't error when this method is called but does when I try to use the result set. (This seems to be a lazy loading behaviour so I tried adding the .ToList() to force eager loading - no difference) I'm using unity/IOC to wire it all up but I believe that's irrelevant to the issue I'm having NB: Relationships between entities are being configured properly and if I turn on proxies/lazy loading/etc... this all just works. I'm intentionally leaving all that turned off as some calls to the BL will be from a website but some will be via WCF - So I want the simplest possible objects. Also, I don't want a change in an object passed to the UI to be committed to the DB if another BL method calls Commit() Can someone please either point out how to make this work or explain why it's not possible? All I want to do is make sure the lambda I pass in is performed against the DB before the results are returned Many thanks. In case it matters, the container is being populated with everything as shown below: Container.AddNewExtension(Of EFRepositoryExtension)() Container.Configure(Of IEFRepositoryExtension)(). WithConnection(ConnectionString). WithContextLifetime(New HttpContextLifetimeManager(Of IObjectContext)()). ConfigureEntity(New CategoryConfig(), "Categories"). ConfigureEntity(New ItemConfig()). ... )

    Read the article

  • ASP.NET MVC validation problem

    - by ile
    ArticleRepostitory.cs: using System; using System.Collections.Generic; using System.Linq; using System.Web; using CMS.Model; using System.Web.Mvc; namespace CMS.Models { public class ArticleDisplay { public ArticleDisplay() { } public int CategoryID { set; get; } public string CategoryTitle { set; get; } public int ArticleID { set; get; } public string ArticleTitle { set; get; } public DateTime ArticleDate; public string ArticleContent { set; get; } } public class ArticleRepository { private DB db = new DB(); // // Query Methods public IQueryable<ArticleDisplay> FindAllArticles() { var result = from category in db.ArticleCategories join article in db.Articles on category.CategoryID equals article.CategoryID select new ArticleDisplay { CategoryID = category.CategoryID, CategoryTitle = category.Title, ArticleID = article.ArticleID, ArticleTitle = article.Title, ArticleDate = article.Date, ArticleContent = article.Content }; return result; } public IQueryable<ArticleDisplay> FindTodayArticles() { var result = from category in db.ArticleCategories join article in db.Articles on category.CategoryID equals article.CategoryID where article.Date == DateTime.Today select new ArticleDisplay { CategoryID = category.CategoryID, CategoryTitle = category.Title, ArticleID = article.ArticleID, ArticleTitle = article.Title, ArticleDate = article.Date, ArticleContent = article.Content }; return result; } public Article GetArticle(int id) { return db.Articles.SingleOrDefault(d => d.ArticleID == id); } public IQueryable<ArticleDisplay> DetailsArticle(int id) { var result = from category in db.ArticleCategories join article in db.Articles on category.CategoryID equals article.CategoryID where id == article.ArticleID select new ArticleDisplay { CategoryID = category.CategoryID, CategoryTitle = category.Title, ArticleID = article.ArticleID, ArticleTitle = article.Title, ArticleDate = article.Date, ArticleContent = article.Content }; return result; } // // Insert/Delete Methods public void Add(Article article) { db.Articles.InsertOnSubmit(article); } public void Delete(Article article) { db.Articles.DeleteOnSubmit(article); } // // Persistence public void Save() { db.SubmitChanges(); } } } ArticleController.cs: using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Mvc.Ajax; using CMS.Models; using CMS.Model; namespace CMS.Controllers { public class ArticleController : Controller { ArticleRepository articleRepository = new ArticleRepository(); ArticleCategoryRepository articleCategoryRepository = new ArticleCategoryRepository(); // // GET: /Article/ public ActionResult Index() { var allArticles = articleRepository.FindAllArticles().ToList(); return View(allArticles); } // // GET: /Article/Details/5 public ActionResult Details(int id) { var article = articleRepository.DetailsArticle(id).Single(); if (article == null) return View("NotFound"); return View(article); } // // GET: /Article/Create public ActionResult Create() { ViewData["categories"] = new SelectList ( articleCategoryRepository.FindAllCategories().ToList(), "CategoryId", "Title" ); Article article = new Article() { Date = DateTime.Now, CategoryID = 1 }; return View(article); } // // POST: /Article/Create [AcceptVerbs(HttpVerbs.Post)] public ActionResult Create(Article article) { if (ModelState.IsValid) { try { // TODO: Add insert logic here articleRepository.Add(article); articleRepository.Save(); return RedirectToAction("Index"); } catch { return View(article); } } else { return View(article); } } // // GET: /Article/Edit/5 public ActionResult Edit(int id) { ViewData["categories"] = new SelectList ( articleCategoryRepository.FindAllCategories().ToList(), "CategoryId", "Title" ); var article = articleRepository.GetArticle(id); return View(article); } // // POST: /Article/Edit/5 [AcceptVerbs(HttpVerbs.Post)] public ActionResult Edit(int id, FormCollection collection) { Article article = articleRepository.GetArticle(id); try { // TODO: Add update logic here UpdateModel(article, collection.ToValueProvider()); articleRepository.Save(); return RedirectToAction("Details", new { id = article.ArticleID }); } catch { return View(article); } } // // HTTP GET: /Article/Delete/1 public ActionResult Delete(int id) { Article article = articleRepository.GetArticle(id); if (article == null) return View("NotFound"); else return View(article); } // // HTTP POST: /Article/Delete/1 [AcceptVerbs(HttpVerbs.Post)] public ActionResult Delete(int id, string confirmButton) { Article article = articleRepository.GetArticle(id); if (article == null) return View("NotFound"); articleRepository.Delete(article); articleRepository.Save(); return View("Deleted"); } } } View/Article/Create.aspx: <%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<CMS.Model.Article>" %> <asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server"> Create </asp:Content> <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server"> <h2>Create</h2> <%= Html.ValidationSummary("Create was unsuccessful. Please correct the errors and try again.") %> <% using (Html.BeginForm()) {%> <fieldset> <legend>Fields</legend> <p> <label for="Title">Title:</label> <%= Html.TextBox("Title") %> <%= Html.ValidationMessage("Title", "*") %> </p> <p> <label for="Content">Content:</label> <%= Html.TextArea("Content", new { id = "Content" })%> <%= Html.ValidationMessage("Content", "*")%> </p> <p> <label for="Date">Date:</label> <%= Html.TextBox("Date") %> <%= Html.ValidationMessage("Date", "*") %> </p> <p> <label for="CategoryID">Category:</label> <%= Html.DropDownList("CategoryId", (IEnumerable<SelectListItem>)ViewData["categories"])%> </p> <p> <input type="submit" value="Create" /> </p> </fieldset> <% } %> <div> <%=Html.ActionLink("Back to List", "Index") %> </div> </asp:Content> If I remove DropDownList from .aspx file then validation (on date only because no other validation exists) works, but of course I can't create new article because one value is missing. If I leave dropdownlist and try to insert wrong date I get following error: System.InvalidOperationException: The ViewData item with the key 'CategoryId' is of type 'System.Int32' but needs to be of type 'IEnumerable'. If I enter correct date than the article is properly inserted. There's one other thing that's confusing me... For example, if I try manually add the categoyID: [AcceptVerbs(HttpVerbs.Post)] public ActionResult Create(Article article) { if (ModelState.IsValid) { try { // TODO: Add insert logic here // Manually add category value article.CategoryID = 1; articleRepository.Add(article); articleRepository.Save(); return RedirectToAction("Index"); } catch { return View(article); } } else { return View(article); } } ..I also get the above error. There's one other thing I noticed. If I add partial class Article, when returning to articleRepository.cs I get error that 'Article' is an ambiguous reference between 'CMS.Models.Article' and 'CMS.Model.Article' Any thoughts on this one?

    Read the article

  • Timeout Expired error Using LINQ

    - by Refracted Paladin
    I am going to sum up my problem first and then offer massive details and what I have already tried. Summary: I have an internal winform app that uses Linq 2 Sql to connect to a local SQL Express database. Each user has there own DB and the DB stay in sync through Merge Replication with a Central DB. All DB's are SQL 2005(sp2or3). We have been using this app for over 5 months now but recently our users are getting a Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding. Detailed: The strange part is they get that in two differnt locations(2 differnt LINQ Methods) and only the first time they fire in a given time period(~5mins). One LINQ method is pulling all records that match a FK ID and then Manipulating them to form a Heirarchy View for a TreeView. The second is pulling all records that match a FK ID and dumping them into a DataGridView. The only things I can find in common with the 2 are that the first IS an IEnumerable and the second converts itself from IQueryable - IEnumerable - DataTable... I looked at the query's in Profiler and they 'seemed' normal. They are not very complicated querys. They are only pulling back 10 - 90 records, from one table. Any thoughts, suggestions, hints whatever would be greatly appreciated. I am at my wit's end on this.... public IList<CaseNoteTreeItem> GetTreeViewDataAsList(int personID) { var myContext = MatrixDataContext.Create(); var caseNotesTree = from cn in myContext.tblCaseNotes where cn.PersonID == personID orderby cn.ContactDate descending, cn.InsertDate descending select new CaseNoteTreeItem { CaseNoteID = cn.CaseNoteID, NoteContactDate = Convert.ToDateTime(cn.ContactDate). ToShortDateString(), ParentNoteID = cn.ParentNote, InsertUser = cn.InsertUser, ContactDetailsPreview = cn.ContactDetails.Substring(0, 75) }; return caseNotesTree.ToList<CaseNoteTreeItem>(); } AND THIS ONE public static DataTable GetAllCNotes(int personID) { using (var context = MatrixDataContext.Create()) { var caseNotes = from cn in context.tblCaseNotes where cn.PersonID == personID orderby cn.ContactDate select new { cn.ContactDate, cn.ContactDetails, cn.TimeSpentUnits, cn.IsCaseLog, cn.IsPreEnrollment, cn.PresentAtContact, cn.InsertDate, cn.InsertUser, cn.CaseNoteID, cn.ParentNote }; return caseNotes.ToList().CopyLinqToDataTable(); } }

    Read the article

  • How can I add an item to a SelectList in ASP.net MVC

    - by Barrigon
    Basically I am looking to insert an item at the beginning of a SelectList with the default value of 0 and the Text Value of " -- Select One --" Something like SelectList list = new SelectList(repository.func.ToList()); ListItem li = new ListItem(value, value); list.items.add(li); Can this be done? Cheers

    Read the article

  • C# Silverlight - Delay Child Window Load?!

    - by Goober
    The Scenario Currently I have a C# Silverlight Application That uses the domainservice class and the ADO.Net Entity Framework to communicate with my database. I want to load a child window upon clicking a button with some data that I retrieve from a server-side query to the database. The Process The first part of this process involves two load operations to load separate data from 2 tables. The next part of the process involves combining those lists of data to display in a listbox. The Problem The problem with this is that the first two asynchronous load operations haven't returned the data by the time the section of code to combine these lists of data is reached, thus result in a null value exception..... Initial Load Operations To Get The Data: public void LoadAudits(Guid jobID) { var context = new InmZenDomainContext(); var imageLoadOperation = context.Load(context.GetImageByIDQuery(jobID)); imageLoadOperation.Completed += (sender3, e3) => { imageList = ((LoadOperation<InmZen.Web.Image>)sender3).Entities.ToList(); }; var auditLoadOperation = context.Load(context.GetAuditByJobIDQuery(jobID)); auditLoadOperation.Completed += (sender2, e2) => { auditList = ((LoadOperation<Audit>)sender2).Entities.ToList(); }; } I Then Want To Execute This Immediately: IEnumerable<JobImageAudit> jobImageAuditList = from a in auditList join ai in imageList on a.ImageID equals ai.ImageID select new JobImageAudit { JobID = a.JobID, ImageID = a.ImageID.Value, CreatedBy = a.CreatedBy, CreatedDate = a.CreatedDate, Comment = a.Comment, LowResUrl = ai.LowResUrl, }; auditTrailList.ItemsSource = jobImageAuditList; However I can't because the async calls haven't returned with the data yet... Thus I have to do this (Perform the Load Operations, Then Press A Button On The Child Window To Execute The List Concatenation and binding): private void LoadAuditsButton_Click(object sender, RoutedEventArgs e) { IEnumerable<JobImageAudit> jobImageAuditList = from a in auditList join ai in imageList on a.ImageID equals ai.ImageID select new JobImageAudit { JobID = a.JobID, ImageID = a.ImageID.Value, CreatedBy = a.CreatedBy, CreatedDate = a.CreatedDate, Comment = a.Comment, LowResUrl = ai.LowResUrl, }; auditTrailList.ItemsSource = jobImageAuditList; } Potential Ideas for Solutions: Delay the child window displaying somehow? Potentially use DomainDataSource and the Activity Load control?! Any thoughts, help, solutions, samples comments etc. greatly appreciated.

    Read the article

  • amazon mws orders help simplify, flatten xml

    - by Scott Kramer
    XDocument doc = XDocument.Load( filename ); var ele = doc.Elements("AmazonEnvelope") //.Elements("Header") .Elements("Message") .Elements("OrderReport") .Elements("Item") .Select(element => new { AmazonOrderItemCode = (string)element.Element("AmazonOrderItemCode"), SKU = (string)element.Element("SKU"), Title = (string)element.Element("Title"), Quantity = (string)element.Element("Quantity"), }) //.Elements("ItemPrice") //.Elements("Component") //.Select(element => new //{ // Type = (string)element.Element("Type"), // Amount = (string)element.Element("Amount"), // }) .ToList(); foreach (var x in ele) { Console.WriteLine(x.ToString()); }

    Read the article

  • Linq to Xml to Datagridview

    - by David Archer
    Right, starting to go crazy here. I have the following code: var query = (from c in db.Descendants("Customer") select c.Elements()); dgvEditCusts.DataSource = query.ToList(); In this, db relates to an XDocument.Load call. How can I get the data into the DataGridView? Just thought I should mention: it returns a completely blank dgv

    Read the article

  • Why default constructor does not appear for value types?

    - by Arun
    The below snippet gives me a list of constructors and methods of a type. static void ReflectOnType(Type type) { Console.WriteLine(type.FullName); Console.WriteLine("------------"); List<ConstructorInfo> constructors = type.GetConstructors(BindingFlags.Public | BindingFlags.Static | BindingFlags.NonPublic |BindingFlags.Instance | BindingFlags.Default).ToList(); List<MethodInfo> methods = type.GetMethods().ToList(); Type baseType = type.BaseType; while (baseType != null) { constructors.AddRange(baseType.GetConstructors(BindingFlags.Public | BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Default)); methods.AddRange(baseType.GetMethods()); baseType = baseType.BaseType; } Console.WriteLine("Reflection on {0} type", type.Name); for (int i = 0; i < constructors.Count; i++) { Console.Write("Constructor: {0}.{1}", constructors[i].DeclaringType.Name, constructors[i].Name); Console.Write("("); ParameterInfo[] parameterInfos = constructors[i].GetParameters(); if (parameterInfos.Length > 0) { for (int j = 0; j < parameterInfos.Length; j++) { if (j > 0) { Console.Write(", "); } Console.Write("{0} {1}", parameterInfos[j].ParameterType, parameterInfos[j].Name); } } Console.Write(")"); if (constructors[i].IsSpecialName) { Console.Write(" has 'SpecialName' attribute"); } Console.WriteLine(); } Console.WriteLine(); for (int i = 0; i < methods.Count; i++) { Console.Write("Method: {0}.{1}", methods[i].DeclaringType.Name, methods[i].Name); // Determine whether or not each field is a special name. if (methods[i].IsSpecialName) { Console.Write(" has 'SpecialName' attribute"); } Console.WriteLine(); } } But when I pass an ‘int’ type to this method, why don’t I see the implicit constructor in the output? Or, how do I modify the above code to list the default constructor as well (in case I’m missing something in my code).

    Read the article

  • Bind a Java Collection to xQuery sequence from xQuery

    - by jtzero
    declare function Error:toString($this as javaObject) as xs:string external; the previous binds a return String() to xs:string. is it possible to return a collection and bind it to an xQuery Sequence, say the following declare function Error:toList($this as javaObject) as squenceType external; so that it can be run through a flwr?

    Read the article

< Previous Page | 3 4 5 6 7 8 9 10 11 12 13 14  | Next Page >