Friday, December 25, 2009

Making URL rewriting on IIS 7 works like IIS 6

what is URL rewriting ?

URL rewriting is the process of intercepting an incoming Web request and redirecting the request to a different resource. When performing URL rewriting, typically the URL being requested is checked and, based on its value, the request is redirected to a different URL.

Making URL rewriting  on IIS7?

Upgrading to IIS 7 should be rather transparent, unfortunately that is not the case when it comes to URL rewriting as we knew it from IIS 6. In IIS 6 all we had to do was to add a wildcard mapping making sure that all requests went through the ASPNET ISAPI process. After this was done, one could create a global.asax file that would either pass requests directly through or rewrite the URL based on an internal algorithm.

1) Start by opening the IIS Manager and selecting your website.

2) Now enter the "Handler Mappings" section

3) Notice the "StaticFile" handler. Currently it's set to match * and catch both File and Directory requests. If you look back at the first image, you'll notice that the error message details that the handler causing the 404 error is the StaticFile handler. As I know that all my static files will have a file extension (also I don't care for directory browsing), I'll simply change my StaticFile handler so it only matches *.* - and only files.

What needs to be done now is that we need to map any and all requests to the aspnet_isapi.dll isapi file - just like we would usually do in IIS 6.

Add a new Script Map to the list of Handler Mappings and set it up like this:

The aspnet_isapi.dll file cannot be used as a Handler for websites running in the new IIS 7 Integrated Mode, thus we will need to make our website run in classic .NET mode. Right click your website node in the IIS Manager and select Advanced Settings. Select the "Classic .NET AppPool" and close the dialog boxes:

"Failed to Execute URL", what a great descriptive error. Fortunately you won't have to spend hours ripping out hair... As I have already done that - at least I'll save a trip or two to the barber.

The problem is that the static files are being processed by the aspnet_isapi.dll file instead of simply sending the request along to the StaticFile handler. If you click the "View Ordered List..." link in the IIS Manager from the Handler Mappings view, you'll see the order in which the handlers are being executed for each request:

When you add a new Script Map it'll automatically get placed at the very top of the line taking precedence over any other handlers, including the StaticFile one.

What we have to do is to move our Wildcard handler to the very bottom, below the StaticFile handler. By letting the StaticFile handler have precedence over our Wildcard handler we ensure that any static files (matching *.*) gets processed correctly while any other URL's gets passed along to our own Wildcard handler that'll do the URL rewriting and make business work as usual:

Thursday, October 22, 2009

SharePoint as a Document Management System

What is SharePoint?

Microsoft Office SharePoint Server 2007 is an integrated suite of server capabilities that can help improve organizational effectiveness by providing comprehensive content management and enterprise search, accelerating shared business processes, and facilitating information-sharing across boundaries for better business insight. Additionally, this collaboration and content management server provides IT professionals and developers with the platform and tools they need for server administration, application extensibility, and interoperability.

Give your business a highly secure, central location where employees can efficiently collaborate with team members, find organizational resources, manage content and workflow, and gain the business insight to make better-informed decisions. Employees can create and manage custom team- and project-focused intranet sites for collaboration and document sharing.

SharePoint as a Document Management System

Document Management Basics


Before diving into the scenarios, it's important to understand the major components of any document management system and how SharePoint provides these. They include providing storage for the documents, versioning, metadata, security, indexing, workflow, and retrieval.

Storage


SharePoint leverages a concept called a document library to store documents. Document libraries let you define containers for keeping documents together, such as documents for a specific project, department, or any other logical grouping. Document libraries are not limited to Microsoft Office files—they can hold any document format, including PDFs, images, videos, and text files. However, SharePoint provides additional functionality for Microsoft Office 2007 documents (Word, Excel, PowerPoint, etc.).

In terms of the underlying technology, SharePoint uses a different approach for physically storing the documents than most document management products. While most vendors choose to store the documents on the file system and store the metadata in a database, SharePoint 2007 stores both documents and metadata in the database.

Versioning


Versioning saves copies of a document, letting users and administrators see and track changes to a document over time. When a user saves a new version of a document to a document library, the older versions remain available as well. This is an important feature in a collaborative environment where many people may be making changes to the same document.

Metadata


In a document management system, metadata is the information that describes the document. It comes in two flavors: automatic and user-defined.

  • Automatic metadata is traditional descriptive information, such as title, author, created date, file size, etc. This metadata is automatically added to the system when a user adds a document to SharePoint,

  • User-defined metadata requires an administrator or developer to add extra "columns" to SharePoint document libraries. These columns hold additional information about the document. For example, when creating a document library to house sales presentations, you might add columns for the presentation location, the presenter, and the presentation date. SharePoint supports individual data types for each column, so the presentation location column could be a dropdown of all major cities where presentations are held, the presenter column could be validated against all Active Directory users, and the presentation date could be defined as a date.


Security


Whenever documents are stored in a central repository, it's important to consider who will be able to access them. SharePoint allows administrators to define security rights to SharePoint sites, libraries within those sites, and documents within those libraries. These rights consist of permissions assigned to individual users or groups of users. Permissions levels range from read-only to full control.

Indexing


Indexing of documents is important when you're trying to find the right document quickly. SharePoint not only indexes the metadata for the documents it stores, it also creates a full-text index of any Microsoft Office documents. The full-text index lets users search for documents even when the target search terms appear somewhere deep within a document.

SharePoint 2007 enhances the search functionality significantly over previous versions. It has better relevancy algorithms, better security trimming (prevents users from seeing search results for which they should not have access), and better search management and reporting tools.

Workflow


A document workflow is a prescribed set of steps the document may go through during its development and lifetime. You can think of a workflow as an assembly line for your documents. Some documents may be subjected to more workflow than others. For example, a loan application may go through a rigorous process, passing from one person to another and according to a set of complex rules. At a simpler level, you may just want to ensure that someone provides feedback for meeting notes before you publish them to a team. Either way, SharePoint workflows can help.

SharePoint 2007 ships with several basic workflows that allow you to quickly request feedback on a document or get approval. To define more complex workflows, users can leverage SharePoint Designer or write custom code.

Tuesday, October 13, 2009

Automatic SQL Server Backup

Automatic SQL Server Backup


I am running Windows Server 2008 with MS SQL Server and put togther this HOW-TO about how to backup a database automatically. I figured I would share it with you:

I am using Microsoft SQL Server 2008 Express but you should be able to use these instructions for all versions of Microsoft SQL Server 2005 and Microsoft SQL Server 2008.

CREATE A SQL FILE and save it as "backup.sql"

declare @filepath varchar(255)
declare @filename varchar(255)
declare @file varchar(510)

set @filepath='D:\Praticle Test\'
declare @date varchar(8)
set @date=CONVERT(varchar(8), GETDATE(), 112)
set @filename= '-Backup.bak'
set @file=@filepath+ @date + @filename

Backup Database EHSolution To Disk = @file

CREATE A BATCH FILE With following content


sqlcmd -E -S pserver -i D:\backup.sql

SET BATCH FILE TO RUN IN WINDOWS TASK SCHEDULER

Start -> Run.

CODE

schtasks /create /sc Daily /st 03:30:00 /tn "MyTask" /tr "cmd /c D:\Backup.bat"


Wednesday, April 1, 2009

Sending HTML Mail

MailMessage mail = new MailMessage(FromEmail, Toemail);
mail.Bcc.Add(AdminEmail);

mail.Subject = "Subject goes here";

string strBody = "";
strBody = "Message Body";

mail.IsBodyHtml = true;
mail.Body = strBody;

SmtpClient client = new SmtpClient();
client.Host = SMTPServer;
client.Port =SMTPPort;

System.Net.NetworkCredential basicAuthenticationInfo = new System.Net.NetworkCredential(SMTPUser, SMTPPassword);
client.UseDefaultCredentials = false;
client.Credentials = basicAuthenticationInfo;

try
{
client.Send(mail);
}
catch (Exception ex)
{

}

How to Configure Source Control for Visual Studio 2008

When you have first installed Microsoft Visual Studio 2008 and Micrsoft Visual SourceSafe 2005, there is not initially a configured relationship between the two applications.
Source Control is not a menu item at this state until you configure the Source Control plug-in by using the Options dialog screen.

You can open the Options dialog screen by selecting Tools in the main menu then selecting Options submenu item. Drill down to the Source Control and Plug-in Selection in the options treeview.
There is a drop down list which lists available Source Control options and applications and an option for indicating not to use any of the source control software. In order to use Microsoft Visual SourceSafe 2005, you can select "Microsoft Visual SourceSafe" in the available source control plug-in combobox.

[caption id="attachment_53" align="alignnone" width="480" caption="plug-in-selection for Visual studio 2008"]plug-in-selection for Visual studio 2008[/caption]

If you select Visual SourceSafe plug-in two more branches will appear in the options treeview below the Source Control, "Environment" and "Plug-in Settings".

Monday, March 9, 2009

Use APPLY

Use APPLY
The apply statement was created for the situation where you put multiple inline nested queries in the one statement. For example, take the following statement:
SELECT soh.SalesOrderID,
Quantity=(SELECT TOP 1 (Quantity)
FROM Sales.SalesOrderDetails
WHERE  SalesOrderID = soh.SalesOrderID),
UnitPrice=(SELECT TOP 1 (UnitPrice)
FROM Sales.SalesOrderDetails
WHERE  SalesOrderID = soh.SalesOrderID)
FROM Sales.SalesOrderHeader soh
This performs an extra query, retrieving data from another table using the same criterion. This can now be replaced with the following:

SELECT soh.SalesOrderID, soh.OrderDate, a.*
FROM Sales.SalesOrderHeader soh
CROSS APPLY (
SELECT TOP (1) sod.UnitPrice, sod.Quantity
FROM Sales.SalesOrderDetail sod
WHERE sod.SalesOrderId = soh.SalesOrderId
ORDER BY sod.Quantity DESC
) as a

Friday, March 6, 2009

URL Rewriting in the IIS 7.0

follow the below mention steps for URL Rewriting in the IIS 7.0.

  1. Open Properties of the Virtual Directory "website1" from IIS.

  2. Click on “Configuration”, from Virtual Directory Tab.

  3. Click on “Insert” from Mappings Tab.

  4. Add the following path,


a. “X:\WINDOWS\Microsoft.NET\Framework\v2.0.507\aspnet_isapi.dll” in Executable. (X is the Windows Drive. i.e. where the framework is installed”)
b. Uncheck the Option “Check that file Exist”.

[gallery link="file"]

URL Rewriting in the IIS 6

[gallery link="file"]

Follow the below mention steps for URL Rewriting in the IIS.

1) Open Properties of the Virtual Directory  from IIS.

2) Click on “Configuration”, from Virtual Directory Tab.

3) Click on “Add” from Mapping Tab.

4) Add the following path,

a. “X:WINDOWSMicrosoft.NETFrameworkv2.0.50727aspnet_isapi.dll”  in Executable.  (X is the Windows Drive. i.e. where the framework is installed”)

b. Type “.*” in Extension.

c. Uncheck the Option “Check that file Exist”.

Add the following code in Global.asax file

string[] arrPath;
string strPath = string.Empty;
string strUrl = string.Empty;
string strQS = string.Empty;
string strQrystr = string.Empty;

string strLocal = ConfigurationManager.AppSettings["Local"];

protected void Application_BeginRequest(object sender, EventArgs e)
{
string str1 = "UrlRequest";
string str2 = str1;

strQrystr = string.Empty;
strUrl = string.Empty;
setPath();

if (strPath.IndexOf(".") > 0)
{
return;
}
try
{
// ### Start - If main page(like http://localhost/websiteName/) then exit sub
if (strPath == "" || strPath == "/")
{
HttpContext.Current.RewritePath(strLocal + "/Default.aspx", "", "");
return;
}

strQS = Request.QueryString.ToString();

if (System.IO.File.Exists(Server.MapPath("~/" + arrPath[1] + ".aspx")))
{
strUrl = ConfigurationManager.AppSettings["Local"] + "/" + arrPath[1] + ".aspx";

if (arrPath.Length > 0)
{
for (int i = 0; i < arrPath.Length; i++)
{
if (arrPath[i] != null && arrPath[i] != "")
{
strQrystr = strQrystr + "q" + i + "=" + arrPath[i] + "&";
}
}
}
if (strQrystr.Length > 0)
{
strQrystr = strQrystr.Substring(0, strQrystr.Length - 1);
}
}
else
{
Response.Redirect(strLocal + "/Default.aspx");
}

//### Start - Actual Url Rewrite

if (strQS == "")
HttpContext.Current.RewritePath(strUrl, "", strQrystr + strQS);
else
{
if (strQrystr != "")
{
HttpContext.Current.RewritePath(strUrl, "", strQrystr + "&" + strQS);
}
else
{
HttpContext.Current.RewritePath(strUrl, "", strQS);
}
}
}
catch (IndexOutOfRangeException ex)
{
ex.Message.ToString();

}
catch (Exception ex)
{
ex.Message.ToString();
}
}
private void setPath()
{
strPath = HttpContext.Current.Request.Path.ToString().ToLower();

if (HttpContext.Current.Request.Url.AbsoluteUri.ToLower().IndexOf("localhost") != -1 || strLocal != "")
{
strPath = strPath.Replace(strLocal.ToLower() + "/", "");
}
else
{
strPath = strPath.Substring(1);
}
arrPath = strPath.Split('/');
}

Add following lines in web.config

<add key="Local" value="/VirtualdirectoryName"/>

Making Store Procedure Generic

Making Store Procedure Generic


Consider creating stored procedures in the master database.



Use the special "sp_" prefix for these procedures, and use the undocumented system stored procedure "sp_MS_marksystemobject" to mark the stored procedure as a system stored procedure.

System stored procedures, although residing in the master database, operate on the database objects from where the stored procedure is executed.

All the usual caveats about using undocumented procedures and adding stored procedures to a system database apply.

Example:
***********
CREATE PROCEDURE sp_counts AS

DECLARE @TABLENAME VARCHAR(50)
DECLARE @SQL VARCHAR(200)
create table #temp
(
tablename varchar(300),
noofrows int
)

DECLARE C1 CURSOR FOR
select table_name from information_schema.tables where table_type='base table'

OPEN C1
FETCH NEXT FROM C1 INTO @TABLENAME
WHILE @@FETCH_STATUS=0
BEGIN

SET @SQL = 'select isnull(null,'''+@TABLENAME+'''),rows from sysindexes where indid<2 and id = object_id('+ '''' + @TABLENAME +'''' +')'

insert into #temp exec(@SQL)
FETCH NEXT FROM C1 INTO @TABLENAME
END
close C1
deallocate C1
delete from #temp where tablename = 'dtproperties'
select * from #temp order by noofrows desc
drop table #temp
GO

********
exec sp_MS_marksystemobject 'sp_counts'
********

Now from any database you can give EXEC SP_COUNTS which gives you the tablename and total rows in the table.