Silverlight : Binding a WebContext User Property to a DomainQueryParameter
In Domain Data Source if you want to send a parameter to the Query the simplest way to do this would be
{Binding Path=User.Proper, Source={StaticResource WebContext}}Example:
<riacontrols:domaindatasource AutoLoad="True" x:Name="dataSource" LoadSize="20" QueryName="GetClients" LoadingData="dataSource_LoadingData" LoadedData="dataSource_LoadedData" SubmittedChanges="dataSource_SubmittedChanges" > </riacontrols:domaindatasource><riacontrols:domaindatasource .DomainContext> <datasouce:portalcontext /> </riacontrols:domaindatasource> <riacontrols:domaindatasource .FilterDescriptors> <riacontrols:filterdescriptor PropertyPath="ClientName" Operator="Contains" Value="{Binding ElementName=TextFilter,Path=Text}" IsCaseSensitive="False"> </riacontrols:filterdescriptor> </riacontrols:domaindatasource> <riacontrols:domaindatasource .QueryParameters> <riacontrols:parameter ParameterName="AccessLevel" Value="{Binding Path=User.DataAccessLevel, Source={StaticResource WebContext}}"/> </riacontrols:domaindatasource>
Using Linq to Find a Control
I think Every one has one time or the other tried to find a control by looping over and find the required control, but we can use Linq to do the same thing.
public static class PageExtensions { public static IEnumerable<control> All(this ControlCollection controls) { foreach (Control control in controls) { foreach (Control grandChild in control.Controls.All()) yield return grandChild; yield return control; } } } </control>
Then you can use as a Linq Expression
var ctrls = controls.All().Where(c => c.GetType() == typeof(Button));
Mix and Mash Asp.net MVC with Webforms
A lot of people including me wanted to to get on the bandwagon of ASP.net MVC, but the main problem is we do not always get to start new projects and there is always a timeline hanging. I will not talk about the benefits of MVC Pattern as most of us already aware of it, But for an ASP.net Developer where everything is tied up in Webforms this may seem difficult, but once you start taking advantages of this pattern, the usefulness becomes obvious, me having worked on Rails and PHP frameworks such as CodeIgnitor and CakePHP, It was never a question of If, but when, and the best way to begin would be use your existing skills with webforms and start bringin in MVC Pattern, and before you know it you can be completely taking the benefits out of both worlds.
Webforms with MVC
If you are starting with a new project its really simple, start of with a new MVC Project in Visual Studio Add a New Webform run it and thats it no configuration required, the reason is that because MVC Framework is built on top of same ASP.net platform, it runs and the reason why the routing doesn’t try and hijack this request is because of the way it works, if the physical file of the request exists the request is always made to the aspx file, for better performance and save disk query on each .aspx request you can also add the following line in your global.asax
public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.IgnoreRoute("{resource}.aspx/{*pathInfo}"); routes.MapRoute( "Default", // Route name "{controller}/{action}/{id}", // URL with parameters new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults ); }
MVC with Webforms
But most of us never start with new projects right ?, so you have to do a bit more work, Add the following as Reference to your Web Application

Now Update your web.config to reflect
<system .web> <compilation debug="true" targetFramework="4.0"> <assemblies> <add assembly="System.Web.Abstractions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" /> <add assembly="System.Web.Routing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" /> <add assembly="System.Web.Mvc, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" /> </assemblies> </compilation> <pages> <namespaces> <add namespace="System.Web.Mvc" /> <add namespace="System.Web.Mvc.Ajax" /> <add namespace="System.Web.Mvc.Html" /> <add namespace="System.Web.Routing" /> </namespaces> </pages> ...... </system>
Add the following code to global.asax
public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.IgnoreRoute("{resource}.aspx/{*pathInfo}"); routes.MapRoute( "Default", // Route name "{controller}/{action}/{id}", // URL with parameters new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults ); } void Application_Start(object sender, EventArgs e) { AreaRegistration.RegisterAllAreas(); RegisterRoutes(RouteTable.Routes); }
Now Add the Controllers, Views, Folders to the root of application and you are good to go:
Home Controller – /Controllers/HomeControllers.cs
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace WebApp.Test.Controllers { [HandleError] public class HomeController : Controller { public ActionResult Index() { ViewData["Message"] = "Welcome to ASP.NET MVC!"; return View(); } } }
View – /Views/Home/Index.aspx
< %@ Page Language="C#" MasterPageFile="~/Site.Master" Inherits="System.Web.Mvc.ViewPage" %> <asp:content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server"> </asp:content> <asp:content ID="Content2" ContentPlaceHolderID="MainContent" runat="server"> <h2>< %: ViewData["Message"] %></h2> <p> To learn more about ASP.NET MVC visit <a href="http://asp.net/mvc" title="ASP.NET MVC Website">http://asp.net/mvc</a>. </p> </asp:content>
You can even use the same Master Page


P.S: The VS Project doesn’t support integrated way of creating Views and Controllers in this method
Use Debug output window to monitor SQL generated by LINQ2SQL
In all the examples out there to see the SQL generated by a LINQ2SQL query console.out is used, but to monitor the SQL in a debug window we need to write a special text writer implementation
using System.IO; using System.Text; using System.Diagnostics; using System.Globalization; using System; namespace nj.Diagnostics { /// <summary> /// Implements a <see cref="TextWriter"/> for writing information to the debugger log. /// </summary> /// <seealso cref="Debugger.Log"/> public class DebuggerWriter : TextWriter { private bool isOpen; private static UnicodeEncoding encoding; private readonly int level; private readonly string category; /// <summary> /// Initializes a new instance of the <see cref="DebuggerWriter"/> class. /// </summary> public DebuggerWriter() : this(0, Debugger.DefaultCategory) { } /// <summary> /// Initializes a new instance of the <see cref="DebuggerWriter"/> class with the specified level and category. /// </summary> /// <param name="level">A description of the importance of the messages.</param> /// <param name="category">The category of the messages.</param> public DebuggerWriter(int level, string category) : this(level, category, CultureInfo.CurrentCulture) { } /// <summary> /// Initializes a new instance of the <see cref="DebuggerWriter"/> class with the specified level, category and format provider. /// </summary> /// <param name="level">A description of the importance of the messages.</param> /// <param name="category">The category of the messages.</param> /// <param name="formatProvider">An <see cref="IFormatProvider"/> object that controls formatting.</param> public DebuggerWriter(int level, string category, IFormatProvider formatProvider) : base(formatProvider) { this.level = level; this.category = category; this.isOpen = true; } protected override void Dispose(bool disposing) { isOpen = false; base.Dispose(disposing); } public override void Write(char value) { if (!isOpen) { throw new ObjectDisposedException(null); } Debugger.Log(level, category, value.ToString()); } public override void Write(string value) { if (!isOpen) { throw new ObjectDisposedException(null); } if (value != null) { Debugger.Log(level, category, value); } } public override void Write(char[] buffer, int index, int count) { if (!isOpen) { throw new ObjectDisposedException(null); } if (buffer == null || index < 0 || count < 0 || buffer.Length - index < count) { base.Write(buffer, index, count); // delegate throw exception to base class } Debugger.Log(level, category, new string(buffer, index, count)); } public override Encoding Encoding { get { if (encoding == null) { encoding = new UnicodeEncoding(false, false); } return encoding; } } public int Level { get { return level; } } public string Category { get { return category; } } } }
The you can use
datacontext.log = new DebuggerWriter();
Forms Authentication fails even when browser accepts cookies
While using Forms authentication in ASP.net
<forms name=".ASPXAUTH" loginUrl="login.aspx" defaultUrl="Default.aspx" protection="All" timeout="30" path="/" requireSSL="false" slidingExpiration="true" cookieless="AutoDetect" domain="" enableCrossAppRedirects="false"> <credentials passwordFormat="SHA1" /> </forms>
please remeber to set path = “/” or else the cookie based authentication fails, I am yet to figure out why this is happening but atleast this solves the problem.
Cascade Delete with Linq2SQL
Consider this, you have Invoice and Invioce details in 2 tables and the details are referenced by InvoiceId, What happens to Invoice Details once you delete the invoice ?, In SQL atleast you can do cascade delete and also set the value to null, but most real life programs would want to delete the details, Linq2SQL by default tries to set a null value which in most cases fails, and there is no visual way to set this the only way to do this is to do some manual xml editing.
Right click and open the .dbml file with the XML Editor and then navigate to the table for which you want to do this, then look for the relation which references the parent table
<association Name="...." Member="...." ThisKey="...." OtherKey="...." Type="...." IsForeignKey="true" />Now add DeleteOnNull=”true” to this association so this behaves as expected
<association Name="...." Member="...." ThisKey="...." OtherKey="...." Type="...." IsForeignKey="true" DeleteOnNull="true" />Use Linq with SQL CE
If you have tried this before you might have run into an error which says that the database is unsupported, Baisically LINQ2SQL in just language extension which converts into plain old SQL, so in theory it should work with any database, but SQL CE supports the same SQL as SQL Server This is not because Linq2SQL doesn’t support SQL CE but VS ORM designer doesn’t support that, but there is a way in which you can generate the Linq2SQL class ,
This is by using the “SQLMetal.exe”, this utility helps you in generating the Linq2SQL classes,
To do this simply create a batch file with the following command in the SQLCE database directory
"C:Program FilesMicrosoft SDKsWindowsv6.0abinsqlmetal.exe" /pluralize /dbml:DBMLNAME.dbml DATAFILENAME.sdf
This will create the DBML which you can then edit and manipulate in the VS ORM designer, and since the datacontext will not have connection string in it, while initializing the data context you can use something like
DataContext db = new DataContext (@"Data Source=DataBase.sdf");
Convert (Cast) between 2 custom classes
If you have ever wanted to convert (cast) between two custom classes, there is a simple way to do it,
public partial class xxxFinalClass { public static explicit operator xxxFinalClass(xxxOriginalClass data) { var temp = new xxxFinalClass(); //do Conversion return temp; } }
Now you can use like
xxxFinalClass newobj = (xxxFinalClass)oldobj;
LINQ2SQL RAD with confidence
If you are like me who also does have to done some rapid prototyping and application development, you know how painstaking it is to do setup each wire for even a simple application to work, and you will be working so rapidly that you would have forgotten the column names you have entered in db few minutes ago, that fact aside you would still require a large prieces of code which would actually constitute the middle tier of application, but the problem is in RAD you do need a top notch middle tier which would cover all the aspects required, then what ? and add to that the fact that you are so used to working with objects that you have even forgotten how to retrive data just using code or you find the whole connection – adapter – dataset thing too outdated and too much work just to retrive one row from db.
Now we know what a middle teir is , its nothing but an ORM which maps objects to data along with addtional functions to manipulate that data, for this there exists good amount of code generators which based on your database would generate all code required which would constitute the core of middle tier, but i always found them to be too cumberome ( may be i am too lazy) , now may be some year and a half ago , i was working on a project which extensively used LINQ for queying objects, instead of writing functions for each thing, till then LINQ has become second nature, and i wonder how i used to to do this when LINQ was not around, same time i started looking web for LINQ and i saw something about DLINQ which is now reffered to as LINQ2SQL, LINQ2SQL does what we need to do the hard way, wire up. Just create a new LINQ2SQL class in your project and drag the tables from Server Explorer and voila , you have your midddle tier ready (well not exactly) , it creates classes for each of the table in the db along with associations for relations , (eg : If i have a students table in it creates a student class with each column in student as a property, and if you have something like SectionId in Student which links to the section table you can access the linked section by just using Student.Section). Everything becomes so simple from here on, atleast for RAD, It also creates functions for SPs,
The only problem i have with this till date is it works only with SQL Server (I have been able to get it working with SQLCE – If this only worked with MySQL) and some things like serialization doesn’t happen the way i want it to , but anyway this is a tool which you have to use once to get know its usefullness.
My latest Work on WPF
WPF has been here for quite a while now and i done some basic projects on wpf, but for the last two months i had the opportunity to completely work on WPF, not just WPF but also used Linq2SQL as the base for the complete application, wet my hands with ADO.net Entity Model and lot of work in Expression Blend,
The software was for KPCC and it an complete automation and information management system for them, I will not reveal much more, but a few screens which are not part of the NDA have been posted here,


