Asp.net ReportViewer : Access Remote Server Report with Credentials
If you want to work with remote SSRS report while debugging your asp.net application you would want to authenticate with the remote server, you cannot use asp.net impersonation as this would actually make the entire application run under impersonation so to solve this we can use impersonation for the report viewer only to do this :
#if (DEBUG) this.ReportViewer1.ServerReport.ReportServerCredentials = new ReportServerCredentials("username", "password","domain"); #endif
and a ReportServerCredentials class
public class ReportServerCredentials : IReportServerCredentials { private string _userName; private string _password; private string _domain; public ReportServerCredentials(string userName, string password, string domain) { _userName = userName; _password = password; _domain = domain; } public System.Security.Principal.WindowsIdentity ImpersonationUser { get { return null; } } public System.Net.ICredentials NetworkCredentials { get { return new System.Net.NetworkCredential(_userName, _password, _domain); } } bool IReportServerCredentials.GetFormsCredentials(out Cookie authCookie, out string userName, out string password, out string authority) { authCookie = null; userName = _userName; password = _password authority = _domain; return false; } }
Asp.net Dyanamic Data : A leap for RAD
I have always basically forms over data for the longest period of time (LOB Apps) and most of the time its the same thing over and over again, Setup Database, create scaffolding forms for all the master tables and then move to the next steps, but wait there should be an easy way to this, In the MVC framework you can generate pages based on the model, but there are still a few things that you should wire up manually, enter dynamic data template and this feels like a magical unicorn at the beginning and once you dig deep into into it, its just beautiful, and will save a lot of steps for you.
So lets begin
You have 2 options a Linq2SQL based Application or Entity Framework based application and its just a matter of your preference, Then just create a data Context, This is what i did just to go through and this is not a perfect data model but you can get the point, just create your data context you are almost good to go
then you ll have to uncomment a single line in global.asax
DefaultModel.RegisterContext(typeof(DataModel), new ContextConfiguration() { ScaffoldAllTables = true });
Here the default property for ScaffoldAllTables is false, change it to true if you want scaffolding on all tables, (for now)
and you are done
And this is what you get , Projects and Tasks along with filter and foreign key correctly linked
Now lets customize this a little bit, we would never want all the scaffold all tables and also we would need some validation and hearer names to be changed a bit.
To Scaffold specific tables we will have to mark the tables with [ScaffoldTable(true)] property, and as the Datacontext generated classes are partials we can extend the classes in a seperate file also to provide metadata we will use data annotations and mark all the necessary fields with the required information
namespace TestApplication { [ScaffoldTable(true)] [MetadataType(typeof(Attributes.Project))] public partial class Project { } [ScaffoldTable(true)] [MetadataType(typeof(Attributes.Task))] public partial class Task { } namespace Attributes { public partial class Project { [Required] [StringLength(50, MinimumLength = 5)] [Display(Name = "Project Name")] public string ProjectName { get; set; } } public partial class Task { [Required] [Display(Name = "Project", Order = 0)] public Project Project { get; set; } [Required] [Display(Name = "Employee Code", Order = 1, GroupName = "Employee")] public string EmployeeCode { get; set; } [Required] [Display(Name = "Track Date", Order = 2, GroupName = "Date & Time")] public DateTime TrackDate { get; set; } [Required] [Display(Name = "Hours", Order = 3, GroupName = "Date & Time")] public decimal TaskHours { get; set; } [Required] [Display(Name = "Task Descriprion", Order = 4, GroupName = "Information")] public string TaskDescriprion { get; set; } } } }
The modified task screen would look like
And this is just the beginning we can do a lot more stuff as all the controls can be customized, I will post about grouping and also customizing display and edit controls in a subsequent blog.
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
Using a ASP.net Grid view using code
We have all used grid view along with data sources but some time you need to to that from code, the problem is most of us do not know how to use this from code, but Its not that difficult to that. Here’s a simple way to do that.
A Simple gridĀ First column is a readonly templated field, second one a readonly bound field and third a templated entry field. At the Edit the edit command Field
<asp:GridView ID="GridView1" runat="server" CssSelectorClass="PrettyGridView" PageSize="50" AllowSorting="True" AutoGenerateColumns="False" EnableSortingAndPagingCallbacks="True"> <columns> <asp:templatefield HeaderText="Center Id" SortExpression="center_Id"> <edititemtemplate> <asp:Label ID="Label10" runat="server" Text='<%# Eval("bind1") %>'/> </edititemtemplate> <itemtemplate> <asp:Label ID="Label10" runat="server" Text='<%# Bind("bind1") %>'/> </itemtemplate> </asp:templatefield> <asp:boundfield DataField="City_Name" HeaderText="City Name" ReadOnly="True" SortExpression="City_Name"></asp:boundfield> <asp:templatefield HeaderText="Rate"> <edititemtemplate> <asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("bind2") %>'/> </edititemtemplate> <itemtemplate> <asp:Label ID="Label1" runat="server" Text='<%# Bind("bind2") %>'/> </itemtemplate> </asp:templatefield> <asp:commandfield ShowEditButton="True"></asp:commandfield> </columns> </asp:GridView>
First Write a Function for loading data which will be reused on every action. I call it BindData()
Private Sub BindData() conn = New OleDbConnection(GetJetConnectionString) adap = New OleDbDataAdapter("Custom SQL Query", conn) Dim datatable1 As New DataTable adap.Fill(datatable1) dataset1 = New DataSet dataset1.Tables.Add(datatable1) Me.GridView1.DataSource = dataset1 Me.GridView1.DataBind() End Sub
Now since the gridview is binded from code we have to handle all its events. So When the user clicks on edit. Here I have done two thingsĀ one is enable editing mode, then I store the data of textbox in a viewstate, so that it can be accessed later when updating, please remember that the regular method of e.OldValues and e.NewValues Will not work because we have to do that manually, (which can be done, but for our purposes we will use viewstate)
Protected Sub GridView1_RowEditing(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewEditEventArgs) Handles GridView1.RowEditing GridView1.EditIndex = e.NewEditIndex BindData() Dim row As GridViewRow = GridView1.Rows(GridView1.EditIndex) If row IsNot Nothing Then Dim t As TextBox = TryCast(row.FindControl("TextBox1"), TextBox) If t IsNot Nothing Then ViewState("OldRate") = t.Text End If End If End Sub
Now for the cancel part
Protected Sub GridView1_RowCancelingEdit(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCancelEditEventArgs) Handles GridView1.RowCancelingEdit GridView1.EditIndex = -1 BindData() End Sub
Now for the update part. First new value is found out, if it is blank nothing is done, if old value does not Exist INSERT command is used if old value does exist UPDATE command is used. Here I did a Simple SQL execution but I think you will figure out a better way
Protected Sub GridView1_RowUpdating(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewUpdateEventArgs) Handles GridView1.RowUpdating Dim new_rate, old_rate As String old_rate = ViewState("OldRate") Dim row As GridViewRow = GridView1.Rows(e.RowIndex) If row IsNot Nothing Then Dim t As TextBox = TryCast(row.FindControl("TextBox1"), TextBox) If t IsNot Nothing Then new_rate = t.Text If new_rate = "" Then GridView1.EditIndex = -1 BindData() Exit Sub End If If new_rate = old_rate Then GridView1.EditIndex = -1 BindData() Exit Sub Else Dim label1 As Label = TryCast(row.FindControl("label10"), Label) Dim center_id As String = label1.Text Dim conn As New OleDbConnection(ConnectionString) Dim cmd As New OleDbCommand cmd.Connection = conn cmd.CommandType = CommandType.Text Dim SQL As String If old_rate = "" Then SQL = "INSERT INTO QUERY" Else SQL = "UPDATE QUERY" End If cmd.CommandText = SQL conn.Open() cmd.ExecuteNonQuery() conn.Close() GridView1.EditIndex = -1 BindData() End If Else GridView1.EditIndex = -1 BindData() End If End If End Sub






