Dec 15, 2011

How to restore database when database was suspect

EXEC sp_resetstatus DataBaseName;
ALTER DATABASE DataBaseName SET EMERGENCY
DBCC checkdb(DataBaseName)
ALTER DATABASE DataBaseName SET SINGLE_USER WITH ROLLBACK IMMEDIATE
DBCC CheckDB (DataBaseName, REPAIR_ALLOW_DATA_LOSS)
ALTER DATABASE DataBaseName SET MULTI_USER

Nov 30, 2011

Create Dynamic Excel file using Asp.Net

public static void Write(HttpResponse response)
{

// make sure nothing is in response stream
response.Clear();
response.Charset = "";

// set MIME type to be Excel file.
response.ContentType = "application/ms-excel";

// add a header to response to force download (specifying filename)
response.AddHeader("Content-Disposition", "attachment; filename=\"MyFile.xls\"");

for (int i = 0; i < 10; i++)
{
// Send the data. Tab delimited, with newlines.
response.Write("Col1 \t Col2 \t Col3 \t Col4 \n");
}



// Close response stream.
response.End();

}

Nov 18, 2011

Parent Child Relationship on self table in sqlserver

CREATE TABLE dbo.Emp
(
EmpID int PRIMARY KEY,
EmpName varchar(30),
MgrID int FOREIGN KEY REFERENCES Emp(EmpID)
)
GO

Insert few record into table

INSERT dbo.Emp SELECT 1, 'President', NULL
INSERT dbo.Emp SELECT 2, 'Vice President', 1
INSERT dbo.Emp SELECT 3, 'CEO', 2
INSERT dbo.Emp SELECT 4, 'CTO', 2
INSERT dbo.Emp SELECT 5, 'Group Project Manager', 4
INSERT dbo.Emp SELECT 6, 'Project Manager 1', 5
INSERT dbo.Emp SELECT 7, 'Project Manager 2', 5
INSERT dbo.Emp SELECT 8, 'Team Leader 1', 6
INSERT dbo.Emp SELECT 9, 'Software Engineer 1', 8
INSERT dbo.Emp SELECT 10, 'Software Engineer 2', 8
INSERT dbo.Emp SELECT 11, 'Test Lead 1', 6
INSERT dbo.Emp SELECT 12, 'Tester 1', 11
INSERT dbo.Emp SELECT 13, 'Tester 2', 11
INSERT dbo.Emp SELECT 14, 'Team Leader 2', 7
INSERT dbo.Emp SELECT 15, 'Software Engineer 3', 14
INSERT dbo.Emp SELECT 16, 'Software Engineer 4', 14
INSERT dbo.Emp SELECT 17, 'Test Lead 2', 7
INSERT dbo.Emp SELECT 18, 'Tester 3', 17
INSERT dbo.Emp SELECT 19, 'Tester 4', 17
INSERT dbo.Emp SELECT 20, 'Tester 5', 17
GO


Create sql function


create FUNCTION [dbo].[ShowHierarchy]
(
@Root bigint
)
RETURNS
@menutable TABLE(EmpName varchar(max),MgrID int,EmpID int)
AS
BEGIN


DECLARE @EmpID int, @EmpName varchar(30),@MgrID int, @rootid bigint


set @rootid =@Root
SELECT @EmpID=EmpID,@EmpName=EmpName,@MgrID=MgrID FROM dbo.Emp WHERE EmpID = @Root

-- SET @EmpName = (SELECT EmpName FROM dbo.Emp WHERE EmpID = @Root)
if(@EmpName is not null)
begin
insert into @menutable select REPLICATE(' ', @@NESTLEVEL * 4) + @EmpName,@MgrID,@EmpID
end

SET @EmpID = (SELECT MIN(EmpID) FROM dbo.Emp WHERE MgrID = @Root)

WHILE @EmpID IS NOT NULL
BEGIN
insert into @menutable select * from dbo.ShowHierarchy(@EmpID)
SET @EmpID = (SELECT MIN(EmpID) FROM dbo.Emp WHERE MgrID = @rootid AND EmpID > @EmpID)
END
return
END


//call this function from where you want
Select * from dbo.ShowHierarchy(0)


Nov 11, 2011

Create Dynamic Control Using Jquery with Asp.Net

Hello Friends,

After so many R & D works i got good solution for generate dynamic control in asp.net using jquery/ javascript.

I have got two solution. For more click here to download examples.

Sep 22, 2011

How to call server side function using JQuery in Asp.net

Click Here for Download Source Code

Below is Default.aspx page code
-------------------------------

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!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 id="Head1" runat="server">
<title>Call server side method using Jquery</title>

<!-- Add the jQuery Reference Library-->
<script src="Script/jquery-1.4.min.js" type="text/javascript"></script>
<script type="text/javascript">
$('#btnok').click(function() {
$.ajax({
type: "POST",
url: "Default.aspx/Test1",
data: "{'args1':'Kalpesh','args2':'Patel'}",
contentType: "application/json",
dataType: "json",
success: function(msg) {
// Replace the div's content with the page method's return.
$("#newresult").text(msg.d);
}
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<input id="Button1" type="button" value="button" />
<span id="status"></span>
</div>
</form>
</body>
</html>


Code Behide file code (Default.aspx.cs)
-----------------------------------------


using System;
using System.Web.Services;
using System.Web;

public partial class _Default : System.Web.UI.Page
{
public void test()
{


}

[WebMethod(EnableSession = false)]
public static string Test1(string args1, string args2)
{
return "Hello: " + args1 + " " + args2;
}
[WebMethod]
public static string Test2()
{


return "Hello: " + DateTime.Now.Millisecond + " -- Kalpesh Patel";
}
}

Sep 14, 2011

How to split a string with multi-character delimiter in Asp.Net

string [] words = myStr.Split(new String[] { "##" }, StringSplitOptions.None);

Sep 3, 2011

Disable Validation Control From JavaScript.

Just simply call the inbuilt Ajax function from Javascript.

<script type="text/javascript">
function HasPageValidators() {
var hasValidators = false;

try {
if (Page_Validators.length > 0) {
hasValidators = true;
}
}
catch (error) {
}

return hasValidators;
}

function ValidationGroupEnable(validationGroupName, isEnable) {
if (HasPageValidators()) {
for (i = 0; i < Page_Validators.length; i++) {
if (Page_Validators[i].validationGroup == validationGroupName) {
ValidatorEnable(Page_Validators[i], isEnable);
}
}
}
}
</script&ft;

Call Function :

ValidationGroupEnable(validationgroupname, false);
Note : It Will Disable validation of Control for "validationgroupname"
there EnableClientScript true For Control

Aug 24, 2011

Sometimes Page load event not firing in asp.net


The reason for the page executing doesn't affect the page cycle, the Load event always fires when the page is executed.

So, if the Page_Load doesn't run sometimes, it's because the page is cached and doesn't execute on the server. The page can be cached in the browser, in a router somewhere along the way, or on the server using server side page caching.

If you haven't enabled server side page caching for the page, it's cached in the browser or in the network. You can use cache settings to try to elliminate this:

Response.Cache.SetCacheability(HttpCacheability.NoCache);

This will keep the page from being cached in normal circumstances. (Check also that your browser isn't in offline mode, then it will use anything in the cache regardless of it's cacheability settings.)

Aug 4, 2011

Excel Data Reader - Read Excel files in .NET (Convert Excel data to DataTable using Asp.Net)

Click here to download Excel.dll File FileStream stream = File.Open(filePath, FileMode.Open, FileAccess.Read);
//1. Reading from a binary Excel file ('97-2003 format; *.xls)
IExcelDataReader excelReader =ExcelReaderFactory.CreateBinaryReader(stream);

//... //2. Reading from a OpenXml Excel file (2007 format; *.xlsx)

IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);
//... //3. DataSet - The result of each spreadsheet will be created in the result.Tables
DataSet result = excelReader.AsDataSet();

//... //4. DataSet - Create column names from first row
excelReader.IsFirstRowAsColumnNames = true;
DataSet result = excelReader.AsDataSet();
//5. Data Reader methods

while
(excelReader.Read()) { //excelReader.GetInt32(0); }
//6. Free resources (IExcelDataReader is IDisposable) excelReader.Close();

I hope help to you.

Jul 12, 2011

Get Physical Path using Asp.Net

Hello Friend,

I have found to get physical path from different way.

1) On .aspx.cs Page
string path = Server.MapPath("/");

2) On Class File (.CS) Page
String Path = HttpContext.Current.Server.MapPath("/");

3) If you are using Thread and want to get physical path in .CS or .asax file
String Path = HttpContext.AppDomainAppPath.Replace("//","\\");

Jul 7, 2011

India Currency Format in .Rdcl report and Write custom function in .Rdcl Report.







Step 1: First choose Document outline from left panel








Step 2: Right click on Report and select Property











Step 3: Write function in code tab











Step 4: Then select field from report which you want to set currency format.












Step 5: Call custom function from code tab. using =code.FunctionName(parameter)









Step 6: You will get result.

I hope help to you.

Jul 6, 2011

Declare Nested Cursor in Sql Server

declare @id bigint
--Declare outer cursor
declare outer_cursor cursor for
select id from table

--Declare inner cursor as a variable
declare @inner_cursor cursor

open outer_cursor
fetch next from outer_cursor into @id
while(@@FETCH_STATUS=0)
begin
-- Few statements
declare @cartid bigint
declare @qty bigint
set @inner_cursor = cursor for select id,qty from cart where productid=@id

open @new_count
fetch next from @
inner_cursor into @cartid, @qty while(@@FETCH_STATUS=0)
begin
--Few Statements
end
end

Jun 21, 2011

India Currency format using Asp.Net

Hello Friends,

I got nice solution.

using System.Globalization;

CultureInfo info = new CultureInfo("hi-IN");
Response.Write(double.Parse("1389000.00").ToString("N2", info));

I hope help to you.

Jun 17, 2011

Use .VB and .CS class file in one website using asp.net

When I was creating my one of the site, I chose to write it in C#. I had a problem with the App_Code folder because I had some code in VB.NET code and some C# code I needed to put in there. I didn't want to rewrite my VB.NET code in the App_Code folder just so I could write the rest of the code for the site in C#.

Luckily, the ASP.NET Team had already thought about just this kind of circumstance. They implemented a way to partition the App_Code folder into sub-folders, one for each set of code files written in the same programming language. Awesome, I didn't have to spend a couple hours converting code from VB.NET to C#!

The below works with ASP.NET 2.0 and later.

Even if you don't use multiple different programming languages for your code files in the App_Code folder, you could use this feature to organize your sets of related code files into sub-folders.

Step 1: Add the following lines to the web.config


<configuration>
<system.web>
<compilation>
<codeSubDirectories>
<add directoryName="VB_Code"/>
<add directoryName="CS_Code"/>
codeSubDirectories>
compilation>
system.web>
configuration>

Step 2: Create a sub-folder in the App_Code folder for each language you want to support.
For Example:
/App_Code/VB_Code
/App_Code/CS_Code

Step 3: Place your VB.NET code in the VB_Code folder and place C# code in the CS_Code folder.

Display India Currency format using JavaScript

function intToFormat(nStr)
{
nStr += '';
x = nStr.split('.');
x1 = x[0];
x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
var z = 0;
var len = String(x1).length;
var num = parseInt((len/2)-1);

while (rgx.test(x1))
{
if(z > 0)
{
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
else
{
x1 = x1.replace(rgx, '$1' + ',' + '$2');
rgx = /(\d+)(\d{2})/;
}
z++;
num--;
if(num == 0)
{
break;
}
}
return x1 + x2;
}

Jun 6, 2011

Reduce Image File Size Using Asp.Net

//Call to function
imageSave(fluCatImage.FileName, fluCatImage.PostedFile.InputStream, Server.MapPath("~/"), Server.MapPath("../uploadimage/"));


//Implement Function
public void imageSave(string imagename, Stream s, string serverpath, string foldername)
{
if (imagename != string.Empty)
{
System.Drawing.Image image = System.Drawing.Image.FromStream(s);

Bitmap source = new Bitmap(image); //<-- or any other source

Bitmap target = new Bitmap(source.Width, source.Height);
Graphics g = Graphics.FromImage(target);

EncoderParameters e;
g.CompositingQuality = CompositingQuality.HighSpeed; //<-- here
g.InterpolationMode = InterpolationMode.Low;// <-- here

Rectangle recCompression = new Rectangle(0, 0, source.Width, source.Height);
g.DrawImage(source, recCompression);

e = new EncoderParameters(2);
e.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, (long)70);// <-- here 70% quality
e.Param[1] = new EncoderParameter(System.Drawing.Imaging.Encoder.Compression, (long)EncoderValue.CompressionLZW); //<-- here
DateTime MyDate = DateTime.Now;
source.Dispose();
string imgname = DateTime.UtcNow.ToString().Replace(" ", "").Replace("AM", "").Replace("PM", "").Replace("/", "").Replace("-", "").Replace(":", "");
String MyString = imgname + ".jpg";
target.Save(foldername + MyString, GetEncoderInfo("image/jpeg"), e);
// MemoryStream ms = new MemoryStream();
// target.Save(ms, GetEncoderInfo("image/jpeg"),e);
// ms.WriteTo(ms);

g.Dispose();
target.Dispose();
}
}

public static ImageCodecInfo GetEncoderInfo(string sMime)
{
ImageCodecInfo[] objEncoders;
objEncoders = ImageCodecInfo.GetImageEncoders();
for (int iLoop = 0; iLoop <= (objEncoders.Length - 1); iLoop++)
{
if (objEncoders[iLoop].MimeType == sMime)
return objEncoders[iLoop];
}
return null;
}

Jun 3, 2011

Reset AutoIncrement in SqlServer after Delete

I got solution for reset auto identity key to 1.

Just run below query and get result

DBCC CHECKIDENT (TableName, RESEED,1)
hope it will help you

May 25, 2011

Set Cookie from Javascript and get from Asp.net

--------------------------------Start Set Cookie from Javasript
///Get cookie
function getCookie(c_name) {
var i, x, y, ARRcookies = document.cookie.split(";");
for (i = 0; i < ARRcookies.length; i++) {
x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
x = x.replace(/^\s+\s+$/g, "");
if (x == c_name) {
return unescape(y);
}
}
}
///Set cookie
function setCookie(c_name, value, exdays) {
var exdate = new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value = escape(value) + ((exdays == null) ? "" : "; expires=" + exdate.toUTCString());
document.cookie = c_name + "=" + c_value;
}
///Check cookie
function checkCookie() {
var username = getCookie("username");
if (username != null && username != "") {
//alert("Welcome again " + username);
}
else {
username = prompt("Please enter your name:", "");
if (username != null && username != "") {
setCookie("username", username, 365);
}
}
}

--------------------------------End Set Cookie from Javasript
--------------------------------Start Get Cookie from Asp.Net

public string TapName
{
get
{
string tapname = string.Empty;
try
{
if (HttpContext.Current.Request.Cookies["TapName"] != null)
{
HttpCookie hc1 = HttpContext.Current.Request.Cookies["TapName"];
tapname = hc1.Value;
}
}
catch (Exception ex)
{
tapname = string.Empty;
}
return tapname;
}
}



--------------------------------Start Get Cookie from Asp.Net

May 17, 2011

Mar 27, 2011

Find control in content page from nested master page

Please refer below code.

ContentPlaceHolder cp = this.Master.Master.FindControl("ContentPlaceHolder2") as ContentPlaceHolder;
cp.FindControl("TopPartCTL1").Visible = true;

I hope above code will help you.

Youtube z-index problem

Here is an example of youtube embeded code change for z-index problem.

1) if you are using object for embeded code
So please add below line into your code.

<param name="wmode" value="opaque">

<object width="640" height="385"><param name="movie" value="http://www.youtube.com/v/riS8Z2grelo?fs=1&hl=en_US"><param name="allowFullScreen" value="true"><param name="wmode" value="opaque"><param name="allowscriptaccess" value="always"<>embed src="http://www.youtube.com/v/riS8Z2grelo?fs=1&hl=en_US" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" wmode="opaque" width="640" height="385"></embed></object>


2) If you are using iframe for embeded code
So please add into url below code

<iframe title="YouTube video player" class="youtube-player" type="text/html" src="http://www.youtube.com/embed/riS8Z2grelo?wmode=transparent" allowfullscreen="" width="640" frameborder="0" height="390"></iframe>