Wednesday, December 22, 2010

All Check Boxes check of Respective inner repeater

Step : 1

function CheckAllRoleCheckBoxesParent(obj)
{
//alert(2);
//debugger;
chk = document.documentElement.getElementsByTagName('input');
var Parent=obj.attributes['Parent'].nodeValue;


for(var i=0; i {
if(chk[i].attributes["type"].nodeValue == "checkbox")
{
if(chk[i].attributes['Parent1'] != null)
{
//alert('checkbox');
if(chk[i].attributes['Parent1'].nodeValue==Parent)
{
//alert(chk[i].attributes['rolecode'].nodeValue + '=' + rc);
//chk[i].checked=obj.checked;
chk[i].click();
}
}

}

}
}


Strep : 2

<input id="chk" runat="server" type="checkbox" value='<%#Eval("Location")%>'
onclick="javascript:CheckAllRoleCheckBoxesParent(this);" Parent='<%#Eval("id")%>'/>
<%#Eval("Location")%>


Step:3

protected string Parent1;


Step :4

On Item Databound ofParent

Parent1 = DataBinder.Eval(e.Item.DataItem, "id").ToString();

Thursday, September 16, 2010

Select Distinct from DataTable

public DataSet ds = new DataSet();

DataTable dtDate = SelectDistinct("aaa", dt, "Date");

public DataTable SelectDistinct(string TableName, DataTable SourceTable, string FieldName)
{
DataTable dt = new DataTable(TableName);
dt.Columns.Add(FieldName, SourceTable.Columns[FieldName].DataType);

object LastValue = null;
foreach (DataRow dr in SourceTable.Select("", FieldName))
{
if (LastValue == null || !(ColumnEqual(LastValue, dr[FieldName])))
{
LastValue = dr[FieldName];
dt.Rows.Add(new object[] { LastValue });
}
}
if (ds != null)
ds.Tables.Add(dt);
return dt;
}
private bool ColumnEqual(object A, object B)
{

// Compares two values to see if they are equal. Also compares DBNULL.Value.
// Note: If your DataTable contains object fields, then you must extend this
// function to handle them in a meaningful way if you intend to group on them.

if (A == DBNull.Value && B == DBNull.Value) // both are DBNull.Value
return true;
if (A == DBNull.Value || B == DBNull.Value) // only one is DBNull.Value
return false;
return (A.Equals(B)); // value type standard comparison
}

Impersonation webconfig

<system.web>
<identity impersonate="true" username="Domain\username" password="password">
</system.web>

Impersonation Programmatically

public const int LOGON32_LOGON_INTERACTIVE = 2;
public const int LOGON32_PROVIDER_DEFAULT = 0;

WindowsImpersonationContext impersonationContext;

[DllImport("advapi32.dll")]
public static extern int LogonUserA(String lpszUserName,
String lpszDomain,
String lpszPassword,
int dwLogonType,
int dwLogonProvider,
ref IntPtr phToken);
[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern int DuplicateToken(IntPtr hToken,
int impersonationLevel,
ref IntPtr hNewToken);

[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern bool RevertToSelf();

[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
public static extern bool CloseHandle(IntPtr handle);


private bool impersonateValidUser(String userName, String domain, String password)
{
WindowsIdentity tempWindowsIdentity;
IntPtr token = IntPtr.Zero;
IntPtr tokenDuplicate = IntPtr.Zero;

if (RevertToSelf())
{
if (LogonUserA(userName, domain, password, LOGON32_LOGON_INTERACTIVE,
LOGON32_PROVIDER_DEFAULT, ref token) != 0)
{
if (DuplicateToken(token, 2, ref tokenDuplicate) != 0)
{
tempWindowsIdentity = new WindowsIdentity(tokenDuplicate);
impersonationContext = tempWindowsIdentity.Impersonate();
if (impersonationContext != null)
{
CloseHandle(token);
CloseHandle(tokenDuplicate);
return true;
}
}
}
}
if (token != IntPtr.Zero)
CloseHandle(token);
if (tokenDuplicate != IntPtr.Zero)
CloseHandle(tokenDuplicate);
return false;
}

private void undoImpersonation()
{
impersonationContext.Undo();
}

BindData()

{

if (impersonateValidUser("abc", "abc", "abc"))
{

//work
undoImpersonation();

}
}

Conversion of Datarow [] to Datatable

dt = new DataTable();
dt.Columns.Add("Industries", typeof(string));
dt.Columns.Add("Project", typeof(string));
dt.Columns.Add("FolderName", typeof(string));
dt.Columns.Add("FolderPath", typeof(string));
dt.Columns.Add("Date", typeof(string));

foreach (DataRow dr in dto)
{
dt.ImportRow(dr);
}
dt.AcceptChanges();

dt.Select(Date Filter)

string filter = "[Date] >= '" + Convert.ToDateTime(txtTo.Text).ToShortDateString() + "' AND [Date] <= '" + Convert.ToDateTime(txtFrom.Text).ToShortDateString() + "'";

DataRow[] dto = notDownloaded.Select(filter);
//DataRow[] dto = notDownloaded;

Thursday, June 17, 2010

CSV to DataTable Conversion

public static DataTable csvToDataTable(string file, bool isRowOneHeader)
{

DataTable csvDataTable = new DataTable();

//no try/catch - add these in yourselfs or let exception happen
String[] csvData = File.ReadAllLines(HttpContext.Current.Server.MapPath(file));

//if no data in file ‘manually’ throw an exception
if (csvData.Length == 0)
{
throw new Exception(”CSV File Appears to be Empty”);
}

String[] headings = csvData[0].Split(’,');
int index = 0; //will be zero or one depending on isRowOneHeader

if(isRowOneHeader) //if first record lists headers
{
index = 1; //so we won’t take headings as data

//for each heading
for(int i = 0; i < headings.Length; i++)
{
//replace spaces with underscores for column names
headings[i] = headings[i].Replace(” “, “_”);

//add a column for each heading
csvDataTable.Columns.Add(headings[i], typeof(string));
}
}
else //if no headers just go for col1, col2 etc.
{
for (int i = 0; i < headings.Length; i++)
{
//create arbitary column names
csvDataTable.Columns.Add(”col”+(i+1).ToString(), typeof(string));
}
}

//populate the DataTable
for (int i = index; i < csvData.Length; i++)
{
//create new rows
DataRow row = csvDataTable.NewRow();

for (int j = 0; j < headings.Length; j++)
{
//fill them
row[j] = csvData[i].Split(’,')[j];
}

//add rows to over DataTable
csvDataTable.Rows.Add(row);
}

//return the CSV DataTable
return csvDataTable;

}

Friday, June 11, 2010

Check Box Click Enable Disable Row Elements

Step :1 (JavaScript)

function EnableDisableTextBox(objCheckBox, objName,objName2)
{
try
{
var chk = document.getElementById(objCheckBox);
var CategoryName = document.getElementById(objName);
var CategoryName2 = document.getElementById(objName2);
//var CategoryABBR = document.getElementById(objABBR);

if(chk.checked)
{
clr="FFFFFF";
CategoryName.Enabled = true;
CategoryName.removeAttribute('disabled');
CategoryName.style.background=clr;
CategoryName.focus();

CategoryName2.Enabled = true;
CategoryName2.removeAttribute('disabled');
CategoryName2.style.background=clr;


//CategoryABBR.Enabled = true;
//CategoryABBR.style.background=clr;
// CategoryABBR.removeAttribute('disabled');


}
else
{
//clr="D4D0C8";
clr="F6F6F6";

CategoryName.setAttribute('disabled','disabled');
CategoryName.style.background=clr;
CategoryName.Enabled = false;
CategoryName.value='';
CategoryName2.setAttribute('disabled','disabled');
CategoryName2.style.background=clr;
CategoryName2.Enabled = false;
CategoryName2.value='';
// CategoryABBR.setAttribute('disabled','disabled');
// CategoryABBR.style.background=clr;
// CategoryABBR.Enabled = false;
}

}
catch(e)
{
}

}


Step:2 (CS File)

protected void rptLinks_OnItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
HtmlInputCheckBox chkFunctions = HtmlInputCheckBox)e.Item.FindControl("chkFunctions");
chkFunctions.Attributes.Add("onclick", "EnableDisableTextBox('" + chkFunctions.ClientID + "','" + txtQuantity.ClientID + "','" + txtTo.ClientID + "')");
}

}


Step 3(aspx)


<input id="chkFunctions" runat="server" type="checkbox" />

Thursday, June 3, 2010

Clear all the fields

var elements = document.getElementsByTagName("input");
for (var ii=0; ii < elements.length; ii++) {
if (elements[ii].type == "text") {
elements[ii].value = "";
}
}

Multiple Fields Search Stored Procedure

ALTER PROCEDURE XPS_TemplateSearch
@Template_Name varchar(100) = null,
@TemplateType_Code int = null,
@Subject varchar(200) = null
AS
BEGIN
--select * from [XPS_Template] where Template_Name=@Template_Name or TemplateType_Code=@TemplateType_Code or Subject=@Subject is_Active=1

IF(@Template_Name = '')
SET @Template_Name = null
IF(@TemplateType_Code = -1)
SET @TemplateType_Code = null
IF(@Subject = '')
SET @Subject = null


--DECLARE @Qry VARCHAR(1000)
--SET @Qry = 'select * from [XPS_Template] where is_Active=1 and ( Template_Name like ''%'+@Template_Name+'%'' or TemplateType_Code ='+convert(varchar(20),@TemplateType_Code)+' or Subject Like ''%'+@Subject+'%'')'
--select @Qry
--print @Qry

select *
from [XPS_Template]
where is_Active=1
and Template_Name like case when @Template_Name is not null then @Template_Name
when @Template_Name is null then Template_Name end
and TemplateType_Code = case when @TemplateType_Code is not null then @TemplateType_Code
when @TemplateType_Code is null then TemplateType_Code end
and [Subject] like case when @Subject is not null then @Subject
when @Subject is null then [Subject] end

/*and (
Template_Name like ISNULL(@Template_Name,Template_Name)
or TemplateType_Code = ISNULL(@TemplateType_Code,TemplateType_Code)
or [Subject] like ISNULL(@Subject,[Subject])
)
*/


END

Dynamic Query Like

--SET @Qry = 'select * from [XPS_Template] where is_Active=1 and ( Template_Name like ''%'+@Template_Name+'%'' or TemplateType_Code ='+convert(varchar(20),@TemplateType_Code)+' or Subject Like ''%'+@Subject+'%'')'
--select @Qry
--print @Qry

Wednesday, June 2, 2010

dynamic Query For any Colum name and Value

CREATE PROCEDURE [dbo].[Display_Select_Student]
(
@Col_Name varchar(500)=null,
@Col_Value varchar(500)=null
)

AS
BEGIN
SET NOCOUNT ON;

DECLARE @Qry VARCHAR(1000)
SET @Qry = 'SELECT * FROM [Student] WHERE '+@Col_Name+'='''+@Col_Value+''''

EXEC(@Qry)


SET NOCOUNT OFF;
END

Friday, May 28, 2010

SQL SERVER – DBCC RESEED Table Identity Value – Reset Table Identity

DBCC CHECKIDENT can reseed (reset) the identity value of the table. For example, YourTable has 25 rows with 25 as last identity. If we want next record to have identity as 35 we need to run following T SQL script in Query Analyzer.

DBCC CHECKIDENT (yourtable, reseed, 34)

If table has to start with an identity of 1 with the next insert then table should be reseeded with the identity to 0. If identity seed is set below values that currently are in table, it will violate the uniqueness constraint as soon as the values start to duplicate and will generate error.

Image Uploader

private void UploadLogo(string LogoFileName)
{
if (FileUpload1.HasFile)
{
string fileExt =
System.IO.Path.GetExtension(FileUpload1.FileName);


try
{

if (Directory.Exists(Server.MapPath("..\\AssociateLogos")))
{
//string path = "\\images\\";
string path = "..\\AssociateLogos\\";

int a = LogoFileName.LastIndexOf("/");
string fileName = LogoFileName.Substring(a+1);
string Serverpath = Server.MapPath(path);
FileUpload1.SaveAs(Serverpath +
fileName);
Label1.Text = "File name: " +
FileUpload1.PostedFile.FileName + "
" +
FileUpload1.PostedFile.ContentLength + " kb
" +
"Content type: " +
FileUpload1.PostedFile.ContentType;
}
else
{
Directory.CreateDirectory(Server.MapPath("..\\AssociateLogos"));
string path = "..\\AssociateLogos\\";
string Serverpath = Server.MapPath(path);
FileUpload1.SaveAs(Serverpath +
LogoFileName);
Label1.Text = "File name: " +
FileUpload1.PostedFile.FileName + "
" +
FileUpload1.PostedFile.ContentLength + " kb
" +
"Content type: " +
FileUpload1.PostedFile.ContentType;
}
}
catch (Exception ex)
{
Label1.Text = "ERROR: " + ex.Message.ToString();
}

}
else
{
Label1.Text = "You have not specified a file.";
}
}

Thursday, May 27, 2010

Splitting CSV

#region "Splitting CSV"
private int[] commaStrToArray(string strIntComma)
{ string [] strArray; strArray = strIntComma.Split(new char[] {','}); int [] intArray = new int [strArray.Length]; for (int i = 0; i < strArray.Length; i++) intArray[i] = int.Parse(strArray[i]); return intArray; }


#endregion

Monday, May 24, 2010

Drop Down List Select All

ddlKeywords.Items.Insert(0, new ListItem("--All--", "-1"));

Temp Table Creation Insertion and Display

declare @table table(id int identity(1,1),userid int, Fullname varchar(250),DepartmentName)
insert into @table(userid,Fullname,DepartmentName)
select distinct a.userid , fullname ,deptname from table1
select * from @table

Open Child Window

function OpenWinForUpdation(code)
{
//window.open(url,'meeting Mangement','toolbar=0,width=900,height=600');
window.open('Abc.aspx?fc='+code,'Roza','toolbar=0,width=1200,height=800,scrollbars=yes');
//window.location.href = url;
}

JQuery Accordian

function openDiv()
{
//$('#openDiv').click(function() {
// alert( $('#divContent'));
$('#ShowHide').slideToggle('slow');

// });
}


Child Window Closed

ScriptManager.RegisterClientScriptBlock(this, GetType(), "Cl", "alert('Keyword Added Successfully'); self.close();", true);

Child Window Closed and Parent Refresh

Just Write this on button submit event

ScriptManager.RegisterClientScriptBlock(this, GetType(), "Cl", "alert('Keyword Added Successfully');opener.location.href = opener.location.href;this.close();", true);

ALternate

ScriptManager.RegisterClientScriptBlock(this, GetType(), "Cl", "parent.hs.close();parent.location.href = parent.location.href;", true);

Find any keyword used in any stored procedure

select distinct name from sysobjects sc
inner join syscomments sc2
on sc.id = sc2.id
where
sc2.text like '%between%'
order by name desc

Date Btween Date Range check

select top 500 convert(datetime,LastUpdated_Date,101),* from contactDetails
where convert(datetime,LastUpdated_Date,101) between convert(datetime,'Apr 01, 2009',101) and convert(datetime,'May 31, 2010',101)

DropDown Lsit Filter Search Stored Procedure

CREATE PROCEDURE [dbo].[SR_SelectProjectsDetailsForSpecificStatusWithSpecificUser]
@Portal_User_ID INT,
@Project_status_code INT,
@Category_Code int
AS

BEGIN

SET NOCOUNT ON
IF(ISNULL(@Project_status_code,0) > 0)
BEGIN
SELECT Project.Project_Code, Project.Project_Name, Project.Project_type_Code, Project.Project_Type_Details, Project.Project_status_code,
Project.Project_DeadLine, ProjectCategory.Category_Name, ProjectStatus.Project_Status_Name, ProjectType.Project_Type_Name,
ProjectResource.Portal_User_ID, ProjectResource.Role_Code, ProjectResource.Project_code AS Expr1
FROM Project (NOLOCK)
INNER JOIN ProjectStatus (NOLOCK)
ON Project.Project_status_code = ProjectStatus.Project_Status_code
INNER JOIN ProjectCategory (NOLOCK)
ON Project.Category_Code = ProjectCategory.Category_Code
INNER JOIN ProjectType (NOLOCK)
ON Project.Project_type_Code = ProjectType.Project_Type_Code
INNER JOIN ProjectResource (NOLOCK)
ON Project.Project_Code = ProjectResource.Project_code
WHERE Project.Project_status_code=@Project_status_code and ProjectResource.Portal_User_ID=@Portal_User_ID and Project.Category_Code=@Category_Code
ORDER BY Project.Project_Code DESC

END
ELSE
BEGIN
SELECT Project.Project_Code, Project.Project_Name, Project.Project_type_Code, Project.Project_Type_Details, Project.Project_status_code,
Project.Project_DeadLine, ProjectCategory.Category_Name, ProjectStatus.Project_Status_Name, ProjectType.Project_Type_Name,
ProjectResource.Portal_User_ID, ProjectResource.Role_Code, ProjectResource.Project_code AS Expr1
FROM Project (NOLOCK)
INNER JOIN ProjectStatus (NOLOCK)
ON Project.Project_status_code = ProjectStatus.Project_Status_code
INNER JOIN ProjectCategory (NOLOCK)
ON Project.Category_Code = ProjectCategory.Category_Code
INNER JOIN ProjectType (NOLOCK)
ON Project.Project_type_Code = ProjectType.Project_Type_Code
INNER JOIN ProjectResource (NOLOCK)
ON Project.Project_Code = ProjectResource.Project_code
WHERE ProjectResource.Portal_User_ID=@Portal_User_ID and Project.Category_Code=@Category_Code
ORDER BY Project.Project_Code DESC

END
SET NOCOUNT OFF

END

Export Crystal Reports to PDF file

Reports are used by business for various management purposes. Crystal reports is very versatile and easy to use reporting tool that is bundled with the Microsoft Visual Studio .Net. There have been many enhancements in the latest version of crystal reports which make it simpler for developers to export reports directly to the HTTP response object.
Read More http://www.beansoftware.com/asp.net-tutorials/export-crystal-reports-to-pdf.aspx