Friday, October 14, 2011

Dot net tools

Following Tools will help for dot net developers

1)LINQPad

LINQPad lets you interactively query databases in a modern query language: LINQ. Kiss goodbye to SQL Management Studio!

LINQPad supports everything in C# 4.0 and Framework 4.0:

•LINQ to Objects
•LINQ to SQL and Entity Framework
•LINQ to XML
•Parallel LINQ

Download Link
--------------
http://www.linqpad.net/


Find SQL Sever all the table's foreign key list using sql querys

Following query will list out all tables foreign key's


SELECT kcuf.TABLE_NAME AS 'Table Name', kcup.TABLE_NAME AS 'Reference table name',
kcup.COLUMN_NAME AS 'Reference table column name'
FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS rc
INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE kcup
ON kcup.CONSTRAINT_SCHEMA = rc.UNIQUE_CONSTRAINT_SCHEMA
AND kcup.CONSTRAINT_NAME = rc.UNIQUE_CONSTRAINT_NAME
INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE kcuf
ON kcuf.CONSTRAINT_SCHEMA = rc.CONSTRAINT_SCHEMA
AND kcuf.CONSTRAINT_NAME = rc.CONSTRAINT_NAME
AND kcup.ORDINAL_POSITION = kcuf.ORDINAL_POSITION
ORDER BY kcuf.TABLE_NAME



Happy Coding..

Friday, August 26, 2011

sql server database how to drop database forcefully

There are many ways to drop database forcefully
1) we need to find active process spid and we need kill
2) following query will help to drop database forcefully


IF EXISTS(SELECT 1 FROM sysdatabases WHERE [NAME]='databaseName')

BEGIN

ALTER DATABASE databaseName

SET SINGLE_USER

WITH ROLLBACK IMMEDIATE;

ALTER DATABASE databaseName

SET MULTI_USER

WITH ROLLBACK IMMEDIATE;

DROP DATABASE databaseName



END

happy coding...

Tuesday, August 23, 2011

sql server how to reset identity column

Following query can help for resting identity column

Query
------
DBCC CHECKIDENT('tableName', RESEED, 0)

happy coding.....

Tuesday, May 31, 2011

sql server comma separated values count

Following steps will explains how to write query for count comma separated values

1)Create table using following Query


/****** Object: Table [dbo].[GroupsDetails] Script Date: 05/31/2011 21:38:10 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO

CREATE TABLE [dbo].[GroupsDetails](
[GroupId] [int] NULL,
[GroupMembers] [varchar](50) NULL
) ON [PRIMARY]

GO

SET ANSI_PADDING OFF
GO




2)Insert table data using following query


INSERT INTO [GroupsDetails]([GroupId],[GroupMembers])VALUES(1,'manikandan,raja,kumar,selvem')
INSERT INTO [GroupsDetails]([GroupId],[GroupMembers])VALUES(2,'balaji,sankar')
INSERT INTO [GroupsDetails]([GroupId],[GroupMembers])VALUES(3,'maha,raja')
INSERT INTO [GroupsDetails]([GroupId],[GroupMembers])VALUES(4,'maha,mala')



3)Following query will give comma separated total count in every rows


SELECT GroupId,LEN(GroupMembers) - LEN(REPLACE(GroupMembers, ',', ''))+1 as TotalGroupMembes
FROM GroupsDetails



Out put



happy coding..

Saturday, April 30, 2011

how to create windows service and how to create windows service setup and deployment

This post will explain following questions

1)How to Create windows service

2)How to create Windows Service installation using Msi

How to Create windows service
-----------------------------

Step 1:(Create Windows Service Project Using Visual Studio)


File-->New-->Project-->Visual C#(Visual basic)-->Windows-->Windows Service-->Ok


step 2: select service1.cs and View Code


protected override void OnStart(string[] args)
{
//Here we can Write code what we need to on while service Started.

EventLog.WriteEntry("service created");
}

protected override void OnStop()
{
//Here we can Write code what we need to on while service stopping.

EventLog.WriteEntry("service created");
}


step 3: (need to add service installer)
Select the service1.cs design view and right click the designer view
then select add installer.



Project installer file will create automatically


sample screen:



step 4 : Project installer --->select service installer1 tool--->properties-->
update following fields
1) starttype == Automatic
2)description , display Name ect... for service related information
fields you can add

step 5 : Project installer --->select serviceprocessinstaller1-->properties
Account-->Local system(it won't ask user name password,if you select user then we need to pass user name like domainname\username, password)

step 6:select project -->properties -->application-->startup object-->select your project program file


step 7:build and release the file



using installutil.exe we can test windows service,it will be located dot net framework 2.0 folder.



using command prompt installing windows service

installutil C:\servicetest.exe


using command prompt Uninstalling windows service

installutil /u C:\servicetest.exe




Your service Created,now how we can create setup and deployment file

step 1:
create new setup and deployment project
select setup and deployment project-->right click-->add-->project output-->primary output--Ok


step 2:
select project-->right click-->view-->Custom actions-->



select custom actions-->right click-->Application folder-->
primary output from servicename(Active)-->ok


step 3:
Build and test setup file.


happy coding...

Friday, April 29, 2011

using C# how to verify active directory user accounts

Following code will help for developing active directory user account validations

1)System.DirectoryServices assembly need to add the reference for active project


2)following code using we can verify Active directory user account


//For Login buttonClick Event

private void Login_Click(object sender, EventArgs e)
{


if (AuthenticateUser("Domain Name", "User Name", "passWord"))
{
MessageBox.Show("User Logged In");
}
else
{
MessageBox.Show("Unable to Authenticate Using the Supplied Credentials");

}

}


//verfication methoed

public bool AuthenticateUser(string domainName, string userName, string password)
{
bool ret = false;

try
{
DirectoryEntry de = new DirectoryEntry("LDAP://" + domainName,
userName, password);
DirectorySearcher dsearch = new DirectorySearcher(de);
SearchResult results = null;

results = dsearch.FindOne();

ret = true;
}
catch
{
ret = false;
}

return ret;
}

happy coding.....

Thursday, March 24, 2011

C# how to call Javascript

If You are using asp.net ajax(script manger) you can write the following code


ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "Facility", "alert('Select any Facility');", true);

Grid view eval value pass to JavaScript arguments

Following sample Code will help how to pass JavaScript arguments

Sample Code
===========
javascript
-----------

function showPropertiesPage(databound)
{

}

Aspx Code
----------

Thursday, March 17, 2011

using Visual studio how to create setup file (dot net Framework offline install)

Following steps will explain about how to create setup files in visual studio (how to add offline dot net Framework)

1)Add new Project (other project types-->setup and Deployment-->setup project)
ref:



2)select setup and Deployment project (Right Click--> add-->project output)


3) select--> Primary out put-->Ok



4)following Image will show project detected dependencies(dot net framework will be online install,if you want to give an application client online means ,above steps ok,you can build the application can give the exe,if some clients want offline install means following more steps required.




5)select setup and Deployment project-->properties-->prerequisites...->select .net Framework 3.5-->select -->download prerequisites from same location as my application-->ok




6)offline Framework exe you can get your visual studio cd.

happy coding...

Friday, February 25, 2011

How to set iframe content controls value from Parent page

hi guys following sample will help for set iframe content controls value from Parent page

Parent page
-----------

..body onload="setiframevalues()"/..

function setiframevalues() {
window.frames[0].document.getElementById('txtname').value = "Welcome";
window.frames[0].document.getElementById('txtname2').value = "Manikandan";

}

iframe calling page Sample
----------------------------

Name
.....input id="txtname" type="text" ...

name2
...input id="txtname2" type="text"...

Saturday, February 12, 2011

Sql Server Start /Stop Services using bat file

how To prepare Bat file for Starting and stopping sql server Services

1)For Starting Sql Server Services

Create the Notepad File

NET START MSSQL$SQLEXPRESS

Save as *.Bat File


1)For stopping Sql Server Services

Create the Notepad File

NET STOP MSSQL$SQLEXPRESS

Save as *.Bat File

Happy Coding....

Thursday, February 3, 2011

Asp.net using C# open Fullscreen popup page or same page as fulll screen

Hi.,

Following Code Will help for, Open any page as full screen Page.
And it will avoid same page opens multiple Times

Sample Code

protected void FullScreenMode()
{
StringBuilder FullScreenScript = new StringBuilder();
//Check the name of the opened window in order to avoid of window re-open over and over again...
FullScreenScript.Append("if(this.name != 'InFullScreen')");
FullScreenScript.Append("{" + Environment.NewLine);
FullScreenScript.Append("window.open(window.location.href,'InFullScreen','fullscreen=yes,menubar=yes,toolbar=yes,status=yes,scrollbars=auto');" + Environment.NewLine);
FullScreenScript.Append("}");
this.ClientScript.RegisterStartupScript(this.GetType(), "InFullScreen", FullScreenScript.ToString(), true);
}

Wednesday, February 2, 2011

Access Modifiers (C# Programming Guide)

All types and type members have an accessibility level, which controls whether they can be used from other code in your assembly or other assemblies. You can use the following access modifiers to specify the accessibility of a type or member when you declare it:

public
The type or member can be accessed by any other code in the same assembly or another assembly that references it.

private
The type or member can be accessed only by code in the same class or struct.

protected
The type or member can be accessed only by code in the same class or struct, or in a class that is derived from that class.

internal
The type or member can be accessed by any code in the same assembly, but not from another assembly.

protected internal
The type or member can be accessed by any code in the assembly in which it is declared, or from within a derived class in another assembly. Access from another assembly must take place within a class declaration that derives from the class in which the protected internal element is declared, and it must take place through an instance of the derived class type.


Default Access Modifiers
------------------------
Class:
=====

class sample
{
}

Default Access Modifiers :internal

structure:
==========

struct sample
{
}

Default Access Modifiers :internal

Note:
structure Won't support Protected

InterFace:
=========

Interface sample
{
}

Default Access Modifiers :internal


Enum:
====

enum sample
{
}

Default Access Modifiers :Public



Methoeds,Property,Field
========================
Default Access Modifiers :Private

Ineterface Methoeds
===================
Default Access Modifiers :Public


Happy Coding..........

Tuesday, February 1, 2011

how to encrypt viewstate in asp.net

Following Property will use for encrypt the ViewState

1)EnableViewstateMac="true"

2)ViewstateEncryptionMOde="Always"



Note:

If we encrypt the view state means application will get slow..

Friday, January 28, 2011

Asp.net Query string how To Transfer File Location

Following Code will help, who want transfer FileLocation
Like (C:\\manikandan\\resume.doc) one page To another page Using Querystring


Sample Code:=
=============

Parent Page:

String fileFullPath=Server.UrlEncode(C:\\manikandan\\resume.doc);
Response.Redirect(..\Sample.aspx?Loc=fileFullPath);



Child Page:
=============

string FileLocation = string.Empty;

if (!string.IsNullOrEmpty(Server.UrlDecode(Request.QueryString["Loc"].ToString())))
{
FileLocation = Request.QueryString["Loc"].ToString();
}

Thanks ,Happy Coding

Monday, January 24, 2011

c# read value from registry

Hi Guys

Following Code will help for how to read values from registry.

RegistryKey regKeyAppRootforET = Registry.LocalMachine.OpenSubKey("SOFTWARE\\YourApplicationName\\KeyName");
if (regKeyAppRootforET != null)
{
if (regKeyAppRootforET.GetValue("KeyName") != null)
{
registryValue = regKeyAppRootforET.GetValue("stringorbinaryKey").ToString();
}
}

Friday, January 21, 2011

Javascript Tips

1)How To Reload the Parent Page Using Javascript

top.location.reload(true);

2)How To Create New Line in Javascript

using "\\n"

sample

alert('sample First Line\\n test')

Using C# Start/Stop Sql Server Services

Following Code will help for starting and stoping Sql Server Services using C#
Code

Sample Code:

ServiceController service = new ServiceController("MSSQL$SQLEXPRESS");//Check sqlexpress service running.
//Sql Serverservice how to stop
if (service.Status == ServiceControllerStatus.Running)
{
service.Stop();
service.Refresh();
}
//Sql Serverservice how to start
if (service.Status == ServiceControllerStatus.Running)
{
service.Stop();
}
}

Thursday, January 13, 2011

asp.net ajaxtoolkit modalpopupextender open server side and cleint Side

Following code will help for how to open ajaxtoolkit modalpopupextender

how it can open via server side code (c#) or cleient Side code

javascript
==========
var launch = false;
function launchModal() {
launch = true;
}

function pageLoad() {
if (launch) {
$find("modalpopupextender client id need to pass here").show();
}
}

Client Side
============

OnClientClick="launchModal()"

serverside:=
============

Following code need to write in any button control click event

ClientScript.RegisterStartupScript(this.GetType(), "key", "launchModal();", true);

Using Javascript Read /Write Cookies

Following Code Will help For Reading And Writing cookie

sample code
============


How To Create
createCookie("slidingpane", "dock", 1);
How To Read
var pane = readCookie("slidingpane")



Ref Function

function createCookie(name, value, days) {
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
var expires = "; expires=" + date.toGMTString();
}
else var expires = "";
document.cookie = name + "=" + value + expires + "; path=/";
}

function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') c = c.substring(1, c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
}
return null;
}

function eraseCookie(name) {
createCookie(name, "", -1);
}

Tuesday, January 11, 2011

JavaScript get Browser height and width and Set into Div

This Article will help for following

1) how To get all Browser Height and Width
2) Dynamically change the div height and width based on browser height and width
3) get the Browser Name

Sample Javascript File
=======================

function() {

var frame = document.getElementById("main");
var htmlheight = document.body.parentNode.scrollHeight;
var windowheight = window.innerHeight;

if (whichBrs() == "Internet Explorer") {
if (htmlheight < windowheight)
{ frame.style.height = windowheight - 150 + "px"; }
else { frame.style.height = htmlheight - 150 + "px"; }

}
else {

if (htmlheight < windowheight) {
frame.style.height = windowheight - 150 + "px";


}
else {
frame.style.height = htmlheight - 150 + "px";

}

}

}




function whichBrs() {
var agt = navigator.userAgent.toLowerCase();
if (agt.indexOf("opera") != -1) return 'Opera';
if (agt.indexOf("staroffice") != -1) return 'Star Office';
if (agt.indexOf("webtv") != -1) return 'WebTV';
if (agt.indexOf("beonex") != -1) return 'Beonex';
if (agt.indexOf("chimera") != -1) return 'Chimera';
if (agt.indexOf("netpositive") != -1) return 'NetPositive';
if (agt.indexOf("phoenix") != -1) return 'Phoenix';
if (agt.indexOf("firefox") != -1) return 'Firefox';
if (agt.indexOf("safari") != -1) return 'Safari';
if (agt.indexOf("skipstone") != -1) return 'SkipStone';
if (agt.indexOf("msie") != -1) return 'Internet Explorer';
if (agt.indexOf("netscape") != -1) return 'Netscape';
if (agt.indexOf("mozilla/5.0") != -1) return 'Mozilla';
if (agt.indexOf('\/') != -1) {
if (agt.substr(0, agt.indexOf('\/')) != 'mozilla') {
return navigator.userAgent.substr(0, agt.indexOf('\/'));
}
else return 'Netscape';
} else if (agt.indexOf(' ') != -1)
return navigator.userAgent.substr(0, agt.indexOf(' '));
else return navigator.userAgent;
}

Monday, January 10, 2011

Asp.net ReportViewer how to clear if no records found

asp.net report viewer, if initially load all records then if you are changing the filter and your result returns no records means you can see what you got last result it will maintain in report viewer how you can clear,following sample code will help

Sample code :
------------------

Reportviewer1.Reset();

REportviewer1.LocalReport.Refresh();

Asp.net Gridview Page Size Increase Dynamically

Asp.net Run time How We can increase page size dynamically using Gridview PageSizeChangeEventArgs event we can achieve the dynamic page Size , following code will explain


Sample Code:
protected void gv1_PageSizeChange(object sender, PageSizeChangeEventArgs e)

{

gv1.PageSize= e.NewPageSize;

gv1.PageIndex = 0;

BindGrid();

}

asp.net using Crystal report opening pdf inside the web page

Following code will explain asp.net without asking open prompt ,automatically open the pdf file inside aspx

sample Code:
=============


public class WebForm1 : System.Web.UI.Page
{
protected CrystalDecisions.Web.CrystalReportViewer CrystalReportViewer1;
protected System.Web.UI.WebControls.Button Button1;
private CrystalReport1 report = new CrystalReport1();
private void Page_Load(object sender, System.EventArgs e)
{
// Put user code to initialize the page here
CrystalReportViewer1.ReportSource = report;
CrystalReportViewer1.Visible = true;
}





-

private void Button1_Click(object sender, System.EventArgs e)
{
MemoryStream oStream; // using System.IO
oStream = (MemoryStream)
report.ExportToStream(
CrystalDecisions.Shared.ExportFormatType.PortableDocFormat);
Response.Clear();
Response.Buffer= true;
Response.ContentType = "application/pdf";
Response.BinaryWrite(oStream.ToArray());
Response.End();
}

Sql Server Get table data (.csv) excuting bat file

How To get sql server Table all records in Csv file by excuting .bat file in Client machine

sample Bat file

1)Open Notepad

2)SQLCMD -S .\SQLEXPRESS -d DatabaseName -E -Q "select * from tableName" -o "FileName.csv" -h-1 -s"," -w 700

3)save as .bat File

Sunday, January 9, 2011

Export Excel From DataGrid using C#

Hi Guys.,
Using c# we need to Export To Excel from datagrid .Following Code will help For you


sample Code:

// create the DataGrid and perform the databinding
System.Web.UI.WebControls.DataGrid grid = new System.Web.UI.WebControls.DataGrid();
grid.HeaderStyle.Font.Bold = true;

DataSet ds = new DataSet();
ds.ReadXml("File Location");
grid.DataSource = ds.Tables[0];
//grid.DataMember = data.Stats.TableName;

grid.DataBind();

// render the DataGrid control to a file
using(StreamWriter sw = new StreamWriter(textBox1.Text))
{
using(HtmlTextWriter hw = new HtmlTextWriter(sw))
{
grid.RenderControl(hw);
}
}
}

Monday, January 3, 2011

usage of Global.axax in asp.net

Following Example will help for maintaining web application

Sample Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;
using System.Diagnostics;

namespace DemoaboutGloabalasax
{
public class Global : System.Web.HttpApplication
{
// int visTeedCount = 0;
///
/// The Application Started it will fire
/// When the iis Start at the time it will fire
///

///
///
protected void Application_Start(object sender, EventArgs e)
{
EventLog.WriteEntry("Sample Application", "Application Started!", EventLogEntryType.Information);

}

protected void Session_Start(object sender, EventArgs e)
{
//visTedCount = visTedCount + visTedCount;
}

protected void Application_BeginRequest(object sender, EventArgs e)
{

}

protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
///need to validate Active Directory User Details here
///
}

///
/// This Event Will fire When the application close
/// Ex: iisreset it will fire
///

///
///
protected void Application_End(object sender, EventArgs e)
{

EventLog.WriteEntry("Sample Application", "Application End at" + DateTime.Now.ToString() + "!", EventLogEntryType.Error);

}
}
}

now You can See all the details about your website in your web server using Event Viewer

1)when the Application Started(iis Started)
2)when the Application Stoped/Restarted(iis Reset)
3)what are the error's occurred in application at what time