Monday, April 5, 2010

URL Rewriting with IIS7

full article is at this address http://weblogs.asp.net/scottgu/archive/2007/02/26/tip-trick-url-rewriting-with-asp-net.aspx

Approach 3: Using an HttpModule to Perform Extension-Less URL Rewriting with IIS7
The above HttpModule approach works great for scenarios where the URL you are re-writing has a .aspx extension, or another file extension that is configured to be processed by ASP.NET.  When you do this no custom server configuration is required - you can just copy your web application up to a remote server and it will work fine.
There are times, though, when you want the URL to re-write to either have a non-ASP.NET file extension (for example: .jpg, .gif, or .htm) or no file-extension at all.  For example, we might want to expose these URLs as our public catalog pages (note they have no .aspx extension):

With IIS5 and IIS6, processing the above URLs using ASP.NET is not super easy.  IIS 5/6 makes it hard to perform URL rewriting on these types of URLs within ISAPI Extensions (which is how ASP.NET is implemented). Instead you need to perform the rewriting earlier in the IIS request pipeline using an ISAPI Filter.  I'll show how to-do this on IIS5/6 in the Approach 4 section below.
The good news, though, is that IIS 7.0 makes handling these types of scenarios super easy.  You can now have an HttpModule execute anywhere within the IIS request pipeline - which means you can use the URLRewriter module above to process and rewrite extension-less URLs (or even URLs with a .asp, .php, or .jsp extension).  Below is how you would configure this with IIS7:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>

  
<configSections>
    
<section name="rewriter"
             requirePermission
="false"
             type
="Intelligencia.UrlRewriter.Configuration.RewriterConfigurationSectionHandler, Intelligencia.UrlRewriter" />
  configSections>
 
  
<system.web>
     
    
<httpModules>
      
<add name="UrlRewriter" type="Intelligencia.UrlRewriter.RewriterHttpModule, Intelligencia.UrlRewriter" />
    httpModules>
   
  
system.web>

  
<system.webServer>

    
<modules runAllManagedModulesForAllRequests="true">
      
<add name="UrlRewriter" type="Intelligencia.UrlRewriter.RewriterHttpModule" />
    modules>

    
<validation validateIntegratedModeConfiguration="false" />

  system.webServer>

  
<rewriter>
    
<rewrite url="~/products/(.+)" to="~/products.aspx?category=$1" />
  rewriter>
  
configuration>
Note the "runAllManagedModulesForAllRequests" attribute that is set to true on the section within .  This will ensure that the UrlRewriter.Net module from Intelligencia, which was written before IIS7 shipped, will be called and have a chance to re-write all URL requests to the server (including for folders).  What is really cool about the above web.config file is that:
1) It will work on any IIS 7.0 machine.  You don't need an administrator to enable anything on the remote host.  It will also work in medium trust shared hosting scenarios.
2) Because I've configured the UrlRewriter in both the and IIS7 section, I can use the same URL Rewriting rules for both the built-in VS web-server (aka Cassini) as well as on IIS7.  Both fully support extension-less URLRewriting.  This makes testing and development really easy.
IIS 7.0 server will ship later this year as part of Windows Longhorn Server, and will support a go-live license with the Beta3 release in a few weeks.  Because of all the new hosting features that have been added to IIS7, we expect hosters to start aggressively offering IIS7 accounts relatively quickly - which means you should be able to start to take advantage of the above extension-less rewriting support soon.  We'll also be shipping a Microsoft supported URL-Rewriting module in the IIS7 RTM timeframe that will be available for free as well that you'll be able to use on IIS7, and which will provide nice support for advanced re-writing scenarios for all content on your web-server.
Sample Download: A sample application that I've built that shows using this extension-less URL technique with IIS7 and the UrlRewriter.Net module can be downloaded here

Sunday, April 4, 2010

Linq to SQL a very good tutorial by scott

a very good tutorial series by scott from microsoft.

http://weblogs.asp.net/scottgu/archive/2007/08/16/linq-to-sql-part-6-retrieving-data-using-stored-procedures.aspx

Saturday, April 3, 2010

sql date time difference calculate

Transact-SQL Reference (SQL Server 2000)
DATEDIFF
Returns the number of date and time boundaries crossed between two specified dates.
Syntax
DATEDIFF ( datepart ,startdate ,enddate )
Arguments
datepart
Is the parameter that specifies on which part of the date to calculate the difference. The table lists dateparts and abbreviations recognized by Microsoft® SQL Server™.
DatepartAbbreviations
Yearyy, yyyy
quarterqq, q
Monthmm, m
dayofyeardy, y
Daydd, d
Weekwk, ww
Hourhh
minutemi, n
secondss, s
millisecondms

startdate
Is the beginning date for the calculation. startdate is an expression that returns a datetime or smalldatetime value, or a character string in a date format.
Because smalldatetime is accurate only to the minute, when a smalldatetime value is used, seconds and milliseconds are always 0.
If you specify only the last two digits of the year, values less than or equal to the last two digits of the value of the two digit year cutoff configuration option are in the same century as the cutoff year. Values greater than the last two digits of the value of this option are in the century that precedes the cutoff year. For example, if the two digit year cutoff is 2049 (default), 49 is interpreted as 2049 and 2050 is interpreted as 1950. To avoid ambiguity, use four-digit years.
For more information about specifying time values, see Time Formats. For more information about specifying dates, see datetime and smalldatetime.
enddate
Is the ending date for the calculation. enddate is an expression that returns a datetime or smalldatetime value, or a character string in a date format.
Return Types
integer
Remarks
startdate is subtracted from enddate. If startdate is later than enddate, a negative value is returned.
DATEDIFF produces an error if the result is out of range for integer values. For milliseconds, the maximum number is 24 days, 20 hours, 31 minutes and 23.647 seconds. For seconds, the maximum number is 68 years.
The method of counting crossed boundaries such as minutes, seconds, and milliseconds makes the result given by DATEDIFF consistent across all data types. The result is a signed integer value equal to the number of datepart boundaries crossed between the first and second date. For example, the number of weeks between Sunday, January 4, and Sunday, January 11, is 1.
Examples
This example determines the difference in days between the current date and the publication date for titles in the pubs database.
USE pubs
GO
SELECT DATEDIFF(day, pubdate, getdate()) AS no_of_days
FROM titles
GO
See Also
CAST and CONVERT
Data Types
Date and Time Functions

linq dynamic query

If you've been stuggling to create a dynamic LINQ query you're not alone. Thanks to some research, hard work and a smart co-worker I was able to implement some cool dynamic LINQ code in our help desk application. 
In our helpdesk we have filter screens that look like this: 


Creating a LINQ query in challenging because we don't know ahead of time which fields the user will complete. They are all optional and without anything selected we want to pull back all tickets. Normally, you'd write a query like this:
 
var ticket = (from t in db.cerberus_Tickets
                          where t.id == id
                          select t).Single();
In the example above we know that the t.id parameter will always be given. So how do you create a query in code when you don't know what fields to include in the WHERE clause ahead of time?
The first key is understanding the LINQ queries are not executed until they are used to enumerate through a collection. This part is key because it means we can create a query and change it in code as long as we don't try to look at the results first.
What we're going to do is create an IQueryable collection that contains all of our Ticket objects and we'll dynamically add our WHERE clause information.  Then we'll create a normal LINQ query that selects all of the matches from our IQueryable collection and handles paging. Because we don't actually enumerate the IQueryable collection that contains all our tickets, it won't actually pull back all of the tickets (which would take forever!). Instead, it will be "merged" with our normally LINQ query at run time when we enumerate over it.
1) Create our LINQ to SQL context objects
 
 
 List<cerberus_Ticket> result = new List<cerberus_Ticket>();
 cerberusDataContext db = new cerberusDataContext(connectionString);
 
2) Create an empty IQueryable collection containing all tickets. Note that this query doesn't actually select everything from the database yet. If it did this would take forever and effectively be filtering the database table in memory. That would not be a good design!
 
 
 IQueryable<cerberus_Ticket> matches = db.cerberus_Tickets;
 
3) Add our WHERE clause information with custom logic to decide if the clauses should be added or not
 
       
 if (this.AgentIdField.Text.Trim().Length > 0)
 {
     matches = matches.Where(a => a.AgentId == criteria.AgentId);
 }
 
 if (this.TicketIdField.Text.Trim().Length > 0)
 {
     matches = matches.Where(a => a.TicketId.Contains(criteria.TicketId));
 }
 
 4) Create a second LINQ query that selects from the first one to sort and page the results.
 
 // calculate start row based on page parameters passed in
 int startRow = (pageNumber - 1) * pageSize;
 
 var output = (from p in matches
               orderby p.DateCreated descending
               select p).Skip(startRow).Take(pageSize).ToList();
 
 
Again, I can't emphasize enough how cool it is that LINQ doesn't query the database until we call the ToList() at the end of the second statement. This delay in execution is the magic that lets us create dynamic queries on the fly.


 
 

linq to sql - 5 minutes overview

http://www.hookedonlinq.com/LINQtoSQL5MinuteOverview.ashx

most of the linq queries are covered in this page.

Binding dropdown to linq business object

first we need to create commonmanager class that holds the business object

public class CommonManager
{

    public static List ListGroups()
    {
        DataClassesDataContext db = new DataClassesDataContext();
        return db.Groups.ToList();
    }

}

 // Binding directly to a LINQ business object.
            this.rcbCommunities.DataSource = CommonManager.ListGroups();
            this.rcbCommunities.DataTextField = "GroupName";
            this.rcbCommunities.DataValueField = "GroupId";
            this.rcbCommunities.DataBind();

CommonManager Class

this is a class that hosts static functions that is used by dropdowns or lists in the UI

public class CommonManager
{

    public static List ListGroups()
    {
        DataClassesDataContext db = new DataClassesDataContext();
        return db.Groups.ToList();
    }

    public static List ListCities()
    {
        DataClassesDataContext db = new DataClassesDataContext();
        return db.Cities.ToList();
    }

    public static List ListBloodGroups()
    {
        DataClassesDataContext db = new DataClassesDataContext();
        return db.BloodGroups.ToList();
    }
}

remove rows from dataset

In order to remove rows from a given dataset and If you really want to use a foreach, copy the rows to an array first:


private void Test()
{
   DataTable dt = new DataTable();
   foreach (DataRow row in ToArray(dt.Rows))
   {
     row.Delete();
   }
}
DataRow[] ToArray(DataRowCollection collection)
{
   DataRow[] result = new DataRow[collection.Count];
   collection.CopyTo(result, 0);
   return result;
}


You can also use a for-next loop...

Charles

http://social.msdn.microsoft.com/Forums/en-US/adodotnetdataproviders/thread/cd5d6063-9226-4f98-9220-7d6b1b53e710

find user record by username

Find user records by their asp.net usernames

 public Donor GetDonorByUserName(string UserName)
    {
        return db.Donors.SingleOrDefault(i => i.UserName == UserName);
    }

Find Distinct from Table

first you need to declare datacontext class

 private DataClassesDataContext db = new DataClassesDataContext();

 public IEnumerable FindDistictCities()
    {
        var s = db.Donors.Select(p => p.City).Distinct();
        return s;
    }

Asp.Net repository class to be used with linq

using System;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
using System.Collections;
using System.Collections.Generic;

///
/// Repository Main File for all Classes of Database
///

///


public class DonorRep
{
    private DataClassesDataContext db = new DataClassesDataContext();

    public IQueryable FindAllDonors()
    {
        return db.Donors;
    }

    public IEnumerable FindDistictCities()
    {
        var s = db.Donors.Select(p => p.City).Distinct();
        return s;
    }

    public Donor GetDonor(int id)
    {
        return db.Donors.SingleOrDefault(i => i.DonorId == id);
    }

    public Donor GetDonorByUserName(string UserName)
    {
        return db.Donors.SingleOrDefault(i => i.UserName == UserName);
    }

    public void Add(Donor donor)
    {
        db.Donors.InsertOnSubmit(donor);
    }

   //persistence
    public void Save()
    {
        db.SubmitChanges();
    }
}
To make a new class and save session variables in this class


public class MySession
{
    // private constructor
    private MySession()
    {
        //implement constructor if you want
    }

    public static MySession Current
    {
        get
        {
            MySession session = (MySession)HttpContext.Current.Session["__MySession__"];
            if (session == null)
            {
                session = new MySession();
                HttpContext.Current.Session["__MySession__"] = session;
            }
            return session;
        }
    }

    // **** Add your session properties here
    //public string Property1 { get; set; }
    //public DateTime MyDate { get; set; }
    //public int LoginId { get; set; }

    //***** You can use these properties from anywhere like this
    //    int loginId = MySession.Current.LoginId;

    //string property1 = MySession.Current.Property1;
    //MySession.Current.Property1 = newValue;

    //DateTime myDate = MySession.Current.MyDate;
    //MySession.Current.MyDate = DateTime.Now;
    public string CurrentUserName { get; set; }
    public string CurrentPageTitle { get; set; }



}