Pages

Thursday 4 August 2011

Displaying Festival Names on Calendar control in ASP.Net

0 comments
 
Tags : Festival Names,Calendar Control,Importance of the day,Asp.Net,C#.Net,SQL Server.

Hi Friends,In this article i would like to explain how to display Festival Names on Calender control in ASP.Net.


* For this i took 1 Calendar control on to the page.

* I created a table with name(Holidays) in SQL Server 2005 & fields are HolidayName,HolidayDate.

* Please find the below table once :



* Then find the code for Calender_DayRender event :

Source Code :

Default.aspx.cs :
using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
SqlConnection con;
protected void Page_Load(object sender, EventArgs e)
{
con = new SqlConnection(ConfigurationManager.ConnectionStrings["DotnetGuruConnectionString"].ConnectionString);
}
protected void Calendar1_DayRender(object sender, DayRenderEventArgs e)
{
CalendarDay day = (CalendarDay)e.Day;
SqlCommand cmd = new SqlCommand("select HolidayName,HolidayDate from Holidays", con);
con.Open();
SqlDataReader dr = cmd.ExecuteReader();

while (dr.Read())
{
if (day.Date.ToString() == dr["HolidayDate"].ToString())
{
TableCell cell = (TableCell)e.Cell;
string s1 = dr["HolidayName"].ToString();
if (s1 != null)
{
cell.BackColor = System.Drawing.Color.LightGray;
cell.Controls.Add(new LiteralControl("
" + s1));
}

}

}
con.Close();
}
}
Design View :

Default.aspx :


 















* Then finally Build(F6) your application & run the application by pressing(F5) button.

* Your out put will looks like as below :
Thank You...

Readmore...
Tuesday 2 August 2011

Logical Operators in SQL Server.

0 comments
 
Tags : Logical Operators,Sql Server 2005,Sql Server 2008,Sql Server Operators.

Hi Friends,In this article i would like to explain Logical Operators in SQL Server.

* Logical operators, like comparison operators, return a Boolean data type with a value of TRUE, FALSE, or UNKNOWN.

* Available Logical Operators :


1) AND:

Performs a logical AND operation. The expression evaluates to TRUE if all conditions are TRUE.

Example :

SELECT * FROM Class
WHERE ( Marks > 40 AND Marks < 100)


2) OR :

Performs a logical OR operation. The expression evaluates to TRUE if atleast one condition is TRUE.

Example :

SELECT * FROM Class
WHERE EmployeeName LIKE 'K%' OR Marks > 40


3) BETWEEN :

It returns TRUE if the operand is within a range otherwise FALSE.

Example :

Select * from Employee
WHERE EmpSalary BETWEEN 5000 AND 15000


4) IN :

This Operator returns TRUE if the operand is equal to one of a list of expressions Otherwise flase.

Example :

SELECT * FROM Students
WHERE StudentId IN(SELECT StudentId FROM CSEDEPT WHERE CSEDeptID=20)


5) EXISTS :

Specifies a subquery to test for the existence of rows.

Example :

SELECT * FROM Students WHERE EXISTS
(
SELECT * FROM Students WHERE CollegeCode='B2'
)


6) LIKE :

Determines whether a specific character string matches a specified pattern.

Example :

SELECT * FROM EnggColleges
WHERE CollegeName LIKE 'S%'

Here,it will return all the records which has 's' as first letter in CollegeName


7) ALL :

It Returns TRUE if all of a set of comparisons are TRUE other wise returns FALSE

Example :

SELECT * FROM Employee
WHERE EMPLOYEEID >= ALL (SELECT EMPLOYEEID from Salary WHERE Salary>5000 )


8) ANY :

ANY returns TRUE when the comparison specified is TRUE for ANY pair, otherwise, returns FALSE.

Example :

SELECT * FROM Colleges WHERE 20000 > ANY
(
SELECT CollegeFess FROM Colleges
)


9) Not :

NOT operator is used To find rows that do not match a value.

Example :

SELECT * FROM Colleges
WHERE CollegeCode NOT IN (50,100,150,200)


Thank You...
Readmore...
Monday 1 August 2011

Difference between Varchar and NVarchar in SQL Server.

2 comments
 
Tags : Varchar ,NVarchar ,Varchar(n),NVarchar(n),SQL Server,String,Length,Difference.

Hi Friends,in this post i would like to explain difference between Varchar
& NVarchar in SQL Server.

*
The data type Varchar and NVarchar are the sql server data types, both will used to store the string values.

Differences :

1
Character Data Type

Varchar - Non-Unicode Data
NVarchar - Unicode Data

2 Character Size

Varchar - 1 byte
NVarchar - 2 bytes

3 Maximum Length

Varchar
- 8,000 bytes
NVarchar - 4,000 bytes

4 Storage Size

Varchar - Actual Length (in bytes)
NVarchar - 2 times Actual Length (in bytes)


* The abbreviation for Varchar is Variable Length character String.

* The abbreviation of NVarchar is uNicode Variable Length character String.



Thank You...
Readmore...
Sunday 31 July 2011

String Functions in SQL Server.

1 comments
 
Tags : String Functions,Sql Server 2005,Sql Server 2008.

Hi Friends,in this article i would like to explain String Functions in SQL Server.

* LEN (string) - Returns the length of the given string.

For Example :

select len(Address) as Address from Employee


* LEFT (string, length) - Returns the specified number of characters from the beginning of the string.

For Example :

Select LEFT(Address,1) as Address from Employee


* RIGTH (string, length) - Returns the specified number of characters from the end of the string.

For Example :

Select RIGHT(Address,2) as Address from Employee


* REVERSE (string) - Returns the given string in reverse order.

For Example :

Select Reverse(Address) as Address from Employee


* UPPER (string) - Converts the given string into uppercase letters.

For Example :

Select UPPER(Address) as Address from Employee


* LOWER(string) - Converts the given string into lowercase letters.

For Example :

Select LOWER(Address) as Address from Employee


* SPACE (integer) - Returns the string with the specified number of space characters.

For Example :

Select SPACE(1) as Address from Employee



* LTRIM (string) - LTRIM function to return a character expression after removing leading spaces.

For Example :

Select LTRIM(Address) as Address from Employee


* RTRIM (string) - RTRIM function to return a character expression after removing trailing spaces.

For Example :

Select RTRIM(Address) as Address from Employee



* SUBSTRING (string, start, length) - Returns the specified number of characters from the string starting at the specified position.

For Example :

Select SUBSTRING (Address, 1, 4) as Address from Employee


Thank you...
Readmore...
Saturday 30 July 2011

How to start and stop triggers in sql server?

1 comments
 
Tags : Enable Trigger,Disable Trigger,SQL Server 2005,SQL Server 2008,Triggers,Start,Stop.

Hi Friends,in this post i would like to explain enabling and disabling triggers in SQL Server.

* By writing Commands we can Start/Stop triggers in SQL Server.


Enabling/Starting Trigger :

Enable Trigger TriggerName ON database.dbo.tablename


Disabling/Stopping Trigger :

Disable Trigger TriggerName ON database.dbo.tablename


Thank You...
Readmore...

SQL Server Triggers.

1 comments
 
Tags : SQL Server 2005,SQL Server 2008,Triggers,DML Triggers,DDL Triggers,Logon Triggers.

Hi Friends,in this post i would like to explain Triggers in SQL Server.

* It is one kind of stored procedure, but triggers neither accept nor return any values.

* Trigger is an action which can be execute automatically.

* It is defined to execute automatically when the specified event is occurred.

Types of Triggers :


1) DML Triggers :

These triggers executes automatically when data manipulation language event occurs. DML events are insert,update,delete.

2) DDL Triggers :

These triggers executes when data definition language events such as create,alter,drop occurs.

3) Logon Triggers :

These triggers fires for logon events.


Difference between Trigger & Stored Procedure :

1) Trigger is implicit execution where as Stored Procedure is explicit execution.

2) Triggers doesn't allow any parameters & doesn't return any values.Stored Procedure can allow parameters & return values.


Advantages :

* We can schedule tasks basing on events.

Disadvantage :

* It is burden because triggers run on database.
* It is difficult to track the changes done by triggers on database.


Thank you...


Readmore...
Tuesday 19 July 2011

How to insert data into XML file?

1 comments
 

Tags : Insert,Data,XML File,Asp.Net,C#.Net

Hi Friends,in this post i would like to explain how to insert data into XML file.

* Here in my example i am stored Name,Location,Email & Gender fields into XML file.For this i took 3 TextBoxes,DropDownList for Gender,Button & a label for displaying message.

* Added XML file with name(InsertData)
For this Go To SolutionExplorer-->Right Click on ApplicationName-->AddNewItem-->Select XML File-->Give Name as InsertData-->Click on Add button.


Design View :









Source Code :

Default.aspx.cs :
using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}

protected void ButtonInsertXML_Click(object sender, EventArgs e)
{
// Open the XML doc
System.Xml.XmlDocument myXmlDocument = new System.Xml.XmlDocument();
myXmlDocument.Load(Server.MapPath("InsertData.xml"));
System.Xml.XmlNode myXmlNode = myXmlDocument.DocumentElement.FirstChild;

// Create new XML element and populate its attributes
System.Xml.XmlElement myXmlElement = myXmlDocument.CreateElement("entry");
myXmlElement.SetAttribute("Name", Server.HtmlEncode(TextBoxName.Text));
myXmlElement.SetAttribute("Location", Server.HtmlEncode(TextBoxLocation.Text));
myXmlElement.SetAttribute("Email", Server.HtmlEncode(TextBoxEmail.Text));
myXmlElement.SetAttribute("Gender", Server.HtmlEncode(DropDownListGender.SelectedItem.Text));


// Insert data into the XML doc and save
myXmlDocument.DocumentElement.InsertBefore(myXmlElement, myXmlNode);
myXmlDocument.Save(Server.MapPath("InsertData.xml"));

// Re-bind data since the doc has been added to
BindData();

LabelMessage.Text = "Record inserted Successfully Inside the XML File...";

TextBoxName.Text = "";
TextBoxLocation.Text = "";
TextBoxEmail.Text = "";

}

void BindData()
{
XmlTextReader myXmlReader = new XmlTextReader(Server.MapPath("InsertData.xml"));
myXmlReader.Close();

}
}



* Then finally Build & Run the application & insert sample input data.It will automatically insert data into InsertData.xml file.


Thank You...
Readmore...
Saturday 2 July 2011

Example on Windows Service

1 comments
 
Hi Friends,in this post i would like to explain windows service for displaying message box for every 3 seconds.

Step 1:

* Open windows service project with projectName WinService1
* Goto ToolBox-->General-->Right Click-->Select choose items-->Select Timer(Systems.Timers)
* Project-->AddReference-->System.Windows.Forms(Message Box is a part of above reference).
* Place a Timer(System.Timers) with interval-3000 & enabled-false.

Code:

{//timer1_Elapsed event.
System.Windows.Forms.MessageBox.Show("This message from Windows Service.");
}

Code for OnStart() event
{
timer1.Enabled=true;
}

Code for OnStop() event
{
timer1.Enabled=false;
}


Step 2:

* Open service1.cs[design]
Right Click
Add installer(Select).
Then 2 controls will be added to the form.
1)ServiceProcessInstaller-->Choose properties-->Account=LocalSystem.
2)ServiceInstaller-->Properties-->ServiceName=MessageBoxDisplay

* Build the project(Build-->Select Build solution)

Note:
* WinService1.exe is created under:
D:\WinService1\bin\debug folder with a service name called as "MessageBoxDisplay"

Step 3:

* open .Net Command prompt.
Start-->Programs-->MSVisualStudio2005-->VSTools-->.Net Command Prompt.
>installutil -i D:\WinService1\bin\debug\WinService1.exe (press enter)
>....
>....
>....
>transaction install has completed.

Step 4:

* Open service(Start-->run-->services.msc)
* MessageBoxDisplay-->RightClick-->Properties-->Logon-->Check "interact with desktop" checkBox-->OK
(Only service contains MessageBox otherwise above step is not required).
* MessageBoxDisplay-->rightClick-->Start.

Then service will be started & MessageBox with message(This message from Windows Service.) will be displayed for every 3 seconds.


Thank You...


Readmore...

Introduction to Windows Services.

1 comments
 

Hi friends,in this post i would like to explain some basic things to know about windows services.



* A service which is under control of windows OS is called windows service.
* Windows services are used to develop automated background processes.
* Windows services contains only application logic but not GUI(Graphical User Interface).
* The controls which are not visible at runtime,can be placed in windows service projects.



For example:
Timer Control,Event log control,File system watcher control.



* To develop windows services .Net provided:
File-->NewProject-->VisualC#-->Windows-->WindowsServiceTemplate.
* Windows service project is avilable in VisualStudio .Net 2005 professional edition,but not available in Standard edition.
* To develop windows service .Net provided a name space:
System.ServiceProcess(NameSpace).
* All the windows services will be stored at:
Start-->Settings-->ControlPanel-->AdministrativeTools-->Services
OR
Start-->run-->Services.msc
* While a service is starting OnStart() event will be executed & while stoping OnStop() event will be executed.



Steps for developing Windows Service:



1)Open windows service project & wrie the required logic.
2)Add the installers & build the project to get an exe file as output.
3)Open .Net command prompt & install exefile with following syntax:
installutil -i exefile path //for installing the service.
installutil -u exefile path //for uninstalling the service.
4)Start the service.




Thank you...

Readmore...

Saving images to our application.

0 comments
 
Hi Friends,in this post i would like to explain how to save images from our PC to application.

* For this i took one FileUpLoad control, Button control and a Label control for displaying message.

Add the following name space:
using System.IO;

Code for button click event():

protected void Button1_Click(object sender, EventArgs e)
{
try
{
string filePath = FileUpload1.PostedFile.FileName;


string filename = Path.GetFileName(filePath);

FileUpload1.PostedFile.SaveAs(@"F:\\Asp.Net\FileUpload\Images\" + filename);

Label1.Text = "Image uploaded successfully.";
}
catch
{
Label1.Text = "Failed to upload image.";
}
}


Note:
F:\\Asp.Net\FileUpload is the application path.
Created Images folder in my application and saving uploaded images into Images folder.

Thank you...

Readmore...

Unique Key on 2 columns in SQL Server.

1 comments
 
Hi friends,in this post i would like to explain how to create Unique Key on 2 columns in SQL Server.

For Example:

Here i am created Unique Key for 2 columns(Name,SurName) on College table.

CREATE TABLE [dbo].[College] ADD CONSTRAINT [UK_College] UNIQUE NONCLUSTERED
(
[Name] ,
[SurName]
)
WITH (PAD_INDEX = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, ONLINE = OFF) ON [PRIMARY]

Thank you...

Readmore...

Set Operators in SQL Server.

2 comments
 
Hi Friends,in this post i would like to explain Set Operators in SQL Server.

*Set Operators are used to combined the data from multiple tables.

Set Operators:
1)UNION
2)UNION ALL
3)INTERSECT
4)EXCEPT

Syntax:
Select query1

Select query2

Select query3

......
......
......

1)UNION
*UNION can select only distinct/unique rows & rows can be arranged in ascending order.

2)UNION ALL
*UNION ALL is used to combine all rows from the given select queries.

3)INTERSECT
* UNION ALL is used to select only common rows from the given set of select queries.

4)EXCEPT
* EXCEPT is equalent to Minus operator in Oracle.To select all rows from the first query,except second query output.

Limitations:
* All queries should have equal number of columns.
* Corresponding column data types should be same.

Thank you...

Readmore...
Monday 20 June 2011

Constraints in SQL Server.

1 comments
 

Hi Friends, in this post I would like to explain Constraints in SQL Server.

* Constraint is a mechanism which can be activated automatically when the specified event is occurred.

* Constraint is a role it can be defined on the selected columns in order to prevent invalid data.

* It is one of the data integrity concepts to enforce integrity explicitly.

Different types of constraints:

1) Not Null: It does not allow null values in the specified column.

2) Check: It is used to validating user conditions.

3) Unique: It doesn’t allow duplicate values in the specified column & it allows only single NULL value.

4) Primary Key: It doesn’t allow duplicate & NULL values.

5) Foreign Key: This is for establishing relation between 2 tables. One table will act as Parent & another will act as Child. And it is associated with either Primary key (or) Unique Constraints.

* For establishing the relation between the tables should maintain at least one common column.

* Foreign key allows duplicate & Null values.

* Only one Primary Key allowed for table.

* Maximum 253 Foreign Keys allowed for table.

* We can define only Primary Key/Unique Key on a single column.

6) Default: It is for defining user default values instead of storing system default values.

Syntax for defining constraints:

Create table tableName

(Column1 datatype Constraint1 Constraint2 ....,

Column2 datatype Constraint1 Constraint2 ....,

.........)

For Example:

Create table Department

(DeptId int PrimaryKey,

DeptName varchar(20) Unique NotNull,

Location varchar(20) Default ‘Hyderabad’)

Thank You…

Readmore...

Java Script function for Printing Div content.

1 comments
 

Hi Friends, in this post I would like to explain Java Script function for Printing Div content.

Here I took one Button control for printing the content.

JavaScript Function:

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

function Print(elementId)

{

var printContent = document.getElementById(elementId);

var windowUrl = 'about:blank';

var uniqueName = new Date();

var windowName = 'Print' + uniqueName.getTime();

var printWindow = window.open(windowUrl, windowName, 'left=50000,top=50000,width=0,height=0');

printWindow.document.write(printContent.innerHTML);

printWindow.document.close();

printWindow.focus();

printWindow.print();

printWindow.close();

}

script>

Div content:

<div id="printDivContent" >

Here we can place any content like controls,text……

div>

Calling div from the Button control:

<asp:Button ID="btnPrint" runat="server" onclientclick="javascript:Print('printDivContent');" Text="Print"

Width="50px" />

Thank You…

Readmore...

Java Script function for entering only Integers values in Textbox.

2 comments
 

Hi Friends, in this post I would like to explain Java Script function for entering only Integers values in Textbox.

JavaScript Function:

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

function isNumberKey()

{

if(!(((event.keyCode>=48&&event.keyCode<=57) || (event.keyCode>=96&&event.keyCode<=105))||(event.keyCode==8) || (event.keyCode==9) || (event.keyCode==37) || (event.keyCode==39) || (event.keyCode==46) || (event.keyCode==190)))

event.returnValue=false;

}

script>

Calling the above function from Textbox control:

<asp:TextBox ID="txtNumericValue" runat="server" Width="120px" onkeydown="isNumberKey();">asp:TextBox>

So that we can enter only Integer Values in the TextBox.


Thank You…

Readmore...
Sunday 12 June 2011

Windows application for converting Text into Speech.

1 comments
 
Hi Friends, in this post I would like to explain how to convert Text into Speech.
· Open windows application.
· Place a TextBox & a Button control on to the form.
· Goto ProjectMenu---> Add Reference---> COM---> MicrosoftSpeechObjectLibrary (Add this reference).
· Add the following namespace: using SpeechLib;
Please go through the code under button click event:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using SpeechLib;

namespace TextToSpeech
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void btnClick_Click(object sender, EventArgs e)
{
SpVoice voice = new SpVoice();//Where SpVoice is the Speakers Voice.
voice.Speak(textBox1.Text,SpeechVoiceSpeakFlags.SVSFDefault);
}
}
}


Thank You...
Readmore...

Deleting files from the system in ASP.Net.

1 comments
 
Hi Friends, in this post I would like to explain how to delete the file existing on the system.
For this I took 1 FileUpload, 1 Button & 1 label control on to the page.
Please find the source code below:

<%@ 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 runat="server">
<title>Untitled Page</title>

</head>
<body>
<form id="form1" runat="server">
<div>
<table width="300px">
<tr>
<td>
<asp:FileUpload ID="fuLoad" runat="server" />
</td>
<td>
<asp:Button ID="btnDelete" runat="server" Text="Delete File"
onclick="btnDelete_Click" />
</td>
</tr>
<tr>
<td colspan="2">
<asp:Label ID="lblDisplayMessage" runat="server" Text=""></asp:Label>
</td>
</tr>
</table>
</div>
</form>
</body>
</html>


Then please find the Code for deleting the file:

using System;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.IO;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}
protected void btnDelete_Click(object sender, EventArgs e)
{
string filePath = fuLoad.PostedFile.FileName;
if (File.Exists(filePath.Trim()))
{
File.Delete(filePath.Trim());
lblDisplayMessage.Text="File Deleted Successfully";
}
else
{
lblDisplayMessage.Text = "File does not exist.";
}

}
}


Thank You...
Readmore...