IBlog

July 1, 2011

HTTP 404 while asp.net web forms and spring.net project

Filed under: ASP.NET, Spring.NET — Himanshu @ 3:32 pm

While doing some refactoring with the project, I suddenly start getting HTTP 404, and that to for all pages that exists and was working few minutes back. I was amused to get the error, with the fact that pages existed, I could see them and feel them! After a while, I noticed that I have deleted a existing .aspx file from project which I forgot to remove from spring.net configuration file.

If you add any .aspx in Spring.Net config that do not exists, Spring.NET brings you to yellow screen with appropriate message. But not when you delete one from project and forget to remove from config file! At least not all the time.

January 5, 2011

ASP.NET Postback on table row click

Filed under: .NET, ASP.NET — Himanshu @ 8:34 am

When you need to go back to the server for further processing on clicking of a html element, for example on html table row click, below code may help you provide such functioning in ASP.NET.

Well, actually to allow control to support bubbling of the events, and allow user of the control to specify CommandName and CommandArgument while being used in template controls,  there is some extract effort, essentially will need to implement IButtonControl. Let’s see the code below that I have implemented to provide function of  selecting row when clicked on it.

   1:  [ToolboxData("<{0}:ListViewRowClickCommand  CommandName=\"Select\" runat=\"server\"></{0}:ListViewRowClickCommand>")]
   2:  public class ListViewRowClickCommand : HtmlTableRow, IButtonControl, IPostBackEventHandler
   3:  {
   4:      public bool DisableCommand { get; set; }
   5:      protected override void Render(HtmlTextWriter writer)
   6:      {
   7:          writer.WriteBeginTag("tr");
   8:          if (ID != null)
   9:              writer.WriteAttribute("id", ClientID);
  10:          if (!DesignMode)
  11:          {
  12:              if (!DisableCommand)
  13:                  writer.WriteAttribute("onclick", "javascript:" +
  14:                      Page.ClientScript.GetPostBackEventReference(this, CommandArgument));
  15:          }
  16:          Attributes.Render(writer);
  17:          writer.Write(HtmlTextWriter.TagRightChar);
  18:  
  19:          RenderChildren(writer);
  20:          writer.WriteEndTag("tr");
  21:      }
  22:  
  23:      public bool CausesValidation
  24:      {
  25:          get { return (bool)(ViewState["CausesValidation"] ?? true); }
  26:          set { ViewState["CausesValidation"] = value; }
  27:      }
  28:  
  29:      public string CommandArgument
  30:      {
  31:          get { return (string)ViewState["CommandArgument"]; }
  32:          set { ViewState["CommandArgument"] = value; }
  33:      }
  34:  
  35:      public string CommandName
  36:      {
  37:          get { return (string)ViewState["CommandName"]; }
  38:          set { ViewState["CommandName"] = value; }
  39:      }
  40:  
  41:      public string PostBackUrl
  42:      {
  43:          get { return (string)ViewState["PostBackUrl"]; }
  44:          set { ViewState["PostBackUrl"] = value; }
  45:      }
  46:  
  47:      public string ValidationGroup
  48:      {
  49:          get { return (string)ViewState["ValidationGroup"]; }
  50:          set { ViewState["ValidationGroup"] = value; }
  51:      }
  52:  
  53:      public event EventHandler Click;
  54:      public event CommandEventHandler Command;
  55:  
  56:      public void RaisePostBackEvent(string eventArgument)
  57:      {
  58:          if (CausesValidation)
  59:          {
  60:              if (Page.IsPostBack)
  61:                  Page.Validate();
  62:              if (!Page.IsValid)
  63:                  return;
  64:          }
  65:  
  66:          OnClick(EventArgs.Empty);
  67:          OnCommand(new CommandEventArgs(CommandName, CommandArgument));
  68:      }
  69:  
  70:      protected virtual void OnCommand(CommandEventArgs eventArgs)
  71:      {
  72:          if (Command != null)
  73:              Command(this, eventArgs);
  74:  
  75:          RaiseBubbleEvent(this, eventArgs);
  76:      }
  77:  
  78:      protected virtual void OnClick(EventArgs eventArgs)
  79:      {
  80:          if (Click != null)
  81:              Click(this, eventArgs);
  82:      }
  83:  }

Above control can be used as below:

   1:  ...
   2:  
   3:  <asp:ListView ID="listViewOfSomething" runat="server" OnSelectedIndexChanging="OnSelectedIndexChanging">
   4:      <LayoutTemplate>
   5:          <table id="htmlTableOfSomething" >
   6:              <tbody>
   7:                  <asp:PlaceHolder ID="itemPlaceholder" runat="server" />
   8:              </tbody>
   9:          </table>
  10:      </LayoutTemplate>
  11:      <ItemTemplate>
  12:          <vdd:ListViewRowClickCommand ID="ListViewRowClickCommand" runat="server"
  13:              CommandName="Select" Class="SomeCssClassForRow" >
  14:              <td class="CssClassForColumn">
  15:  
  16:  ...

Feel free to put comments in case if things are not clear.

May 15, 2009

Sending email message having embedded image (.NET)

Filed under: .NET, ASP.NET, Programming — Himanshu @ 5:16 am

Does your .net application send email messages? Does it send formatted email messages? I think applications should always send formatted email messages instead of text only. (Are asking why? Simple, formatted messages are much more capable, presentable, …).

Counter argument: Some user uses email client that are not capable to show HTML messages. Or someone is doing it for security purpose. Okay, I agree, then send both the views; text view as well as HTML view. Using .NET, one can send multi view email messages, depending on email client settings and/or capability, client is expected to pick the right view and shows that to the user.

Next question is, say we have decided to send email in html and text view, can we send images and style sheets embedded with email? Answers is yes. Here is how one can send multi-part email message using .net libraries that has embedded image.

Here goes the first step, create MailMessage object and setup that with appropriate values

   1: var from = new MailAddress("admin@objectpattern.com", "Himanshu");
   2: var to = new MailAddress("himanshu@objectpattern.net");
   3: var message = new MailMessage(from, to) { Subject = "Hi from ObjectPattern"};

next step changes. As we want to have two views – text and html, we will have to create email body differently.

in these lines of code, there are certain important points

   1: //creating text view
   2: var textViewContent = "Test content for text view";
   3: var textView = AlternateView.CreateAlternateViewFromString(textViewContent, Encoding.UTF8,
   4:                                                            MediaTypeNames.Text.Plain);
   5: //creating html view 
   6: var htmlViewContent = "

Html content containing image logo

Thanks,
ObjectPattern
logo";
   7: var htmlView = AlternateView.CreateAlternateViewFromString(htmlViewContent, Encoding.UTF8,
   8:                                                            MediaTypeNames.Text.Html);

that I would like to bring in to your notice.

  • Notice that we are not assigning Body property of MailMessage type
  • While creating view, we are specifying media type name as either plain text or html text, it can also be rich text.
  • We have created an img tag that referring to source as ‘cid:logo.png’

okay now how we will embed image into email message? That’s easy as well:

   1: var logo = new LinkedResource("images/logo.png", MediaTypeNames.Image.Jpeg) {ContentId = "logo.png"};
   2: htmlView.LinkedResources.Add(logo);

here in first line, first parameter of constructor (“image/logo.png” text) specifies the path of the image file. One can also supply image content as stream if its not coming directly from the file. Now remember, in above section, we had specified the src attribute of img tag, that should match with content id. Else image will not be shown correctly in email client. Also notice that we are adding this image to html view.

We are almost done now. All we need to do now is to add views to message object and sending using SMTP client.

   1: message.AlternateViews.Add(textView);
   2: message.AlternateViews.Add(htmlView);
   3:

August 5, 2008

Paging of SQL Server records

Filed under: .NET, ASP.NET, Sql Server 2005 — Himanshu @ 6:29 am

In one of my ASP.NET, SQL Server project, we were expected to provide paging in the ASP.NET GridView. Microsoft’s very common sample will do this using Dataset filled with all records. If someone is doing GridView paging, s/he is doing it not waste server’s or client’s precious resources, Isn’t it?

To me, it make more sense to do paging of records being fetched in server memory along with view paging. What if table in question has more then 100,000 (1 lack) records?

Digging a bit further, I found a resource which explains how to do paging of records being sent from stored procedure. But it was expecting to have auto identity as primary key in the table. And we were so fortunate that we couldn’t have db design such that we can afford to have auto identity primary key, and so that solution to the paging problem. On doing some more finding, we all agreed to a solution that is described below. It’s not fully optimized, as it do not have any optimization for SQL Server to prepare result sets. But worked for our need in specific project as even in 100,000 records it was working very fast.

In our solution, stored procedure that will fetch records from table and return to caller will needs to have two addition parameters, @RowIndexFrom and @RowIndexTo

Getting customers by page will look like following,

CREATE PROCEDURE [dbo].[GetCustomersPage]
(
    @RowIndexFrom int,
    @RowIndexTo int
)
AS
BEGIN
    SET NOCOUNT ON;
 
    WITH IndexedCustomers AS
    (
        SELECT
            ROW_NUMBER() OVER (ORDER BY Id) AS rowIndex,
            Customers.*
        FROM
            Customers
    )
    SELECT * FROM IndexedCustomers WHERE rowIndex BETWEEN @RowIndexFrom AND @RowIndexTo
 
    SELECT COUNT(*)
    FROM
        Customers
END
GO

 

The stored procedure returns two result set, first will be records for given page (defined by different between @RowIndexFrom and @RowIndexTo parameters). And the second result set will give total number of records for give query. Second result set will help preparing pages list. So, if first page needs to be retrieved of page size 10, parameter values should be 1 and 10 respectively.

Powered by WordPress