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
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.
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.
{
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
{
}
}
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
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
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.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");
}
}
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”
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:
{
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;
}
Remove duplicates in a string array
These are the followings ways, where we can filter a string array to remove the duplicates.
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();
}
How to Add a GridView Column of Radio Buttons
In ASPX File add the following lines of code…
<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…
{
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;
}
}
How to upload a file to ftp server with FileUpload control
{
try
{
string ftphost = "ftpaddress";
string ftpfullpath = "ftp://" + ftphost + ftpfilepath;
Stream streamObj = fileToUpload.InputStream;
Byte[] buffer = new Byte[fileToUpload.ContentLength];
streamObj.Read(buffer, 0, buffer.Length);
streamObj.Close();
streamObj = null;
FtpWebRequest requestObj = FtpWebRequest.Create(ftpfullpath) as FtpWebRequest;
requestObj.Method = WebRequestMethods.Ftp.UploadFile;
requestObj.Credentials = new NetworkCredential("username", "password");
Stream requestStream = requestObj.GetRequestStream();
requestStream.Write(buffer, 0, buffer.Length);
requestStream.Flush();
requestStream.Close();
requestObj = null;
return true;
}
catch
{
return false;
}
}
To create directory on application server with ASP.NET server side code
Here is the code to creating the directory at application with ASP.NET
using System.Data;
using System.Configuration;
// We need this namespace to create directory
using System.IO;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string NewDir = Server.MapPath("New Folder");
// Call function for creating a directory
MakeDirectoryIfExists(NewDir);
}
private void MakeDirectoryIfExists(string NewDirectory)
{
try
{
// Check if directory exists
if (!Directory.Exists(NewDirectory))
{
// Create the directory.
Directory.CreateDirectory(NewDirectory);
}
}
catch (IOException _ex)
{
Response.Write(_ex.Message);
}
}
}
Categories
- Dot Net (12)
- .Net Framework (1)
- Ajax (1)
- ASP.NET (6)
- C#.NET (3)
- Code Snippets (3)
- WCF (1)
- SQL Server (3)
- Tutorials (1)
- Video (1)




