Sunday, November 23, 2008

Search a Stored Procedure the Date Which we added

USE yourDatabaseName;
GO
SELECT name, create_date, modify_date
FROM sys.objects
WHERE type = 'P'
AND name = 'uspYourSearchingSPName'
GO



OR

-- to get all sps

USE yourDatabaseName;
GO
SELECT name, create_date, modify_date
FROM sys.objects
WHERE type = 'P'

GO

Thursday, October 9, 2008

using range validater its easy to validate the Only accept futuredate filed

//in your page load add following codes

rvDelivery.MinimumValue = DateTime.Now.ToShortDateString();
rvDelivery.MaximumValue = DateTime.MaxValue.ToShortDateString();

//Add a customer validator to the page and change this values only
controleto validate : your txtboxname
validation group: your validation group
type: Date

Navigate throught List box using C#

System.Text.StringBuilder sbVender = new System.Text.StringBuilder();

sbVender.Append("<VENDORS>");
foreach (ListItem item in lbVendors.Items)
{
if (item.Selected)
{
sbVender.AppendFormat("<VENDOR VendorId=\"{0}\" />", item.Value.ToString());
}
}
sbVender.Append("</VENDORS>");

Register Ajecx pro with webconfgig C#

//when closing selection group</sectionGroup>
<sectionGroup name="ajaxNet">
<section name="ajaxSettings" type="AjaxPro.AjaxSettingsSectionHandler,AjaxPro.2" requirePermission="false" restartOnExternalChanges="true"/>
</sectionGroup>

//When nexto the

//</appSettings> Closing
<ajaxNet>
<ajaxSettings>
<urlNamespaceMappings useAssemblyQualifiedName="false" allowListOnly="false">
<!--
Set the attribute useAssemblyQualifiedName to true to enable
use of assemblies placed in the GAC by using the full assembly
qualified name.

To hide internal knowledge of assemblies, classes and namespace
you can override the name of the virtual http endpoints.

<add type="Namespace.Class1,Assembly" path="mypath" />
-->
</urlNamespaceMappings>
<jsonConverters>
<!--
This section can be used to add new IJavaScriptConverters to the
Ajax.NET Professional engine. If you want to disable built-in
converters you can use the remove tag.

<remove type="Namespace.Class1,Assembly"/>
<add type="Namespace.Class2,Assembly"/>

<add type="AjaxPro.BitmapConverter,AjaxPro.2" mimeType="image/jpeg" quality="100"/>
-->
</jsonConverters>
<!--
Set the enabled attribute to true to get Stack, TargetSize and Source
information if an exception has been thrown.
-->
<debug enabled="false"/>
<!--
This is the default configuration used with Ajax.NET Professional. You
can put there your static JavaScript files, or remove the path attribute
to completly disable the files.

<scriptReplacements>
<file name="prototype" path="~/ajaxpro/prototype.ashx" />
<file name="core" path="~/ajaxpro/core.ashx" />
<file name="converter" path="~/ajaxpro/converter.ashx" />
</scriptReplacements>
-->
<!-- <encryption cryptType="" keyType="" /> -->
<!--
Set the enabled attribute to true to enable the use of an Ajax.NET Professional
token. This will send a token to the client that will be used to identify if the
requests comes from the same PC.
-->
<token enabled="false" sitePassword="password"/>
<!--
The oldStyle section can be used to enable old styled JavaScript code or
functions that are not used any more.

<oldStyle>
<objectExtendPrototype/>
<appCodeQualifiedFullName/>
<allowNumberBooleanAsString/>
<sessionStateDefaultNone/>
<includeMsPrototype/>
<renderDateTimeAsString/>
<noUtcTime/>
</oldStyle>
-->
</ajaxSettings>
</ajaxNet>

<location path="ajaxpro">
<system.web>
<pages validateRequest="false"/>
<httpHandlers>
<add verb="*" path="*.ashx" type="AjaxPro.AjaxHandlerFactory,AjaxPro.2"/>
</httpHandlers>
<!--
If you need to have Ajax.NET Professional methods running on the
login page you may have to enable your own authorization configuration
here.
-->
<!-- SESSION STATE SETTINGS
By default ASP.NET uses cookies to identify which requests belong to a particular session.
If cookies are not available, a session can be tracked by adding a session identifier to the URL.
To disable cookies, set sessionState cookieless="true".

-->
</system.web>
</location>

validate restict future days/back dates

function checkDate(s,e)
{
var strSplit = e.Value.split("/");
var month = eval(strSplit[0]);
var year = eval(strSplit[2]);
var date = eval(strSplit[1]);

var validDate= new Date(year,month-1,date);
var systemDate = new Date();

if ( systemDate > validDate)
{
e.IsValid = true;
}
else
{
e.IsValid = false;
}
}


//and then create

customer validato

change only this properties
clemt validation functionality=checkDate
controletovalidate=your txtbox name
display=dynamic
errormessage=your error message
change validation group acordingly (Recomended)

validate the onlynumber for text box like money (13245.55)dot allowed using java scripts

function isDecimalKey(evt)
{
var charCode = (evt.which) ? evt.which : event.keyCode

if(charCode==46)
{

return true;
}
else
{
if (charCode > 31 && (charCode < 48 || charCode > 57))
return false;
}
return true;

}

//in the copd addthe follown=ing to the text box event

onkeypress="return isDecimalKey(event)"

using lnk button and Navigate to another URL

if (e.Row.RowType == DataControlRowType.DataRow)
{
try
{
LinkButton lnkbuttonPay = ((LinkButton)e.Row.Cells[2].FindControl("LinkButton1"));
if (lnkbuttonPay != null)
{
lnkbuttonPay.PostBackUrl = "../Vendor/PayVendorOutStanding.aspx?Vendorid=" + gvVender.DataKeys[e.Row.RowIndex].Values[0].ToString() + "&venderName=" + gvVender.DataKeys[e.Row.RowIndex].Values[1].ToString() + "&Outstanding=" + gvVender.DataKeys[e.Row.RowIndex].Values[2].ToString();

}
}
catch (Exception ex)
{
if (Master.CurrentUser != null)
SLStopException.WriteEventLogs(ex, Constants.Database_Connection_Name, string.Empty + "-Admin");
else
SLStopException.WriteEventLogs(ex, Constants.Database_Connection_Name, "Anonymous-Admin");
}
}

validation Using regular expression validation

^\d{1,5}(\.\d{1,2})?$
format should be
XXXX.XX

1-5 . and 1 to 2 digits

rawdatabound handlingand disabling link in datagrid acordingly

protected void gvOrderPhotoPrint_RowDataBound(object sender, GridViewRowEventArgs e)
{
try
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
LinkButton lnkDelete = (LinkButton)e.Row.FindControl("lnkPhotoOrderDelete");
string Status = gvOrderPhotoPrint.DataKeys[e.Row.RowIndex]["ClientStatusDisplay"].ToString().Trim();
if (lnkDelete != null)
{
lnkDelete.Attributes.Add("onclick", "return ConfirmDelete();");
if (Status == "In Progress")
{
lnkDelete.Enabled = false;
}

}


}
}
catch (Exception ex)
{

}
}

histry object in java script history.forward

other methods

Method
back() Loads the previous URL in the history list
forward() Loads the next URL in the history list
go() Loads a specific page in the history list

java script validation for easy numeric only text field

//java script validation for easy numeric only text field
function isNumberKey(evt)
{
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57))
return false;
return true;

}

//source code method calling area


valuble validation expresion for format $XXXX.XX

^\d{1,5}(\.\d{1,2})?$

format should be $XXXX.XX

Advance search using xml (SQL Query)

SELECT vwCarReservationsforVendorCost.VendorId, vwCarReservationsforVendorCost.VendorName, SUM(isnull (vwCarReservationsforVendorCost.VendorcostinRs,0)) AS Total,Sum (isnull(tblVendorPaymentVouchers.Amount,0)) AS AmountPaid, (SUM(isnull (vwCarReservationsforVendorCost.VendorcostinRs,0))-Sum (isnull(tblVendorPaymentVouchers.Amount,0))) AS Outstanding
FROM vwCarReservationsforVendorCost
LEFT OUTER JOIN tblVendorPaymentVouchers ON
tblVendorPaymentVouchers.VendorId=vwCarReservationsforVendorCost.VendorId
WHERE (ReservedDate >= @OrderDateFrom OR @OrderDateFrom = '01/01/1900') AND
(ReservedDate<=@OrderDateTo OR @OrderDateTo='01/01/1900') AND
(vwCarReservationsforVendorCost.vendorId in (SELECT VendorId FROM OPENXML (@iDoc, '/VENDORS/VENDOR',1) WITH (VendorId INT)) OR @Vendors='')
GROUP BY vwCarReservationsforVendorCost.VendorId,vwCarReservationsforVendorCost.VendorName



//this is how you enter the parameters from front end

foreach (ListItem item in lbDeliveryService.Items)
{
if (item.Selected)
{
sbVender.AppendFormat("", item.Value.ToString());
}
}
sbVender.Append("");


DataSet ds = OBJOrder.SearchVendorDeliverCostAnalysisReports(fromDate, toDate, sbVender.ToString());

Usefull String for mattings in C#

"No formatting: " + theDecNumber.ToString();
"Currency formatting: " + theDecNumber.ToString("C");
"Exponential formatting: " + theDecNumber.ToString("E");
"Fixed-point formatting: " + theDecNumber.ToString("F2");
"General formatting: " + theDecNumber.ToString("G");
"Number formatting to 2 decimal places: " + theDecNumber.ToString("N2");
"Number formatting to 3 decimal places: " + theDecNumber.ToString("N3");
"Number formatting to 4 decimal places: " + theDecNumber.ToString("N4");
"Percent formatting: " + theDecNumber.ToString("P0");

Go thoroug list box and get the values whic checked

foreach (ListItem item in lbVendors.Items)
{
if (item.Selected)
{
sbVender.AppendFormat("", item.Value.ToString());
}
}

Tuesday, August 26, 2008

Create Sql server Function and call it as requred (2 input parameters)

CREATE FUNCTION [dbo].[ufIsUserHavingDependendency]
(
@UserId int,
@RoleId int
)
RETURNS int
AS

BEGIN

DECLARE @IsAssigned BIT
DECLARE @Count INT
DECLARE @mRoleId INT
SET @mRoleId=@RoleId
SET @Count = 0

--if role is Supervisor or admin

IF @mRoleId='2' OR @mRoleId='1'
BEGIN

--1.Has created or assigned Courses. (Supervisor)
SELECT @Count = COUNT(tblUserCreatedCourses.UserId) FROM tblUserCreatedCourses
WHERE tblUserCreatedCourses.UserId = @UserId AND @mRoleId<>1
IF(@Count>0)
return 1

--2. Has directly assigned Courses. (Student)
SELECT @Count = COUNT(tblCourse.CourseId) FROM tblCourse
WHERE tblCourse.SupervisorUserId = @UserId
IF(@Count>0)
return 1

-- SELECT @Count = COUNT(tblStudentCourse.StudentId) FROM tblStudentCourse
-- WHERE tblStudentCourse.StudentId=@UserId
-- IF(@Count>0)
-- return 1

--06. Has created ad hoc Question/s? (Supervisor)
SELECT @Count = COUNT(tblCourse.CourseId) FROM tblCourse
INNER JOIN tblQuestion
ON tblQuestion.CourseId= tblCourse.CourseId
WHERE tblCourse.SupervisorUserId = @UserId AND tblQuestion.CourseId <>'0'
IF(@Count>0)
return 1

--07. Has created Course based Question/s? (Supervisor)
SELECT @Count = COUNT(tblQuestion.QuestionId) FROM tblQuestion
WHERE tblQuestion.OwnerId = @UserId AND tblQuestion.CourseId ='0'
IF(@Count>0)
return 1

--09. Has non confirmed Course based Exam/s. (Supervisor)
SELECT @Count = COUNT(tblQuestionPaper.PaperId) FROM tblQuestionPaper
WHERE tblQuestionPaper.OwnerId = @UserId AND tblQuestionPaper.CourseId ='0'
IF(@Count>0)
return 1

--10
SELECT @Count = COUNT(tblCourse.CourseId) FROM tblCourse
INNER JOIN tblQuestionPaper
ON tblCourse.CourseId= tblQuestionPaper.CourseId
WHERE tblCourse.SupervisorUserId = @UserId AND tblQuestionPaper.CourseId <>'0'
IF(@Count>0)
return 1

--17 To 21
SELECT @Count = COUNT(tblUserExam.UserId) FROM dbo.tblUserExam
INNER JOIN dbo.tblQuestionPaper
ON tblQuestionPaper.PaperId=tblUserExam.PaperId
INNER JOIN dbo.tblCourse
ON tblCourse.CourseId=tblQuestionPaper.CourseId
WHERE tblCourse.SupervisorUserId =@UserId AND tblQuestionPaper.CourseId<>'0'
IF(@Count>0)
return 1

--Add hoc
SELECT @Count = COUNT(tblUserExam.UserId) FROM dbo.tblUserExam
INNER JOIN dbo.tblQuestionPaper
ON tblQuestionPaper.PaperId=tblUserExam.PaperId
WHERE dbo.tblQuestionPaper.OwnerId=@UserId AND tblQuestionPaper.CourseId='0'

IF(@Count>0)
return 1

--22
SELECT @Count = COUNT(dbo.tblVideoUser.UserId) FROM dbo.tblVideoUser
WHERE dbo.tblVideoUser.UserId=@UserId
IF(@Count>0)
return 1

END

ELSE IF @mRoleId='3'
BEGIN
--05
SELECT @Count = COUNT(dbo.tblCurriculumStudent.StudentId) FROM dbo.tblCurriculumStudent
WHERE tblCurriculumStudent.StudentId=@UserId
IF(@Count>0)
return 1

--23
SELECT @Count = COUNT(tblNotifications.NotificationID) FROM tblNotifications
INNER JOIN dbo.tblUserNotifications
ON tblNotifications.NotificationID=tblUserNotifications.NotificationID
WHERE dbo.tblUserNotifications.UserID=@UserId AND dbo.tblNotifications.NotificationType='1'--for alert
IF(@Count>0)
return 1

--26
SELECT @Count = COUNT(tblCourseRequest.StudentId) FROM tblCourseRequest
WHERE tblCourseRequest.StudentID=@UserId AND tblCourseRequest.ApprovedStatus='Pending'
IF(@Count>0)
return 1

--27
SELECT @Count = COUNT(tblExamRequest.StudentID) FROM tblExamRequest
WHERE tblExamRequest.StudentID=@UserId
IF(@Count>0)
return 1

--12
SELECT @Count = COUNT(tblUserExam.UserId) FROM tblUserExam
WHERE tblUserExam.UserId=@UserId
IF(@Count>0)
return 1

--13 check student is involved to a course
SELECT @Count = COUNT(tblStudentCourse.StudentId) FROM tblStudentCourse
WHERE tblStudentCourse.StudentId=@UserId
IF(@Count>0)
return 1
END

ELSE

BEGIN
return 0
END

return -3
END
//


//Calling the function sql stored procedure

SELECT tblUsers.Title,
tblUsers.UserID,
tblUsers.UserName,
tblUsers.FirstName,
tblUsers.LastName,
tblUnit.UnitName,
tblRole.RoleId,
tblRole.Description As RoleName,
tblGroups.GroupName,
tblUsers.LastLogDate,
tblUsers.IsActive,
tblUsers.IsSelfRegister,
dbo.ufIsUserHavingDependendency(tblUsers.UserID,tblUsers.RoleID) AS IsUserHavingDependendency,

Data row bound event hadling for hyperlink url whit query string

Data row bound event handling for hyper link url whit query string

protected void gvCourseList_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
HyperLink lnkBtn = (HyperLink)e.Row.Controls[2].Controls[0];
if(lnkBtn != null)
{
lnkBtn.NavigateUrl = "AssignMedia.aspx?CourseId=" + gvCourseList.DataKeys[e.Row.RowIndex].Values["CourseId"].ToString();
}

}
}

Image Curser to hand html and javascript

//Image Curser to hand
style ="cursor:pointer;"

Handaling data row bound event as required C# Asp.net

Handaling data row bound event

protected void gvAvailableVideos_RowDataBound(object sender, GridViewRowEventArgs e)
{
try
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
LinkButton lbtnVideoFile = ((LinkButton)e.Row.Cells[0].FindControl("lbtnVideoFile"));
if (lbtnVideoFile != null)
{
lbtnVideoFile.Text = gvAvailableVideos.DataKeys[rowno]["VideoFileName"].ToString();
DataView dv = DsMediaFiles.Tables[0].DefaultView;
dv.Sort = "id";
int rowId = dv.Find(gvAvailableVideos.DataKeys[rowno]["Id"]);
string VideoPath = string.Empty;
int VideoId;
if (rowId != -1)
{
VideoPath = System.Configuration.ConfigurationManager.AppSettings["StreamingServerPath"].ToString() + dv[rowId]["VideoPath"].ToString();
VideoId = Convert.ToInt32(dv[rowId]["Id"].ToString());
lbtnVideoFile.Attributes.Add("OnClick", "return SetMovie('" + VideoPath + "','" + VideoId + "')");
}

}

HyperLink hlnkAttachment = ((HyperLink)e.Row.Cells[2].FindControl("hlnkAttachment"));
if (hlnkAttachment != null)
{
hlnkAttachment.Text = gvAvailableVideos.DataKeys[rowno]["AttachmentName"].ToString();
hlnkAttachment.NavigateUrl = gvAvailableVideos.DataKeys[rowno]["AttachmentPath"].ToString();
hlnkAttachment.Target = "_blank";
}
rowno += 1;

if (e.Row.Cells[1].Text.Length > Convert.ToInt32(Constants.GridCharactorLength))
{
e.Row.Cells[1].ToolTip = e.Row.Cells[1].Text;
e.Row.Cells[1].Text = e.Row.Cells[1].Text.Substring(0, Convert.ToInt32(Constants.GridCharactorLength)) + "....";
//e.Row.Cells[1].Text = e.Row.Cells[1].Text.ToUpper();

}

}
}

Changing a dataset and datagrid values as you required

////////this is CreateVideoDataSet()
private DataSet CreateVideoDataSet()
{
try
{ //id,videfilename,videopath,Attachment path,attachmentName,course title
DataSet dsNewVideo = new DataSet();
DataTable dt = new DataTable();
DataColumn dc;


dc = new DataColumn();
dc.DataType = System.Type.GetType("System.Int64");
dc.ColumnName = "Id";
dc.Unique = true;
dt.Columns.Add(dc);

dc = new DataColumn();
dc.DataType = System.Type.GetType("System.String");
dc.ColumnName = "VideoFileName";
dc.Unique = false;
dt.Columns.Add(dc);

dc = new DataColumn();
dc.DataType = System.Type.GetType("System.String");
dc.ColumnName = "VideoPath";
dc.Unique = false;
dt.Columns.Add(dc);

dc = new DataColumn();
dc.DataType = System.Type.GetType("System.String");
dc.ColumnName = "AttachmentPath";
dc.Unique = false;
dt.Columns.Add(dc);

dc = new DataColumn();
dc.DataType = System.Type.GetType("System.String");
dc.ColumnName = "AttachmentName";
dc.Unique = false;
dt.Columns.Add(dc);

dc = new DataColumn();
dc.DataType = System.Type.GetType("System.String");
dc.ColumnName = "CourseTitle";
dc.Unique = false;
dt.Columns.Add(dc);

dc = new DataColumn();
dc.DataType = System.Type.GetType("System.Boolean");
dc.ColumnName = "IsAvailableToAll";
dc.Unique = false;
dt.Columns.Add(dc);

dsNewVideo.Tables.Add(dt);
return dsNewVideo;
}

//in the page load
public void FillDataToGrid()
{
try
{
IVideo objIVideo = new IVideo();
DsMediaFiles = objIVideo.GetAvailableVideos();
DataSet dsNewVideo = CreateVideoDataSet();

foreach (DataRow dr in DsMediaFiles.Tables[0].Rows)
{
string LotNos = string.Empty;
DataRow[] found = DsMediaFiles.Tables[0].Select("Id=" + Convert.ToInt32(dr["Id"]));
if (found.Length > 0)
{
for (int i = 0; i < found.Length; i++)
{

LotNos += found[i]["CourseTitle"].ToString() + ",";
}

DataRow[] drows = dsNewVideo.Tables[0].Select("id=" + Convert.ToInt32(dr["id"]));
if (drows.Length == 0)
{
DataRow row1 = dsNewVideo.Tables[0].NewRow();
row1["Id"] = dr["Id"];
row1["VideoFileName"] = dr["VideoFileName"];
row1["VideoPath"] = dr["VideoPath"];
row1["AttachmentPath"] = dr["AttachmentPath"];
row1["AttachmentName"] = dr["AttachmentName"];
row1["IsAvailableToAll"] = dr["IsAvailableToAll"];
row1["CourseTitle"] = LotNos.TrimEnd(',');

if (row1["IsAvailableToAll"].ToString() == "True")
{
row1["CourseTitle"] = "";
}

dsNewVideo.Tables[0].Rows.Add(row1);
}



}
}

if (dsNewVideo != null && dsNewVideo.Tables[0].Rows.Count > 0)
{
gvAvailableVideos.DataSource = dsNewVideo.Tables[0];
gvAvailableVideos.DataBind();
Session["DsMediaFiles"] = dsNewVideo;
}

else
{
gvAvailableVideos.DataSource = null;
gvAvailableVideos.DataBind();
TrNoRecords.Visible = true;
gvAvailableVideos.Visible = false;

}
}

format sql date and time only date like format

CAST( (convert(varchar(12), @expDate,102)) as varchar)

Configure sql mail - Sql server

Configure sql mail Basic steps
//Run followings in sql query window

use master
go
sp_configure 'show advanced options',1
go
reconfigure with override
go
sp_configure 'Database Mail XPs',1
--go
--sp_configure 'SQL Mail XPs',0
go
reconfigure
go





EXECUTE msdb.dbo.sysmail_add_account_sp
@account_name = 'MyMailAccount',
@description = 'Mail account for Database Mail',
@email_address = 'Sanjeewa@mail.com',
@display_name = 'MyAccount',
@username='Sanjeewa@alliontechnologies.com',
@password='tExt123',
@mailserver_name = 'mail.yourmail.com'


EXECUTE msdb.dbo.sysmail_add_profile_sp
@profile_name = 'MyMailProfile',
@description = 'Profile used for database mail'

EXECUTE msdb.dbo.sysmail_add_profileaccount_sp
@profile_name = 'MyMailProfile',
@account_name = 'MyMailAccount',
@sequence_number = 1

EXECUTE msdb.dbo.sysmail_add_principalprofile_sp
@profile_name = 'MyMailProfile',
@principal_name = 'public',
@is_default = 1 ;

//Send a test mail
declare @body1 varchar(100)
set @body1 = 'Server :'+@@servername+ ' My First Database Email xxxyyii'
EXEC msdb.dbo.sp_send_dbmail @recipients='Sanjeewa@Mail.com',
@subject = 'My Mail Test',
@body = @body1,
@body_format = 'HTML' ;

cast dateTime in the data base to Same Format And Compare Two days acordingly

SELECT * FROM dbo.tblCourse where convert(varchar(12), [ExpireDate],102)=convert(varchar(12), getdate(),102)


//Example 2

SELECT UserId,Email,firstName,tblCourse.CourseTitle FROM tblUsers INNER JOIN tblCourse
ON tblUsers.UserId = tblCourse.CreatedBy
WHERE UserId IN (SELECT DISTINCT CreatedBy
FROM dbo.tblCourse)
AND convert(varchar(12), [ExpireDate],102)=convert(varchar(12), getdate(),102)

Restricting max lenth of message box - java script

function MaxLengthRestrictTextBox(s,e)
{

if(e.Value.length > 6000 )
{
e.IsValid = false;
return false;
}

e.IsValid = true;
}

changing image button delete to disable in row bound event C#

protected void gvCourses_RowDataBound(object sender, GridViewRowEventArgs e)
{
try
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
ImageButton btnEdit = (ImageButton)e.Row.FindControl("btnEdit");
if (btnEdit != null)
{

btnEdit.PostBackUrl = "EditCourse.aspx?Tab=1&CourseId=" + gvCourses.DataKeys[e.Row.RowIndex].Values["CourseId"].ToString();
}

ImageButton btnDelete = (ImageButton)e.Row.FindControl("btnDelete");
if (btnDelete != null)
{
string IsAssinged = gvCourses.DataKeys[e.Row.RowIndex].Values["IsCourseAssignedtoaUser"].ToString();
string DoesCourseHasRequest = gvCourses.DataKeys[e.Row.RowIndex].Values["CourseHasRequests"].ToString();
if (IsAssinged == "1")
{
btnDelete.Enabled = false;
btnDelete.ToolTip = Constants.MSG_Course_Assignedorexamcreated;
btnDelete.ImageUrl = "~/Images/btnRomoveDisable.gif";
}
else
{
btnDelete.Enabled = true;
btnDelete.Attributes.Add("onclick", "return ConfirmCourseDelete('" + DoesCourseHasRequest + "');");

}
}
}
}

catch (Exception ex)
{

}
}

Create a Html table dynamically by c# Code

private void LoadForumItems(int mainForumId)
{
ForumItem objForumItems = new ForumItem();
DataSet dsForumItems = objForumItems.GetForumItemsByForumId(mainForumId);

int MainForumId = 0;
int x = 1;
//int j = 1;
HtmlTable htmlMainTable = new HtmlTable();
TrForumItems.Cells[0].Controls.Add(htmlMainTable);
htmlMainTable.Attributes.Add("width", "100%");

//if check the ds empty here
foreach (DataRow dr in dsForumItems.Tables[0].Rows)
{
if (MainForumId != Convert.ToInt32(Request.QueryString["MainForumId"]))
{
HtmlTableRow htmlForumItemRow = new HtmlTableRow();

//Empty Left Cell
HtmlTableCell htmlForumItemEmptyCellLeft = new HtmlTableCell();
htmlForumItemEmptyCellLeft.InnerHtml = " ";
htmlForumItemEmptyCellLeft.Attributes.Add("width", "10");
htmlForumItemEmptyCellLeft.Attributes.Add("class", "tableItems");
htmlForumItemRow.Cells.Add(htmlForumItemEmptyCellLeft);

//Description Cell
HtmlTableCell htmlForumItemCellDescription = new HtmlTableCell();
htmlForumItemCellDescription.InnerHtml = dr["Description"].ToString();
htmlForumItemCellDescription.Attributes.Add("width", "400");
htmlForumItemCellDescription.Attributes.Add("class", "tableItems");
htmlForumItemRow.Cells.Add(htmlForumItemCellDescription);

//Cell reply button
HtmlTableCell htmlForumItemCellButton = new HtmlTableCell();
HyperLink link = new HyperLink();
link.CssClass = "";
link.ToolTip = "Reply";
link.NavigateUrl = "ReplyForum.aspx?ParentId=" + dr["ForumItemId"].ToString() + "&MainForumId=" + dr["MainForumId"].ToString();
link.ImageUrl = "~/Images/btnPostReply.gif";
htmlForumItemCellButton.Attributes.Add("class", "tableItems");

//Create empty cell
HtmlTableCell htmlForumItemEmptyCell = new HtmlTableCell();
htmlForumItemEmptyCell.InnerHtml = "";
htmlForumItemEmptyCell.Attributes.Add("width", "100");
htmlForumItemEmptyCell.Attributes.Add("valign", "top");
htmlForumItemEmptyCell.Controls.Add(link);
htmlForumItemEmptyCell.Attributes.Add("class", "tableItems");
htmlForumItemRow.Cells.Add(htmlForumItemEmptyCell);

//Owner Name cell
HtmlTableCell htmlForumItemCellOwnerName = new HtmlTableCell();
htmlForumItemCellOwnerName.InnerHtml = dr["OwnerName"].ToString();
htmlForumItemCellOwnerName.Attributes.Add("class", "tableItems");
htmlForumItemRow.Cells.Add(htmlForumItemCellOwnerName);

//Cell date time
HtmlTableCell htmlForumItemCellDate = new HtmlTableCell();
htmlForumItemCellDate.InnerHtml = dr["CreateDate"].ToString();
htmlForumItemCellDate.Attributes.Add("class", "tableItems");
htmlForumItemRow.Cells.Add(htmlForumItemCellDate);

//Add rows to html table
htmlMainTable.Rows.Add(htmlForumItemRow);

if (x > 1)
{
//Create empty row
HtmlTableRow htmlEmptyRow = new HtmlTableRow();
HtmlTableCell htmlEmptyCell = new HtmlTableCell();
htmlMainTable.Rows.Add(htmlEmptyRow);

HtmlTableRow htmlEmptyRow2 = new HtmlTableRow();
HtmlTableCell htmlEmptyCell2 = new HtmlTableCell();
htmlMainTable.Rows.Add(htmlEmptyRow2);
}
x += 1;
}
}
}

Friday, May 2, 2008

check file extention of a file using C# Sanjeewa sapumana

//check file extention of a file using C# Sanjeewa sapumana

private bool CheckMediaFileExtention()
{
string UploadedMediaFileName = btnFileUploadSelectMediaFile.FileName;
string[] file = new string[2];
file= UploadedMediaFileName.Split('.');

if (file.Length < 2)
{
return false;
}

string fileext = file[1].ToLower();

if (fileext == "wmv" || fileext == "avi")
{
return true;
}
else
{
TrMessage.Visible = true;
lblError.Text = Constants.MSG_Notifications_EnterSpecifiedMovieFormat.ToString();
lblError.CssClass = Structures.MessegeTypeCSS.MessageError.ToString();
return false;
}

}

get the window closing event using javascript and calling method you required - Sanjeewa sapumana

window.onunload = abort;
function abort()
{
//your Java script or Ajax method as you like
StopMovie();
PlayMedia.UpdateTime(videoviewTime.toString());
}

Create Directery in c# coding is so easy like this - Sanjeewa Sapumana

System.IO.Directory.CreateDirectory(@"C:\New Folder");

create a property dataset for coding C# - Sanjeewa Sapumana

//This will provide easy and convenient way of using property C#

#region Properties

DataSet DsCourseList
{
get
{
if (dsCourseList == null)
{
try
{
Course objCourse = new Course();
DataSet dsTemp;
dsTemp = objCourse.GetAllExamPaperDetails();
if (dsTemp != null && dsTemp.Tables[0].Rows.Count > 0)
{
dsCourseList = dsTemp;
Session["dsCourseList"] = dsCourseList;
}
}
catch (Exception ex)
{
ex.Data.Add("UILayerException", this.GetType().ToString() + MyTutorErrorMesseges.Error_Seperator + "DataSet DsCourseList GEt {}");
Response.Redirect("../Error.aspx?LogId=" + MyTutorException.WriteEventLogs(ex, Constants.Database_Connection_Name, Master.LoggedUser.UserName), false);
}
}
return dsCourseList;
}
set
{
dsCourseList = value;
}
}

#endregion

add attribute to data rowbound of Datagrid (Confirmation java script) -Sanjeewa Sapumana

lb.Attributes.Add("onClick", "ExamConfirm('" + Constants.MSG_Notifications_ExamConfirmation.ToString() + "')");

Create List box item for Default value its quite simple like this

ddlVideos.Items.Insert(0, (new ListItem("--Select Video--", "0")));

Check file extention and validate Client side easily- Sanjeewa sapumana

<script language="javascript" type="text/javascript">

/*To check file extensions */
function checkFileExtension( s,e ){
parafilevalue =document.getElementById("FileUpload1").value
var file = parafilevalue.split('.');

var validType = false;

if( file.length < 2 )
{
return false;
}

var fileext = file[1].toLowerCase();

if( fileext == 'doc' || fileext == 'pdf'|| fileext == 'xls' || fileext == 'ppt'|| fileext == 'txt' )
{
validType = true;
}
if(validType==false)
{
alert("Please enter specified document type");
var who= document.getElementsByName('FileUpload1')[0];
var who2= who.cloneNode(false);
who2.onchange = who.onchange;
who.parentNode.replaceChild(who2,who);
}
return validType;

}
< /script >

Tuesday, April 8, 2008

Add navigate url for the Datagrid using row data bound event (Template colum Used in hear)- Sanjeewa Sapumana

protected void gvCourseList_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
LinkButton lnkAssign = (LinkButton)e.Row.Cells[2].Controls[1];
if (lnkAssign != null)
{
lnkAssign.PostBackUrl = "AssignCourse.aspx?PaperId=" + gvCourseList.DataKeys[e.Row.RowIndex].Values["PaperId"].ToString();
}

LinkButton lnkAssignUser = (LinkButton)e.Row.Cells[3].Controls[1];
if (lnkAssignUser != null)
{
lnkAssignUser.PostBackUrl = "AssignUsers.aspx?PaperId=" + gvCourseList.DataKeys[e.Row.RowIndex].Values["PaperId"].ToString();
}
}
}

Friday, March 7, 2008

How to Enable AjaxPro to your Websiteand call ajax Method Sanjeewa sapumana

(1)//add ajax pro dll
AjaxPro.2.dll

(2)//add this codes to page load here type of=Class name
AjaxPro.Utility.RegisterTypeForAjax(typeof(PlayMedia));

(3)//Add this code top of the method
[AjaxPro.AjaxMethod()]

(4)//your method here
public void UpdateTime(string strVideoViewTimeInMinute)
{
}

(5)//Add this codes for the Web config





(6)//call your method acording event

//IN HTML call the method as this
PlayMedia.UpdateTime(videoviewTime.toString());

Thursday, March 6, 2008

javaScript Call function in every 1 sec(or any time period) Sanjeewa sapumana

//javascript
//in milisecond
var intervaltime=1000;
//Call function in every 1000 milisecond (1 sec)
state=setInterval("ProgressBarUpdate()",intervaltime);
//Finish time out
clearTimeout ( timeoutId );

Friday, February 29, 2008

Creating a folder in the server using asp.net -sanjeewa sapumana

//Check folder is exist
DirectoryInfo dInfo = new DirectoryInfo
(Server.MapPath( strMediaFileSavePath));

//Create Folder and add files
if (!dInfo.Exists)
{
//dInfo.CreateSubdirectory("@"+strMediaFileSavePath);
System.IO.Directory.CreateDirectory
(Server.MapPath(strMediaFileSavePath));


if (this.AddVideo())
{
return true;
}
else
{
return false;
}
}

Tuesday, February 26, 2008

Create a client javascript popup using client script manager C#- Sanjeewa Sapuman

ClientScript.RegisterClientScriptBlock(this.GetType(), "script", "< script language='javascript' > alert('Video File already exist from the server.');</script >");

Creating a Web streaming movie pager using C# and javascript- Sanjeewa Sapumana

//play a movie
//java script windows media player calling by java script
function SetMovie(mpath)

{
//var mediaName="myVideoName";
alert("Declared variables");

if (mpath == " ")
{
alert("apath is a empty");
}

else

document.getElementById('VideoPlayer').URL=mpath;
alert(document.getElementById('VideoPlayer').URL);
document.getElementById('VideoPlayer').controls.play();


alert("now video is playing");
return false;
}

//Defining the windows media player object in html code

< object type="application/x-oleobject" width="421" height="248" id="VideoPlayer" classid="CLSID:6BF52A52-394A-11d3-B153-00C04F79FAA6">
< param name="autostart" value="True" / >
< param name="showcontrols" value="false" / >
//in this case wer taking the url from the datagr id link list
< !--< param name="src" value="MediaFiles//YourMovie.wmv" / >-- >
< /object >


//datra grid databinding
protected void gvAvailableVideos_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
LinkButton lbtnVideoFile = ((LinkButton)e.Row.Cells[0].FindControl("lbtnVideoFile"));
if (lbtnVideoFile != null)
{
lbtnVideoFile.Text = gvAvailableVideos.DataKeys[rowno]["VideoFileName"].ToString();
DataView dv = DsMediaFiles.Tables[0].DefaultView;
dv.Sort = "id";
int rowId = dv.Find(gvAvailableVideos.DataKeys[rowno]["Id"]);
string VideoPath=string.Empty;
if(rowId != -1)
{
VideoPath = dv[rowId]["VideoPath"].ToString();
lbtnVideoFile.Attributes.Add("OnClick", "return SetMovie('" + VideoPath + "')");
}

}
rowno += 1;
}


//datagrid handiling html view

< asp:GridView ID="gvAvailableVideos" runat="server" Width="100%" AllowPaging="True" OnRowDataBound="gvAvailableVideos_RowDataBound" AutoGenerateColumns="False" DataKeyNames="Id,VideoFileName" >
< Columns >
< asp:TemplateField HeaderText="VideoFileName" >
< ItemTemplate >
< asp:LinkButton ID="lbtnVideoFile" CommandArgument='< %# Eval("VideoFileName")% >' runat="server" > </asp:LinkButton >
< /ItemTemplate >
< /asp:TemplateField >
< asp:BoundField DataField="AttachmentName" HeaderText="Attachment Name" / >
< /Columns >
< /asp:GridView >

Friday, February 22, 2008

Create a simple Movie player For html site

< object type="video/x-ms-wmv"
data="YourMovie.wmv" width="320" height="260" >
<param name="src" value="YourMovie.wmv" />
<param name="autostart" value="true" />
<param name="controller" value="true" />

</object >

Thursday, February 21, 2008

Creating mail Class Using C# dotnet (2005VS)

public bool SendEmailUserRegistration(string strEmailFrom, string strEmailTo, string strMailSubject ,string strMailBody,string username,string password)
{
try
{
SmtpClient smtp = new SmtpClient(System.Configuration.ConfigurationSettings.AppSettings["SmtpServer"]);
smtp.Host = "127.0.0.1";
smtp.Port = Convert.ToInt32(System.Configuration.ConfigurationSettings.AppSettings["Port"]);

MailMessage message = new MailMessage(strEmailFrom, strEmailTo);
message.From = new MailAddress(strEmailFrom,"Admin");
message.Subject = System.Configuration.ConfigurationSettings.AppSettings["MessageSubjectUserCreation"].ToString();
message.IsBodyHtml = true;
message.Body = System.Configuration.ConfigurationSettings.AppSettings["MessageBodyUserCreation"].ToString() +"User Name: " + username+ "
" +"Password: "+ password;

//smtp.Send(strEmailFrom, "Name@Company.com", "test subject", strMailBody);
smtp.Send(message);
return true;
}
catch (Exception ex)
{
return false;
}
}

Wednesday, February 20, 2008

Change the maximum file upload size supported by ASP.NET

Indicates the maximum file upload size supported by ASP.NET. This limit can be used to prevent denial of service attacks caused by users posting large files to the server. The size specified is in kilobytes. The default is 4096 KB (4 MB).

Add this code to webconfig
==========================

system.web
httpRuntime maxRequestLength="2097151" executionTimeout="3600"
system.web

Monday, February 18, 2008

Create a dataset Using Specified colum name and to data table C# code

DataSet dsTemp = new DataSet();
//dsTemp = null;
int recqty = 0;

DataTable dtAddNewItems = new DataTable();
DataColumn[] columns = {
new DataColumn("Product_No"),
new DataColumn("Qty_Received"),
new DataColumn("Certificates"),
new DataColumn("CertificateContentType"),
new DataColumn("TransportDamage"),
new DataColumn("PurrchaseQty"),
new DataColumn("Lot_No"),
new DataColumn("Qty_Returned")

};

dtAddNewItems.Columns.AddRange(columns);
dsTemp.Tables.Add(dtAddNewItems);

Find a list Box is Checked (has a list count) using java script

function listBoxisChecked(s,e)
{
var Lstbox=document.getElementById('ctl00_ContentPlaceHolder2_lbxAssignedGroup');

if(Lstbox.options.length == 0)
{
e.IsValid = false;

return;
}
e.IsValid = true;

}

Get Print screen Popup using javascript

html
head
script type="text/javascript">
windows.print();
/script
/head
/html

Friday, February 8, 2008

Random password Creator C# code

public static string CreateRandomPassword(int PasswordLength)
{
string _allowedChars = "abcdefghijkmnopqrstuvwxyzABCDEFGH­JKLMNOPQRSTUVWXYZ0123456789!@$?";
Random randNum = new Random();
char[] chars = new char[PasswordLength];
int allowedCharCount = _allowedChars.Length;
for (int i = 0; i < PasswordLength; i++)
{
chars[i] = _allowedChars[(int)((_allowedChars.Length) * randNum.NextDouble())];
}
return new string(chars);
}