background preloader

Dynamic LINQ (Part 1: Using the LINQ Dynamic Query Library)

Dynamic LINQ (Part 1: Using the LINQ Dynamic Query Library)
LINQ (language integrated query) is one of the new features provided with VS 2008 and .NET 3.5. LINQ makes the concept of querying data a first class programming concept in .NET, and enables you to efficiently express queries in your programming language of choice. One of the benefits of LINQ is that it enables you to write type-safe queries in VB and C#. While writing type-safe queries is great for most scenarios, there are cases where you want the flexibility to dynamically construct queries on the fly. Traditionally these types of dynamic query scenarios are often handled by concatenating strings together to construct dynamic SQL queries. Downloading the LINQ Dynamic Query Library Included on the VS 2008 Samples download page are pointers to VB and C# sample packages that include a cool dynamic query LINQ helper library. Simple Dynamic Query Library Example Using the LINQ DynamicQuery library I could re-write the above query expression instead like so: Hope this helps, Scott Related:  ASP.Net & MVC

Dynamic LINQ Queries with Expression Trees It's possible to build up dynamic LINQ queries or queries with several conditional criteria. In fact there are several options for doing this, including the use of expression trees Like it or not, LINQ is here to stay. Personally I think this is a good thing. LINQ brings a lot of benefits: No magic strings (makes refactoring tools much more effective) SQL-like syntax outside of the database LINQ providers for various data sources (SQL, Entities, Objects, nHibernate, XML, etc) Initially, I thought that there was a big limitation in not being able to build up dynamic queries or queries with conditional criteria. In this article, we will review various approaches for building dynamic LINQ queries, starting with some fairly straightforward options and moving on to building the query from scratch with Expression Trees. Hopefully you'll enjoy the ride. A Little Background For purposes of this discussion, we will use the latter syntax and call it Method chaining. Type Safe Dynamic Sorting

ASP.NET MVC: Do You Know Where Your TempData Is? « Greg Shackles I recently discovered that despite the fact that I’d been using the TempData dictionary in my applications, I didn’t really have a full grasp on what it was doing behind the scenes. Of course this meant learning the lesson the hard way once something stopped working like I thought it would. I only really had myself to blame since in the end it was a simple case of RTFM, but it seemed like a good opportunity to dig in and see how TempData really works. What Is TempData? Let’s start by describing what TempData gives you. Where Is TempData Stored? This is the part that came back to bite me. You might have noticed that I said that TempData is kept in the session by DEFAULT, meaning you are not tied to that if you decide you don’t like it that way. ITempDataProvider and SessionStateTempDataProvider In the System.Web.Mvc namespace you’ll find a very simple interface called ITempDataProvider that looks like this: Not much to see there. How the TempData Provider Gets Used A MongoDB TempData Provider

Injecting Open Graph Protocol Content Into your ASP.NET MVC Site : On All Things Web In many social networking sites, pasting a URL from a news site into Facebook or Linked In displays a nice synopsis of that link. The URL pasted into such status box is read, capturing information about the page and it’s specific contents, such as a title,description, thumbnail, etc. One common technique used is to extract the Open Graph Protocol ( markup defined in the header, which is providing the additional metadata. An open graph tag is a meta tag using property names prefixed with “og:”, each page can have its own specific metadata that describes the purpose of that page. I had already created a site without open graph tags,so I began to think of a way to incorporate them with little effort. @{ ViewBag.Title = “Create a New Group”; ViewBag.Description = “Use this feature to create a new group.”; } Notice I omitted the image property, which will then use the site’s logo link.

The Open Graph protocol Don’t Do Role-Based Authorization Checks; Do Activity-Based Checks I’ve built a few dozen security mechanisms in my career. Unfortunately, I kept getting it wrong, hence the need to keep building them. Over the years, though, I learned a number of different ways that a security system can be built. One of my favorite ways to build authorization systems is through the use of role-based security. The idea is fairly simple: you assign users to roles and roles have permissions. That way you have a nice abstraction that people can be assigned to, as a role, so that you don’t have to assign the same 5, 10, or 500 permissions to every user in your system. Stop Using Roles For Authorization Checks When it comes time to check authorization rules, we often see the role being checked. For example, look at the MSDN documentation for ASP.NET MVC’s AuthorizeAttribute. The Authorize attribute lets you indicate that authorization is restricted to predefined roles or to individual users. What’s Wrong With Role-Based Authorization Checks? Documentation Or in ruby:

Жизненный цикл Request в MVC 3 Framework приложении Любой разработчик знает, что URL в маршрутизации MVC играет ключевую роль. Как известно, существует стандартная маршрутизация: routes.MapRoute( "Default", "{controller}/{action}/{id}", new { controller = "Home", action = "Index", id = UrlParameter.Optional ); Она представляет собой правило по которым выбираются маршруты. routes.MapRoute( "Default", "{controller}/{action}/{*url}", new { controller = "Content", action = "Home", url = UrlParameter.Optional }); Это правило выделяет Action и Controller, а остальную часть присваивает переменной url. Для создания большинства приложений этих знаний хватает. 1. Для чего это может понадобиться? a. public class CustomRouteHandler : MvcRouteHandler { protected override IHttpHandler GetHttpHandler(RequestContext requestContext) { return base.GetHttpHandler(requestContext); } } Инициализировать CustomRouteHandler нужно в классе Global методе Application_Start() 2. 3. Зарегистрировать в контроллере его можно инициализировав в конструкторе. 4.

Exception Handling in ASP.NET MVC Index Introduction Exception handling is a serious matter in any application, whether it's web or desktop. Implementing a proper exception handling is important in any application. In most cases once we catch the exception we have to log the exception details to database or text file and show a friendly message to the user. In ASP.NET applications, error handling is done mostly in two ways: at local level using try-catch blocks and at global level using application events. In this article, we will learn about the HandleError filter and discuss about the different exception handling mechanisms that will fit to an MVC application. HandleError Attribute Exception filters The exception filters are attributes that can be applied over an action or a controller or even at a global level. All the exception filters implements the IExceptionFilter interface. Listing 1. The HandleErrorAttribute is the default implementation of the IExceptionFilter. Listing 2. What the HandleError filter does? Error View

ASP.NET MVC Custom Error 404 (Not Found) Page | Блог NеRадивого ECOномиста I recently had to create a custom 404 Error Page in my ASP.NET MVC project. I thought I would do that in minutes. 6 hours later I found 2 ways to solving the problem. There are global filters in ASP.NET MVC 3 that I’m working with. They are already used in a new page template for rendering a custom error page (using HandleErrorAttribute). It’s wonderful except for the fact it can’t handle the 404 (Page Not Found) error. So I had to go further looking for some other nice solution. If you feel well with redirections or use IIS 7 or higher - built-in method.In other cases - a complicated solution. ASP.NET platform lets show a custom error page by a simple change in Web.config file. When a 404 Error occurs the user will be redirected to yoursite.com/Errors/Error404/? It’s not really nice and handy (you can’t then correct the misstyped url), and also it’s bad for SEO – an article at habr.ru. This approach may be a bit improved by adding redirectMode="ResponseRewrite" to customErrors: Conclusion

Related: