Sep
8

How to take backup all databases in SQL Server

The following code will helps you to take all the databases at a time

DECLARE @name VARCHAR(50) -- database name
DECLARE @path VARCHAR(256) -- path for backup files
DECLARE @fileName VARCHAR(256) -- filename for backup
DECLARE @fileDate VARCHAR(20) -- used for file name
SET @path = 'C:\SQLBackup\'
SELECT @fileDate = CONVERT(VARCHAR(20),GETDATE(),112)
DECLARE db_cursor CURSOR FOR
SELECT name
FROM master.dbo.sysdatabases
WHERE name NOT IN ('master','model','msdb','tempdb')
OPEN db_cursor
FETCH NEXT FROM db_cursor INTO @name
WHILE @@FETCH_STATUS = 0
BEGIN
SET @fileName = @path + @name + '_' + @fileDate + '.BAK'
BACKUP DATABASE @name TO DISK = @fileName
FETCH NEXT FROM db_cursor INTO @name
END
CLOSE db_cursor
DEALLOCATE db_cursor
 
 
 
May
27

The page you are requesting cannot be served because of the extension configuration (WFC) HTTP Error 404.3 – Not Found

Recently, I migrated to Windows 7 and ended up installing all my software’s again. I had a project which involved hosting a WCF service on IIS. The service used a .svc file extension and IIS 7 on my machine was not aware how to handle these files.

The error I got looked something like this:

HTTP Error 404.3 – Not Found

The page you are requesting cannot be served because of the extension configuration. If the page is a script, add a handler. If the file should be downloaded, add a MIME map. Detailed Error InformationModule StaticFileModule.

There were more errors related to local machine below these errors.I looked up the net and after some digging figured out the solution to the problem:

1. Run Visual Studio 2008 Command Prompt as “Administrator”.
2. Navigate to C:\Windows\Microsoft.NET\Framework\v3.0\Windows Communication Foundation.
3. Run this command servicemodelreg –i.
The servicemodelreg is a command line tool which provides the ability to manage the registration on ServiceModel on a machine.

 

Apr
6

Code Snippet : Exporting DataSet to Excel file in asp.net

Here is the code to export DataSet to Excel file.
Process:
Prepare a GridView or DataGrid from code behind file with the DataSet
and use the following code to export as a Excel(.xls) file.

private void Export(DataSet ds)
{
System.Web.UI.WebControls.DataGrid dg;
try
{
Response.Clear();
Response.ClearContent();
Response.ClearHeaders();
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("Content-Disposition", "attachment;filename=ExportFile.xls");
EnableViewState = true;
foreach (DataTable item in ds.Tables)
{
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite = new System.Web.UI.HtmlTextWriter(stringWrite);
dg = new System.Web.UI.WebControls.DataGrid();
dg.ShowHeader = true;
dg.HeaderStyle.BackColor = System.Drawing.Color.Gray;
dg.HeaderStyle.Font.Bold = true;
dg.HeaderStyle.ForeColor = System.Drawing.Color.White;
dg.HeaderStyle.HorizontalAlign = HorizontalAlign.Center;
dg.HeaderStyle.Height = new Unit(30);
dg.HeaderStyle.VerticalAlign = VerticalAlign.Middle;
dg.ForeColor = System.Drawing.Color.Black;
dg.DataSource = item;
dg.DataBind();
dg.RenderControl(htmlWrite);
Response.Write(item.TableName);
Response.Write(stringWrite.ToString());
}
Response.End();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
finally
{
}
}
Mar
8

Complete Lifecycle of an ASP.Net page and controls

Many people have blogged about the lifecycle of an ASP.Net Page or Master Page but every time I need to find the complete lifecycle of a control it’s not so easy. Today I wrote a couple of test pages to generate a reference.
The pages are very simple, I just overrode every method I could find and wrote to the trace. For completeness when the method called its base I wrapped it with “Start MethodName” and “End MethodName” (if you look at the trace outputs below you will see why). I did this for the Master Page (.master), Page (.aspx), User Control (.ascx) and Web Control (.cs), the page structre was simple:

Master Page
Page
User Control
Web Control

read more

Feb
9

Life and Times of Anders Hejlsberg

Right click “Save as…”
Medium Quality WMV (Lo-band, Mobile) WMV (WMV Video)

This episode features industry luminary, Anders Hejlsberg. Before coming to Microsoft in 1996 he was well noted for his work as the principal engineer of Turbo Pascal and the chief architect of the Delphi product line. At Microsoft he was architect for the Visual J++ development system and the Windows Foundation Classes (WFC). Promoted to Distinguished Engineer in 2000, Anders is the chief designer of the C# programming language and a key participant in the development of Microsoft’s .NET framework. In this show, Anders is joined by a surprise guest.

This episode of “Behind the Code” is hosted by Barbara Fox – former senior security architect of cryptography and digital rights management for Microsoft.

“Behind the Code” with Jim Gray to be released March 2006

Feb
8

Passing lists to SQL Server 2005 with XML Parameters

Getting started with SQL Server 2005′s XML Syntax

XML variables in SQL Server 2005 make it easy to “shred” XML strings into relational data. The main new methods you’ll need to use are value() and nodes() which allow us to select values from XML documents.

Sql Code   
DECLARE @productIds xml
SET @productIds ='<Products><id>3</id><id>6</id><id>15</id></Products>'

SELECT
ParamValues.ID.value('.','VARCHAR(20)')
FROM @productIds.nodes('/Products/id') AS ParamValues(ID)

Which gives us the following three rows:

3
6
15

Alright, just show me how to pass a list in a procedure parameter already!

Here’s a proc which takes a single XML parameter. We first declare a table variable (@Products) and load the XML values into it. Once that’s done, we can join against the @Products table as if it were any other table in the database.

Sql Code   
CREATE PROCEDURE SelectByIdList(@productIds xml) AS

DECLARE @Products TABLE (ID int)

INSERT INTO @Products (ID) SELECT ParamValues.ID.value('.','VARCHAR(20)')
FROM @productIds.nodes('/Products/id') AS ParamValues(ID)

SELECT * FROM
    Products
INNER JOIN
    @Products p
ON    Products.ProductID = p.ID

Now we can call it as follows:

EXEC SelectByIdList @productIds='<Products><id>3</id><id>6</id><id>15</id></Products>'

In order to use this, you’ll need to an XML string with your ID’s.:

public static string BuildXmlString(string xmlRootName, string[] values)
{
StringBuilder xmlString = new StringBuilder();

xmlString.AppendFormat("<{0}>", xmlRootName);
for (int i = 0; i < values.Length; i++)
{
xmlString.AppendFormat("<id>{0}</id>", values[i]);
}
xmlString.AppendFormat("</{0}>", xmlRootName);

return xmlString.ToString();
}
Feb
4

Ajax Toolkit: Model Popup extender

Popup dialog box with AJAX toolkit

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="PopUp.ascx.cs" Inherits="MyControls_PopUp" %>
 
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>
<style type="text/css">
.modalBackground{background:#000; opacity:0.4; filter:alpha(opacity=40)}
</style>
<asp:Button id="btnShowPopup" runat="server" style="display:none" />
<asp:ModalPopupExtender ID="mpe" runat="server" TargetControlID="btnShowPopup"  PopupControlID="pnl"
BackgroundCssClass="modalBackground"  DropShadow="true"  CancelControlID="ibClose"  PopupDragHandleControlID="PnlHead"/>
<asp:Panel ID="pnl" runat="server">
<asp:Panel ID="PnlHead" runat="server">
<div>
<div style="float:left; padding:0px; margin:0px; padding-top:10px; padding-left:10px; width:80%; color:#FFF; font-size:14px; font-weight:bold ">
<asp:Label ID="lHeader" runat="server"></asp:Label>
</div>
<asp:ImageButton Width="30px" style="float:right; padding:3px" ID="ibClose" runat="server" ImageUrl="~/App_Themes/Default/images/close.png" />
<div style="clear:both"></div>
</div>
</asp:Panel>
<div>
<div style="text-align:center">
<br />
<asp:Label ID="lMessage" runat="server"></asp:Label>
<br />
<br />
<asp:Button ID="bOK" ValidationGroup="POPUP" runat="server" OnClick="btnOk_Click" Text="OK" />
</div>
</div>
<div style="clear:both"></div>
</asp:Panel>

The following is the c# code for this control

Popup.cs   
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class MyControls_PopUp : System.Web.UI.UserControl
{
    public string Header { get; set; }
    public string Message { get; set; }
    public string CssClass_Header { get; set; }
    public string CssClass_Message { get; set; }
    public string CssClass_Background { get; set; }
    public event EventHandler OKClick;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (CssClass_Background != string.Empty)
            mpe.BackgroundCssClass = CssClass_Background;
        if (CssClass_Header != string.Empty)
            PnlHead.CssClass = CssClass_Header;
        if (CssClass_Message != string.Empty)
            pnl.CssClass = CssClass_Message;
        lHeader.Text = Header;
        lMessage.Text = Message;
    }

    public void Show(string Header, string Message)
    {
        lHeader.Text = Header;
        lMessage.Text = Message;
        mpe.Show();
    }

    public void Hide()
    {
        mpe.Hide();
    }

    public void btnOk_Click(object sender, EventArgs e)
    {
        if (OKClick != null)
            OKClick(this, EventArgs.Empty);
        mpe.Hide();
    }

}

using this popup in the code

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>
<%@ Register src="MyControls/PopUp.ascx" tagname="Popup" tagprefix="uc" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
<style type="text/css">
.modalBackground{background:#000; opacity:0.4; filter:alpha(opacity=40)}
.popupPanel{background:#FFF; border:2px solid #de562b; width:600px; height:200px;}
.popupPanelHead{background:#de562b; border-bottom:2px solid #de562b; width:600px; height:40px;}
</style>
</head>
<body>
    <form id="form1" runat="server">
    <asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server"> </asp:ToolkitScriptManager>
    <div>
        <asp:Button ID="btn" runat="server" Text="ShowPopup" OnClick="btn_Click" />
        <uc:Popup ID="mpc" runat="server" OnOKClick="mpe_OKClick" CssClass_Background="modalBackground" CssClass_Header="popupPanelHead" CssClass_Message="popupPanel" />
    </div>
    </form>
</body>
</html>

Default2.cs code behind file

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class Default2 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
    }
    protected void mpe_OKClick(object sender, EventArgs e)
    {
        Response.Write("ok Button Clicked");
    }

    protected void btn_Click(object sender, EventArgs e)
    {
        mpc.Show("This is Header", "this is Message Body");
    }
}
Jan
28

Code Snippet 1: Best way to convert string to DateTime

This is the best way to convert string to Date
the following code convert string to date which is in
“d/M/yyyy” or “dd/MM/yyyy” or “d/MM/yyyy” or “dd/M/yyyy”

string MyDate = "12/12/2012";
DateTime _MyDate;
if (!DateTime.TryParseExact(MyDate, new[] { "d/M/yyyy", "dd/MM/yyyy", "d/MM/yyyy", "dd/M/yyyy" }, CultureInfo.InvariantCulture, DateTimeStyles.None, out _MyDate))
{
this._message = "Invalid Date";
// do here with invalid date
}
_MyDate
// do here  with valid date

Function:

public static bool ToDate(string DateString, out DateTime Date)
        {
            if (!DateTime.TryParseExact(DateString, new[] { "d/M/yyyy", "dd/MM/yyyy", "d/MM/yyyy", "dd/M/yyyy" }, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out Date))
                return false;
            return true;
        }
Jan
27

Remove duplicates in a string array

These are the followings ways, where we can filter a string array to remove the duplicates.

HashSet   
public static string[] RemoveDuplicates(string[] s)
{
HashSet set = new HashSet(s);
string[] result = new string[set.Count];
set.CopyTo(result);
return result;
}
List 1   
private static string PreviousItem;

private static bool Match(string item)
{
    bool result = (item == PreviousItem);
    PreviousItem = item;
    return result;
}

public static string[] NoDuplicates(string[] input)
{
    PreviousItem = null;
    List<string> result = new List<string>(input);
    result.Sort();
    result.RemoveAll(Match);
    return result.ToArray();
}
Aug
5

How to Add a GridView Column of Radio Buttons

In ASPX File add the following lines of code…

<form id="form1" runat="server">
<div>
<asp:Button ID="btnLoad" runat="server" Text="Load Users" onclick="btnLoad_Click" />
<asp:GridView ID="gvUsers" runat="server" OnRowCreated="gvUsers_RowCreated">
<Columns>
<asp:TemplateField HeaderText="Method1">
<ItemTemplate>
<asp:Literal id="RadioButtonMarkup" runat="server"></asp:Literal>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Method2">
<ItemTemplate>
<input name="MyRadioButton" type="radio" value='<%# Eval("Name") %>'/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
<asp:Button ID="bSubmit" runat="server" Text="Submit" onclick="bSubmit_Click" />
<br />
<asp:Label ID="lmsg" runat="server"></asp:Label>
</form>

In code behind file add the following code…

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}
protected void btnLoad_Click(object sender, EventArgs e)
{
using (ProjectDBDataContext db = new ProjectDBDataContext())
{
var roles = from r in db.MUserInfos select r;
gvUsers.DataSource = roles;
gvUsers.DataBind();
}
}
private int UsersSelectedIndex
{
get
{
if (string.IsNullOrEmpty(Request.Form["UsersGroup"]))
return -1;
else
return Convert.ToInt32(Request.Form["UsersGroup"]);
}
}
protected void gvUsers_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
// Grab a reference to the Literal control
Literal output = (Literal)e.Row.FindControl("RadioButtonMarkup");
// Output the markup except for the "checked" attribute
output.Text = string.Format( "<input type=\"radio\" name=\"UsersGroup\" " + "id=\"RowSelector{0}\" value=\"{0}\"", e.Row.RowIndex);
// See if we need to add the "checked" attribute
if (UsersSelectedIndex == e.Row.RowIndex)
output.Text += " checked=\"checked\"";
// Add the closing tag
output.Text += " />";
}
}
protected void bSubmit_Click(object sender, EventArgs e)
{
int x = UsersSelectedIndex;
lmsg.Text = "method1: " +x.ToString() + "</br>";
string selectedValue = Request.Form["MyRadioButton"];
lmsg.Text += "method2: "  + selectedValue;
}
}

Follow us on Twitter! Follow us on Twitter!
FoxSparrow Tweets

Categories