1
Posted on 1:30 AM by prajeesh and filed under
In my previous post I discussed about disabling the right context menu in a web page , here we can discuss on how to prevent text selection in the web page, if you want to prevent normal users copying content of your web page then it will be useful.
Just add following functions to your web page's body tag.

one drawback is it will not work in mozilla, but we have another workaround for this,just add onmousedown function also in the body tag:

as we added in body tag, you can add these functions in any elements of your web pages for preventing selection Shout it kick it on DotNetKicks.com
0
Posted on 9:46 PM by prajeesh and filed under
Some websites does not allow right click context menu option for security reasons, you can also achieve this by adding following code to your body tag of the page.

Alternatively, you can show an alert saying "Right click disabled" if you call a function from body tag's oncontextmenu event, for eg:-

Disclaimer: I have tested this functions in IE7 and Mozilla 3.0 only , it will not work in Opera.
Enjoy coding

Shout it kick it on DotNetKicks.com
0
Posted on 9:12 PM by prajeesh and filed under
In some websites you may have noticed a fade effect while browsing the pages, we may feel an ajax effect and may not feel slow page load, just add the following meta tag to your page before the body tag.


Please note that it will not work in Mozilla. Shout it kick it on DotNetKicks.com
2
Posted on 4:18 AM by prajeesh and filed under ,
Sometimes you may need to call a method in the parent page from a child user control, for eg:- we have a user control with New, Save, Delete buttons and based on the page type we may need to call appropreate methods.
Before going to actual aim of this post we must have an idea about delegates and event handlers.
What is a delegate & how should we use it?
A deligate is just like a function pointer in c/c++ , delegates can be used to call a method where the call method can be determined only at run time.
How can we declare, instantiate and call a deligate?
Suppose we have a method to add two numbers and display the result in the webpage.
Step 1 : Declaring a delegate

public delegate void SumOfTheNumbers(int a, int b);

where delegate is a keyword and void is the return type of the delegate.
Step 2: Instantiating and calling the delegate

DisplayNumbersDelegate objDisDelegate = new DisplayNumbersDelegate(AddNumbers);
objDisDelegate(5 ,10 );

where "objDisDelegate" is the delegate variable and "AddNumbers" is the function to be called, note that signature of the AddNumbers function must be similer to the delegate we declared, that is it must accept two integer parameters and returns void, when we instantiate the delegate object we are pointing the AddNumbers function to the delegate variable, we can use delegate variable to call the method by passing the values, here we are calling only one function using this delegate this is called single cast delegate, you can also use delegates to call multiple functions also this type of delegates are called multi cast delegates.
Calling a method in a parent page from a user control :
Suppose we have two text boxes and an add button in the user control and we want to call a method to add two numbers declared in the parent page and display result in the same page.
Step 1: Declare the delegate and event in user control.

public delegate void SumOfTheNumbers(int a, int b);
public event SumOfTheNumbers sumnos;

Step 2:Passing the parmeters to the delegate from click event of the Add button in the user control

protected void btnAdd_Click(object sender, EventArgs e)
{
sumnos(int.Parse(txtBoxNum1.Text), int.Parse(txtBoxNum2.Text));
}

Step 3:Declare the add method in parent page.

public void sumofthenumber(int a, int b)
{
Response.Output.Write("sum of{0} and {1} is : {3} ",a,b,a+b);
}

Step 4: Instantiate the delegate from the page load event of the parent page.

protected void Page_Load(object sender, EventArgs e)
{
delControl1.sumnos += new TestProject.UserControls.delControl.SumOfTheNumbers(sumofthenumber);
}

and you are done, hope you enjoyed this post.






Shout it kick it on DotNetKicks.com
0
Posted on 9:52 PM by prajeesh and filed under
Eventhough it is a tech blog, in this post i would like to share my happiness of being a father. We blessed with a baby girl on October 20th this year (2009) , we named her "Prarthana" meaning is Prayer.
Me and my wife Dhanya are enjoying the new life of parenthood with her :).
See her photo taken on 28th day :

Shout it kick it on DotNetKicks.com
0
Posted on 3:02 AM by prajeesh and filed under ,
Working with Gridview inside Gridview.

Grid view is a very useful and easier to use data presentation control in asp.net it is having lots of default features that we can set very easily, but in some of the projects you may need to show a master client relationship to the users For eg:- List of students who are studying in different departments.
We can handle this situation by using nested grid views, ie a Gridview inside a Gridview.
Microsoft is providing a solution for this situation msdn website , see the link : http://msdn.microsoft.com/en-us/library/aa992038(VS.80).aspx

I think Microsoft's solution contains lot of steps to complete the process, I done a workaround on this and come up with a solution, let me explain the tasks in step by step with an example.
Step 1:
Create a gridview named gvDepartments and add a Template Field in it.
Step 2:
Inside the Template Field'd Item Template add another gridview called gvStudents.
Step 3:
Add following code in gvStudents grid view
DataSource ='<%# GetStudentInfo( Convert.ToInt16(Eval("Department_Id")) ) %>'
Where GetStudentInfo is a server side function that returns a datatable containing the list of students based on department id.
Source of the Grid views will be like below code :

DataKeyNames="DepartMent_Id" CellPadding="4" ForeColor="Black"
GridLines="Vertical" BackColor="White" BorderColor="#DEDFDE"
BorderStyle="None" BorderWidth="1px">




<%# Container.DataItemIndex+1 %>





DataSource ='<%# GetStudentInfo( Convert.ToInt16(Eval("Department_Id")) ) %>'
CellPadding="4" ForeColor="#333333" GridLines="None" ShowHeader="False"
AutoGenerateColumns="False">




<%# Container.DataItemIndex +1 %>






















Step 4
Create Method to bind gvDepartments (Must contain a column named “Department_Id” as we are passing this parameter to bind gvStudents).
Step 5
Create a Method named GetStudentInfo(int department_Id) , It accepts Department_Id as parameter and returns a
datatable contains students list,(example given below) and you are done.

public DataTable StudentsByDepartment(int DepartmentId)
{
SqlConnection dbConnection = new SqlConnection(ConnectionString);
DataTable dtStudentList = new DataTable();
try
{
dbConnection.Open();
SqlDataAdapter daStudents = new SqlDataAdapter();
SqlCommand cmdSelect = new SqlCommand("SelectStudentByDep",dbConnection);
cmdSelect.CommandType = CommandType.StoredProcedure;
cmdSelect.Parameters.AddWithValue("@Dep", DepartmentId );
daStudents.SelectCommand = cmdSelect;
daStudents.Fill(dtStudentList);
}
catch (Exception objException)
{
HttpContext.Current.Response.Write(objException.Message);
}
finally
{
if (dbConnection != null && dbConnection.State == ConnectionState.Open)
{
dbConnection.Close();
}
}
return dtStudentList;
}


Figure: Sample output of a nested Gridview :

Shout it kick it on DotNetKicks.com
0
Posted on 5:43 AM by prajeesh and filed under
In some situations we may need to maintain the scroll bar position when we are dealing with large pages with a button causes post back, you can use achieve this by adding MaintainScrollPositionOnPostback=”true” in @Page directive.

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" MaintainScrollPositionOnPostback ="true" %>
Shout it kick it on DotNetKicks.com
0
Posted on 10:29 PM by prajeesh and filed under ,
Here is the list of some commonly used reguler expressions for validating your forms.
E-mail
^([0-9a-zA-Z]([-\.\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9})$
URL
^(htf)tp(s?)\:\/\/[0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*(:(0-9)*)*(\/?)([a-zA-Z0-9\-\.\?\,\'\/\\\+&%\$#_]*)?$
Social Security Number
^\d{3}-\d{2}-\d{4}$
Phone number(Validates US Phone number)
^[01]?[- .]?(\([2-9]\d{2}\)[2-9]\d{2})[- .]?\d{3}[- .]?\d{4}$
Zip Code(Validates US Zip code)
^(\d{5}-\d{4}\d{5}\d{9})$^([a-zA-Z]\d[a-zA-Z] \d[a-zA-Z]\d)$
Currency(Non Negative)
^\d+(\.\d\d)?$
Currency(+ve or -ve)
^(-)?\d+(\.\d\d)?$
Non Negative Integer
^\d+$
For a detailed article on reguler expressions, refer : http://msdn.microsoft.com/en-us/library/ms972966.aspx Shout it kick it on DotNetKicks.com
7
Posted on 4:17 AM by prajeesh and filed under ,
Sometimes you may be want to show your latest twitter tweets in your website or blog, most of the cases you are doing this by using widgets with limited customization facilities and showing ads or links to other websites, here is an easier way to achieve this using twitter API and javascript.
Step 1:
First, decide where about on your page you want your last tweet to display. Then paste following html code there.
Step 2:
Next you need to put these 2 lines of JavaScript below the code in step 1. On the 2nd line of code where it says prajeeshkk.json, you need to replace prajeeshkk with your twitter username.

Step 3:(Optional)
You can apply css and make the div displaying the tweet stylish.


See how my tweet design looks :

Shout it kick it on DotNetKicks.com
0
Posted on 4:06 AM by prajeesh and filed under ,
In some applications we may need to reset all controls in using a single "Reset" button click, here is the c# code to achieve this.

public static void ResetControls(ControlCollection pagecontrols, bool txtbox, bool dropdownlist, bool label)
{
foreach (Control cntrl in pagecontrols)
{
foreach (Control mycontrols in cntrl.Controls)
{
if (txtbox)
{
if (mycontrols is TextBox)
{
(mycontrols as TextBox).Text = string.Empty;
}
}
if (dropdownlist)
{
if (mycontrols is DropDownList)
{
(mycontrols as DropDownList).SelectedIndex = 0;
}
}
if (label)
{
if (mycontrols is Label)
{
(mycontrols as Label).Text = string.Empty;
}
}
}
}
}

We can call this function using following format if you want to clear all controls except label

FormControl.ResetControls(this.Controls, true, true, false);

Shout it kick it on DotNetKicks.com
0
Posted on 8:54 AM by prajeesh and filed under
Sometimes you may need to update an online database with some stored procedure you have modified in your local system, but in most of the cases you may be confused about what are the stored procedures or tables you modified last, here is a quick solution for this.
1.Query to sort Stored Procedures on modified date.

SELECT name, create_date, modify_date,type
FROM sys.objects
WHERE type = 'P' order by modify_date desc

2.Query to sort Stored Procedures on created date

SELECT name, create_date, modify_date,type
FROM sys.objects
WHERE type = 'P' order by create_date desc

3.Query to sort user defined tables on created date

SELECT name, create_date, modify_date,type
FROM sys.objects
WHERE type = 'u' order by create_date desc

4.Query to sort user defined tables on modified date

SELECT name, create_date, modify_date,type
FROM sys.objects
WHERE type = 'u' order by modify_date desc
Shout it kick it on DotNetKicks.com
0
Posted on 12:55 PM by prajeesh and filed under , ,
In some websites you may seen animating or scrolling page titles, here is the trick to do this, just place below code between your page's <head> and </head> tags
Shout it kick it on DotNetKicks.com
0
Posted on 11:01 AM by prajeesh and filed under
Some situations such as a freequently updating page you may need to refresh your page automatically, here is the code to achieve this.

Response.AppendHeader("Refresh", "60; URL=Default.aspx");

Here your page Default.aspx will be refreshed after 60 seconds, if you want to redirect to another page after a few seconds, replace the page 'Default.aspx' with the page you want to be redirected. Shout it kick it on DotNetKicks.com
0
Posted on 5:20 AM by prajeesh and filed under ,
Here is the SQL query to create a stored procedure that deletes all stored procedures in a database


create procedure dropallsp as
declare @procName varchar(500)
declare cur cursor
for Select [name] from sys.procedures where [type] = 'P' and is_ms_shipped = 0 and [name] not like 'sp[_]%diagram%'
open cur
fetch next from cur into @procName
while @@fetch_status = 0
begin
exec('drop procedure ' + @procName)
fetch next from cur into @procName
end
close cur
deallocate cur
Shout it kick it on DotNetKicks.com
0
Posted on 5:13 AM by prajeesh and filed under ,
Here is an easy way to drop all tables in a database using a single query.

exec sp_msforeachtable 'Drop table ?'

As it is an undocumented stored procedure it may be get removed any time without any notification. Shout it kick it on DotNetKicks.com
0
Posted on 2:05 PM by prajeesh and filed under
Microsoft Launched a new community portal for developers to thrive your career, this portal helps you to find a job, training, trial software's and community support for developers.
URL is : http://www.microsoft.com/click/thrivedev/ Shout it kick it on DotNetKicks.com
0
Posted on 1:24 PM by prajeesh and filed under ,
In ASP.net we are using Response.Redirect or Server.Transfer for redirect to another page, this Redirection can also be done using Javascript or HTML
javascript:

< language="javascript">
window.location = "YourURL.aspx";
< /script >

Plain HTML(you can add following code between your <head> and </head> tags):

< equiv="REFRESH" content="0;url=yourURL.aspx">
Shout it kick it on DotNetKicks.com
1
Posted on 12:47 PM by prajeesh and filed under
In ASP.net we are redirecting to a page using Response.Redirect("PageName.aspx") ; or
using Server.Transfer("PageName.aspx"); difference between these two commands are
Response.Redirect tells browser to redirect to another page where Server.Transfer instead of telling the browser it changes the focus of the web server to another page so it reduces HTTP requests and run your application faster also browser url will be same, please note that Server.Transfer can only used for redirection between the sites running in same server.
If you set PreserveForm parameter True then existing query strings and form values are available in next page too.


Shout it kick it on DotNetKicks.com
0
Posted on 1:29 PM by prajeesh and filed under , , ,
Me and my colleague Anurag were trying to integrate a Paypal button in one of our recent project, we copied the button code available from Paypal website to our ASP.NET page and it was not worked and button click results only in a postback, at last we realized that it wont work as button code contained a form and ASP.net will not support more than one form in a page.
The button code we got from Paypal was like below:








We googled a lot to overcome this situation and finally we got a quick solution from Chyake Uchaya's blog, but the solution was not worked well in Mozilla, we done minor changes in the code and it worked perfectly finally, here is the code:





if you are not using Master pages, you can replace getElementById('aspnetForm') with getElementById('form1') or the form name you are using. Shout it kick it on DotNetKicks.com
0
Posted on 3:00 AM by prajeesh and filed under ,


Microsoft corporation announces Windows 7 pricing and upgrade option program.
So here’s the low-down on pricing for Windows 7. The estimated retail prices for upgrade packaged retail product of Windows 7 in the U.S. are:
Windows 7 Home Premium (Upgrade): $119.99
Windows 7 Professional (Upgrade): $199.99
Windows 7 Ultimate (Upgrade): $219.99
And the estimated retail prices for full packaged retail product of Windows 7 in the U.S. are:
Windows 7 Home Premium (Full): $199.99
Windows 7 Professional (Full): $299.99
Windows 7 Ultimate (Full): $319.99
This means that Windows 7 Home Premium full retail product is $40.00 less than Windows Vista Home Premium today.

Read full story here Shout it kick it on DotNetKicks.com
0
Posted on 12:52 AM by prajeesh and filed under , ,
Many asp.net communities and discussion forums are flooded with questions on how to resize images while uploading or how to generate image thumbnails while uploading an image, i have seen many posts giving the solution, here i am going to combine some solutions and created a simple solution.
Another feature of this solution is you can upload any number of images at a time.
Here is the code:


using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
///
/// Summary description for clsImageUpload : Credits : http://prajeeshkk.blogspot.com
///

public class clsImageUpload
{
string fileName;
public clsImageUpload()
{
//
// TODO: Add constructor logic here
//
}
//This function is called from aspnet page, it takes directory name as parameter
public string HandleUploadedFile(string directory)
{
// To get the root of the web site
string root = HttpContext.Current.Server.MapPath("~/");
// clean up the path
if (!root.EndsWith(@"\"))
root += @"\";
// make a folder to store the images in
string fileDirectory = root + @"\" + directory + "\\";
// create the folder if it does not exist
// make a link to the new file

// loop through the file in the request
for (int i = 0; i < HttpContext.Current.Request.Files.Count; i++)
{
// get the file instance
HttpPostedFile fi = HttpContext.Current.Request.Files.Get(i);
// create a byte array to store the file bytes
byte[] fileBytes = new byte[fi.ContentLength];
// fill the byte array
using (System.IO.Stream stream = fi.InputStream)
{
stream.Read(fileBytes, 0, fi.ContentLength);
}
// create a random file name
fileName = Guid.NewGuid().ToString();

// write the resized file to the file system
File.WriteAllBytes(fileDirectory + fileName + "_thumb.jpg", ResizeImageFile(fileBytes, 75));
fileBytes = null;
}
return (fileName + "_thumb.jpg");
}
public void HandleUploadedFileUseExistingName(string directory, string fname)
{
// get the root of the web site
string root = HttpContext.Current.Server.MapPath("~/");
// clean up the path
if (!root.EndsWith(@"\"))
root += @"\";
// make a folder to store the images in
string fileDirectory = root + @"\" + directory + "\\";
// loop through the file in the request
for (int i = 0; i < HttpContext.Current.Request.Files.Count; i++)
{
// get the file instance
HttpPostedFile fi = HttpContext.Current.Request.Files.Get(i);
// create a byte array to store the file bytes
byte[] fileBytes = new byte[fi.ContentLength];
// fill the byte array
using (System.IO.Stream stream = fi.InputStream)
{
stream.Read(fileBytes, 0, fi.ContentLength);
}
// create a random file name
fileName = fname;
// write the resized file to the file system
File.WriteAllBytes(fileDirectory + fileName, ResizeImageFile(fileBytes, 75));
fileBytes = null;
}
}
/// This fuction returns a Byte array containing the resized file
private static byte[] ResizeImageFile(byte[] imageFile, int targetSize)
{
using (System.Drawing.Image oldImage =
System.Drawing.Image.FromStream(new MemoryStream(imageFile)))
{
//If you want to maintain the propotion use following code
//Size newSize = CalculateDimensions(oldImage.Size, targetSize);
//If you want to use a fixed size use following one
Size newSize = GetDimension();
using (Bitmap newImage =
new Bitmap(newSize.Width,
newSize.Height, PixelFormat.Format24bppRgb))
{
using (Graphics canvas = Graphics.FromImage(newImage))
{
canvas.SmoothingMode = SmoothingMode.AntiAlias;
canvas.InterpolationMode = InterpolationMode.HighQualityBicubic;
canvas.PixelOffsetMode = PixelOffsetMode.HighQuality;
canvas.DrawImage(oldImage,
new Rectangle(new Point(0, 0), newSize));
MemoryStream m = new MemoryStream();
newImage.Save(m, ImageFormat.Jpeg);
return m.GetBuffer();
}
}
}
}
/// This function Calculates the new size of the image based on the target size
private static Size CalculateDimensions(Size oldSize, int targetSize)
{
Size newSize = new Size();
if (oldSize.Height > oldSize.Width)
{
newSize.Width =
(int)(oldSize.Width * ((float)targetSize / (float)oldSize.Height));
newSize.Height = targetSize;
}
else
{
newSize.Width = targetSize;
newSize.Height =
(int)(oldSize.Height * ((float)targetSize / (float)oldSize.Width));
}
return newSize;
}
//Dimension of the images can be set here
private static Size GetDimension()
{
Size newSize = new Size();
newSize.Width = 100;
newSize.Height = 100;
return newSize;
}
}

You can download source code from here Shout it kick it on DotNetKicks.com
0
Posted on 10:09 AM by prajeesh and filed under
In some situations you may need to convert your data table to data reader, suppose you have a Data table named dt and etDataFromDB() is a function that returns a data table, here is the steps to convert data table to data reader.
DataTable dt = new DataTable();
dt = getDataFromDB();
DataTableReader dtr;
dtr = dt.CreateDataReader();
while (dtr.Read())
{
//Do your tasks

} Shout it kick it on DotNetKicks.com
1
Posted on 5:23 AM by prajeesh and filed under ,
Suppose you have a Grid view and you want to display values returned from a server side function that accepts a bound value rather displaying bounded values itself, then you have to add a template field in the Grid view and add following code.
<asp:TemplateField HeaderText="Status">
<ItemTemplate>
<%#YourFunction(Eval("Status"))%>
</ItemTemplate>
</asp:TemplateField> Shout it kick it on DotNetKicks.com
0
Posted on 9:02 AM by prajeesh and filed under ,
In many situations we may need to add auto number or serial numbers in grid view column, but we cannot find a property in property window to add this.
We can add auto number column in Grid view or Data List by using Container.DataItemIndex property in Gridview or Data List mark up.

Add a Template field and add following code in Grid view Mark up:

<asp:TemplateField HeaderText="Serial Number">
<ItemTemplate>
<%# Container.DataItemIndex + 1 %>
</ItemTemplate>
</asp:TemplateField> Shout it kick it on DotNetKicks.com
0
Posted on 4:32 AM by prajeesh and filed under ,
In a previous post i have explained about calling a web service from javascript, please see this post to see calling a web service without parameters.
Suppose you have a web service that accepts user name and password and returns a value in XML format and you want to show the returned value in a webpage or a widget.

For example :

<?xml version="1.0" encoding="utf-8" ?>
<int xmlns="http://tempuri.org/">1</int>

You can use following code snippet to call a web service from javascript:
<script language="text/javascript">
var returned_data;
var request = new XMLHttpRequest();
//function to initialize web service
function initializeWebservice()
{
var url="http://2test.hopto.org/Leadservice.asmx/GetLeadCounts?UserName=Prajeesh&Password=123456";; //Web service url
request.onreadystatechange = webStatusProc;
request.open( "GET", url, true );
request.send();
}
//function to process webservice response
function webStatusProc()
{
if (request.readyState == 4) // Request completed?
{
response = request.responseXML.toXML();
XML = XMLDOM.parse( response);
returned_data= XML.evaluate('string(/int)');
alert(returned-data);
//do anything with returned data
}
}
</script> Shout it kick it on DotNetKicks.com
0
Posted on 7:55 AM by prajeesh and filed under ,
Google code released an open source web page speed analyzer for Mozilla, called "Page Speed" it works like yahoo Yslow.

Page Speed is an open-source Firefox/Firebug Add-on. Webmasters and web developers can use Page Speed to evaluate the performance of their web pages and to get suggestions on how to improve them.

You can download it from Here Shout it kick it on DotNetKicks.com
0
Posted on 3:48 PM by prajeesh and filed under ,
We can upload images very easily using File upload control in asp.net, also you can validate the upload the file type using Reguler expression validator, following is the regular expression validation control code for validating image types such as jpg, png and bmp.
<asp:RegularExpressionValidator ID="RegularExpressionValidator2" runat="server"
ErrorMessage="Upload a valid image (jpg/png/bmp)"
ValidationExpression ="^.+\.((jpg)(JPG)(gif)(GIF)(jpeg)(JPEG)(png)(PNG)(bmp)(BMP))$"
ControlToValidate="fupImage" ValidationGroup="Author_reg"> Upload a valid image;</asp:RegularExpressionValidator>
Shout it kick it on DotNetKicks.com
0
Posted on 2:46 PM by prajeesh and filed under ,
Suppose you have a web service that returns a value in XML format and you want to show the returned value in a webpage or a widget.
For example :

<?xml version="1.0" encoding="utf-8" ?>
<int xmlns="http://tempuri.org/">1</int>

You can use following code snippet to call a web service from javascript:
<script language="text/javascript">
var returned_data;
var request = new XMLHttpRequest();
//function to initialize web service
function initializeWebservice()
{
var url =
http://Localhost/Testwebservice.asmx/GetLeadCounts; //Web service url
request.onreadystatechange = webStatusProc;
request.open( "GET", url, true );
request.send();
}
//function to process webservice response
function webStatusProc()
{
if (request.readyState == 4) // Request completed?
{
response = request.responseXML.toXML();
XML = XMLDOM.parse( response);
returned_data= XML.evaluate('string(/int)');
alert(returned-data);
//do anything with returned data
}
}
</script>



Shout it kick it on DotNetKicks.com
0
Posted on 4:25 AM by prajeesh and filed under ,
If you find "The test form is only available for requests from the local machine" message in your webservice page after hosted in your server, dont worry just add following tags in your web.config file just before </system.web>
tag
<webServices>
<protocols>
<add name="HttpGet"/>
<add name="HttpPost"/>
</protocols>
</webServices> Shout it kick it on DotNetKicks.com
0
Posted on 12:22 AM by prajeesh and filed under ,
In some sites you may have seen visitors counter/Total hits at the bottom of the website, in asp.net it is very easy to implement this feature, here i will show you a simple example that stores visitors count in a Text file.
First you have to add a Global.asax file into the solution you are working, you can do this by Right clicking your project name in the solution explorer ->Add New Item -> Global Application Class.
create a Hits.txt file in the root folder of your application and just add following code in the Session_Start event in the Global.asax file.

void Session_Start(object sender, EventArgs e)
{
// Code that runs when a new session is started
Application.Lock();
if (System.IO.File.Exists(Server.MapPath(Request.ApplicationPath + "/Hits.txt")))
{
System.IO.StreamReader sr = new System.IO.StreamReader(Server.MapPath(Request.ApplicationPath + "/Hits.txt"));
string count = sr.ReadToEnd();
sr.Dispose();
Application["Hits"] = int.Parse(count) + 1;
System.IO.StreamWriter sw = new System.IO.StreamWriter(Server.MapPath(Request.ApplicationPath + "/Hits.txt"));
sw.Write(Application["Hits"].ToString());
sw.Dispose();
}
//Application["Hits"] = int.Parse(Application["Hits"].ToString()) + 1;
Application["OnlineUsers"] = (int)Application["OnlineUsers"] + 1;
Application.UnLock();
}

Reading Data from Hits.text file:
if (System.IO.File.Exists(Server.MapPath(Request.ApplicationPath + "/TestFile.txt"))){
{
System.IO.StreamReader sr = new System.IO.StreamReader(Server.MapPath(Request.ApplicationPath + "/Hits.txt"));
string strdata = sr.ReadToEnd();
sr.Dispose();
}
Here total hits will be available in "strdata" variable.
we have to create a StreamReader object to read data from a text file, follow this MSDN article to know more about StreamReader class. Shout it kick it on DotNetKicks.com
0
Posted on 11:22 PM by prajeesh and filed under ,
It is a good idea to create log files to identify exceptions occured in your webapplication in a live environment.
In ASP.net we can achieve this by creating a Text file in the application and write exceptions into the text file with time of exception, here is the sample code:
First you have to create a Log.txt file in the root folder of your application
try
{
//lines of code that may generate exceptions.
}
catch(Exception ex)
{
if (System.IO.File.Exists(HttpContext.Current.Request.ApplicationPath + "/Log.txt"));
{
System.IO.StreamWriter Sr = new System.IO.StreamWriter(HttpContext.Current.Server.MapPath(HttpContext.Current.Request.ApplicationPath+"/Log.txt"),true);
Sr.WriteLine(
DateTime.Now.ToString()+":"+ex.ToString());
}
}

so all exceptions generated within the try block will be recorded into Log.txt file.


Shout it kick it on DotNetKicks.com
0
Posted on 10:12 PM by prajeesh and filed under ,
File manipulation is a very easy task in asp.net, i this article i will show you a simple example that writes and and read data from a text file.
suppose we have a Text file named "TestFile.txt" in the root folder of our web application.
Writing Data to a text file :
if (System.IO.File.Exists(Server.MapPath(Request.ApplicationPath + "/TestFile.txt")))
{
System.IO.StreamWriter sw = new System.IO.StreamWriter(Server.MapPath(Request.ApplicationPath + "/TestFile.txt"));
sw.Write("Hello world");
sw.Dispose();
}

if you want to Append data in the Text file then you have to set append parameter true in StramWriter object constructor.
Eg:-
System.IO.StreamWriter sw = new System.IO.StreamWriter(Server.MapPath(Request.ApplicationPath + "/TestFile.txt"),true);
we need to create a streamwriter object to write lines of data into a text file, follow this MSDN article to understand more about StreamWriter class.

Reading Data from a Text file:
if (System.IO.File.Exists(Server.MapPath(Request.ApplicationPath + "/TestFile.txt")))
{
System.IO.StreamReader sr = new System.IO.StreamReader(Server.MapPath(Request.ApplicationPath + "/TestFile.txt"));
string strdata = sr.ReadToEnd();
sr.Dispose();

}
we have to create a StreamReader object to read data from a text file, follow this MSDN article to know more about StreamReader class.
Data will be available in strdata variable.

Shout it kick it on DotNetKicks.com
0
Posted on 12:10 PM by prajeesh and filed under , ,
I am working with IPIX Solutions Pvt Ltd , one of the leading web design company in india.
We are a widely established web design company offering an extensive range of customized products for all your web related needs. We provide well-organized ecommerce website design solutions and development services according to the existing business and client’s needs that help to grab more customers. Our capabilities and experience will assist you to launch any type of website with all the latest technologies and best SEO. IPIX Solutions’ main services include:
Domain Registration & Hosting
Web Designing
Web Application Development
E-commerce Solutions
Flash Development
Multimedia & Graphic Solutions
and
Search Engine Optimization
..etc

click here for all you web development related inquiries Shout it kick it on DotNetKicks.com
0
Posted on 11:43 AM by prajeesh and filed under ,
Here is the quick fix to solve design breakage problem in IE 8 browser.

<meta content="IE=EmulateIE7?" equiv="X-UA-Compatible"/>
you can add this tag in all web pages you want to fix temporarily, but i recommend you manually fix the errors later as IE8 is going to be a leading browser using full power of css 3.0.
or you can also use following tag to fix in all popular browsers
<meta http-equiv="X-UA-Compatible" content="IE=7" />
<meta http-equiv="X-UA-Compatible" content="IE=8" />
<meta http-equiv="X-UA-Compatible" content="IE=8;FF=3;Opera=9;Konqueror=3;Safari=3" /> Shout it kick it on DotNetKicks.com
0
Posted on 11:46 PM by prajeesh and filed under
If you are a new user of SQL Server 2008 you probably got Save (Not Permitted) Dialog Box while trying to add or delete columns of a table, message content will be like this
"saving changes is not permitted because the changes you have made require the listed tables to be dropped and re-created", i found the solution to avoid this message today in MSDN while searching the same.
To change this option, on the Tools menu, click Options, expand Designers, and then click Table and Database Designers. Select or clear the Prevent saving changes that require the table to be re-created check box. Shout it kick it on DotNetKicks.com
0
Posted on 4:23 AM by prajeesh and filed under ,
Some situations it becomes necessary that the data that to be populated to a gridview or any other controls not directly come from a single function but we have to get it from some other source, like from multiple functions, a file system, or other sources. In such ssituations you can populate the DataSet or DataTable in your ASP.NET web page programmatically and then bind the web control with this data object.
Here i would like to explain a simple method to achieve this
DataTable dtHome = new DataTable();
dtHome.Columns.Add("Name",string.Empty.GetType());
dtHome.Columns.Add("City",string.Empty.GetType());
dtHome.Columns.Add("State",string.Empty.GetType());

Now we have successfully created a data table with empty rows with string data type fields, in next step we have to add rows in the data table.
dtHome.Rows.Add("Prajeesh","Calicut","Kerala");
Now we have added a single row to the data table, you can use this datatable to populate a grid view or other data presentation controls, it will display a single row of data.
GridView1.DataSource = dtHome;
GridView1.DataBind();

Shout it kick it on DotNetKicks.com
0
Posted on 11:34 AM by prajeesh and filed under ,
Sending e-mails is an essential feature needed in most of the websites, .net framework supplies a SMTP class that enables you to send simple e-mails. If you have to send an e-mail with additional features, you have to make use of the MailMessage class. With the help of this class, you can insert attachments, set priorities etc..very easily. You can also send HTML e-mail using MailMessage class. To send an e-mail using asp.net, you should have access to a server with .net Framework and SMTP enabled on it.
1. Sending a simple e-mail using SMTP
First we need to import the System.Web.Mail namespace.
using System.Web.Mail;
Synatax for sending a simple e-mail message :
SmtpMail.Send("FROM","TO","SUBJECT","MESSAGE BODY");
Example:
SmtpMail.Send("sender@testmail.com","recipient@testmail.com", "Test e-mail

2.Sending e-mail using MailMessage class
Instead of supplying all parameters in the Send() method, you can define properties and values separately by creating an instance of the MailMessage class. using MailMessage class, you can easily add attachments, set priorities, BCC, CC values and other additional features.
MailMessage objEmail = new MailMessage();
objEmail.To = "recipient@test-email.com";
objEmail.From = "sender@test-email.com";
objEmail.Cc = "recipientcc@test-email.com";
objEmail.Subject = "Test Email";
objEmail.Body = "This is a test email message";
objEmail.Priority = MailPriority.High;

try
{
SmtpMail.Send(objEmail);
Response.Write("your mail has been sent");

SmtpMail.SmtpServer = "localhost"
}
catch (Exception ex)
{
Response.Write("Mail sending failed: " + ex.ToString());
}

If you want to send mails in HTML format, include following code also
objEmail.BodyFormat = MailFormat.Html;
Adding Attachements to emails:
MailAttachment MyAttachment
objEmail.Attachments.Add()= new MailAttachment("C:\\My Folder\\MyFile.txt");




Shout it kick it on DotNetKicks.com
0
Posted on 10:43 PM by prajeesh and filed under ,
The meta tags are essential part of the Search Engine Optimization, meta tags are used to provide keywords in web pages. When you are doing a CMS project, it is necessory to add keywords from control panel for each page, Now in ASP.NET 2.0 and above, you can add these meta tags programmatically. The HtmlMeta class provides programmatic access to the HTML <meta> element on the server. The HTML <meta>element is a container for data about the rendered page, but not page content itself.
The Name property of HtmlMeta provides the property name and the Content property is used to specify the property value. The Scheme property to specify additional information to user agents on how to interpret the metadata property and the HttpEquiv property in place of the Name property when the resulting metadata property will be retrieved using HTTP.
For Pages Not using Master Pages:
private void CreateMetaTags()
{
HtmlMeta hm = new HtmlMeta();
HtmlHead head = (HtmlHead)Page.Header;
hm.Name = "Keywords";
hm.Content = "keywords,asp.net, c# help";
head.Controls.Add(hm);
}

For Pages Using Master Pages:
The solution to this is to first provide an id to your Head Tag in Master Page :
< head runat="server" id="masterHead">
Now add the following code to page_load event of the requires page

//Find the Head Tag in Master Page
HtmlHead hdMaster = (HtmlHead)Page.Master.FindControl("masterHead");
HtmlMeta htmMeta = new HtmlMeta();
htmMeta.Attributes.Add("name","description");
htmMeta.Attributes.Add("content", "this is test content for meta description");
//Add Meta Tag to Head
hdMaster.Controls.Add(htmMeta);
//Adding keyword Meta Tag to Head Section
HtmlMeta hm2 = new HtmlMeta();
hm2.Attributes.Add("name", "keywords");
hm2.Attributes.Add("content", "asp.net,meta,keywords,dynamically,masterpage"); hdMaster.Controls.Add(hm2); Shout it kick it on DotNetKicks.com
1
Posted on 9:55 AM by prajeesh and filed under ,
The usual workaround for this purpose is loopthrough the rows in the Data Reader and assign each rows to Data Table, This is a time consuming process.
But Dot Net 2.0 and above provides a new DataTable.Load() as a quicker solution.
Here is the method
DataTable.Load(IDataReader); Shout it kick it on DotNetKicks.com
0
Posted on 9:02 AM by prajeesh and filed under

Shout it kick it on DotNetKicks.com