Gridview Edit_Update_Delete Manipulation

Posted by Venkat | Labels: ,

We are going to see how to Edit , Delete , update Gridview rows , when the Gridview is binded through Bound Column.
BoundField in Grid view and bind the data to each field using "Edit Column" option in smart tag of grid view.

We can also add images to Edit and Delete option in Grid view "edit columns" by adding a "commandfield".
This is the Code , here i have take some sample table to do this operation.
String con1 = ConfigurationManager.ConnectionStrings["con"].ToString();

DataSet ds = new DataSet();

To Edit Row

protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)

{

GridView1.EditIndex = e.NewEditIndex;

bindata();

}


To Update the Rows :
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)

{

string i = GridView1.DataKeys[e.RowIndex].Value.ToString();

int j = Convert.ToInt32(i);

TextBox t1 = new TextBox();

t1 = (TextBox)GridView1.Rows[e.RowIndex].Cells [0].Controls [0];

TextBox t2 = new TextBox();

t2 = (TextBox)GridView1.Rows[e.RowIndex].Cells [1].Controls [0];

TextBox t3 = new TextBox();

t3 = (TextBox)GridView1.Rows[e.RowIndex].Cells [2].Controls [0];



SqlConnection con = new SqlConnection(con1);

string upt = "update Allergies set Allergy = @allergy, Symptoms = @symptom, Action_to_be_taken =@action where Allergy_id=" + j;



SqlCommand cmd = new SqlCommand(upt, con);

cmd.Parameters.Add("@allergy", SqlDbType.VarChar).Value = t1.Text;

cmd.Parameters.Add("@symptom", SqlDbType.VarChar).Value = t2.Text;

cmd.Parameters.Add("@action", SqlDbType.VarChar).Value = t3.Text;

con.Open();



cmd.ExecuteNonQuery();

con.Close();

GridView1.EditIndex = -1;

bindata();

}
To Cancel the Edit rows :

protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)

{

GridView1.EditIndex = -1;

bindata();

}
To Delete the Rows :
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)

{

string i = GridView1.DataKeys[e.RowIndex].Value.ToString();

int j = Convert.ToInt32(i);

SqlConnection con = new SqlConnection(con1);

string del = "Delete from Allergies where Allergy_id=" + j;

SqlCommand cmd = new SqlCommand(del, con);

con.Open();

cmd.ExecuteNonQuery();

con.Close();

GridView1.EditIndex = -1;

bindata();

}

ASP.NET Performance Tips

Posted by Venkat | Labels:

When i checked the Forums there i have seen the post ie: posted by one members  regard ASP.NET Performance, I am have some articles based on performance so with that this too will  be helpful.
For better performance improvement..kindly flow the following YSLOW rules,
Performance Improving Methods( From YSlow)

1. Make fewer HTTP requests

Decreasing the number of components on a page reduces the number of HTTP requests required to render the page, resulting in faster page loads. Some ways to reduce the number of components include: combine files, combine multiple scripts into one script, combine multiple CSS files into one style sheet, and use CSS Sprites and image maps.

2. Content Delivery Network (CDN)

User proximity to web servers impacts response times. Deploying content across multiple geographically dispersed servers helps users perceive that pages are loading faster.

3. Add Expires headers

Web pages are becoming increasingly complex with more scripts, style sheets, images, and Flash on them. A first-time visit to a page may require several HTTP requests to load all the components. By using Expires headers these components become cacheable, which avoids unnecessary HTTP requests on subsequent page views. Expires headers are most often associated with images, but they can and should be used on all page components including scripts, style sheets, and Flash.

4. Compress components with gzip

Compression reduces response times by reducing the size of the HTTP response. Gzip is the most popular and effective compression method currently available and generally reduces the response size by about 70%. Approximately 90% of today's Internet traffic travels through browsers that claim to support gzip.
5. Grade A on Put CSS at top
Moving style sheets to the document HEAD element helps pages appear to load quicker since this allows pages to render progressively.

6. Put JavaScript at bottom

JavaScript scripts block parallel downloads; that is, when a script is downloading, the browser will not start any other downloads. To help the page load faster, move scripts to the bottom of the page if they are deferrable.

7. Avoid CSS expressions

CSS expressions (supported in IE beginning with Version 5) are a powerful, and dangerous, way to dynamically set CSS properties. These expressions are evaluated frequently: when the page is rendered and resized, when the page is scrolled, and even when the user moves the mouse over the page. These frequent evaluations degrade the user experience.

8. Make JavaScript and CSS external

Using external JavaScript and CSS files generally produces faster pages because the files are cached by the browser. JavaScript and CSS that are inlined in HTML documents get downloaded each time the HTML document is requested. This reduces the number of HTTP requests but increases the HTML document size. On the other hand, if the JavaScript and CSS are in external files cached by the browser, the HTML document size is reduced without increasing the number of HTTP requests.

9. Reduce DNS lookups

The Domain Name System (DNS) maps hostnames to IP addresses, just like phonebooks map people's names to their phone numbers. When you type URL www.yahoo.com into the browser, the browser contacts a DNS resolver that returns the server's IP address. DNS has a cost; typically it takes 20 to 120 milliseconds for it to look up the IP address for a hostname. The browser cannot download anything from the host until the lookup completes.

10. Minify JavaScript and CSS

Minification removes unnecessary characters from a file to reduce its size, thereby improving load times. When a file is minified, comments and unneeded white space characters (space, newline, and tab) are removed. This improves response time since the size of the download files is reduced.

11. Avoid URL redirects

URL redirects are made using HTTP status codes 301 and 302. They tell the browser to go to another location. Inserting a redirect between the user and the final HTML document delays everything on the page since nothing on the page can be rendered and no components can be downloaded until the HTML document arrives.

12.Remove duplicate JavaScript and CSS

Duplicate JavaScript and CSS files hurt performance by creating unnecessary HTTP requests (IE only) and wasted JavaScript execution (IE and Firefox). In IE, if an external script is included twice and is not cacheable, it generates two HTTP requests during page loading. Even if the script is cacheable, extra HTTP requests occur when the user reloads the page. In both IE and Firefox, duplicate JavaScript scripts cause wasted time evaluating the same scripts more than once. This redundant script execution happens regardless of whether the script is cacheable.

12. Configure entity tags (ETags)

Entity tags (ETags) are a mechanism web servers and the browser use to determine whether a component in the browser's cache matches one on the origin server. Since ETags are typically constructed using attributes that make them unique to a specific server hosting a site, the tags will not match when a browser gets the original component from one server and later tries to validate that component on a different server.

13. Make AJAX cacheable

One of AJAX's benefits is it provides instantaneous feedback to the user because it requests information asynchronously from the backend web server. However, using AJAX does not guarantee the user will not wait for the asynchronous JavaScript and XML responses to return. Optimizing AJAX responses is important to improve performance, and making the responses cacheable is the best way to optimize them.

14. GET for AJAX requests

When using the XMLHttpRequest object, the browser implements POST in two steps: (1) send the headers, and (2) send the data. It is better to use GET instead of POST since GET sends the headers and the data together (unless there are many cookies). IE's maximum URL length is 2 KB, so if you are sending more than this amount of data you may not be able to use GET.

15. Reduce the number of DOM elements


A complex page means more bytes to download, and it also means slower DOM access in JavaScript. Reduce the number of DOM elements on the page to improve performance.

16. Avoid HTTP 404 (Not Found) error

Making an HTTP request and receiving a 404 (Not Found) error is expensive and degrades the user experience. Some sites have helpful 404 messages (for example, "Did you mean ...?"), which may assist the user, but server resources are still wasted.

17. Reduce cookie size

HTTP cookies are used for authentication, personalization, and other purposes. Cookie information is exchanged in the HTTP headers between web servers and the browser, so keeping the cookie size small minimizes the impact on response time.

18. Use cookie-free domains

When the browser requests a static image and sends cookies with the request, the server ignores the cookies. These cookies are unnecessary network traffic. To workaround this problem, make sure that static components are requested with cookie-free requests by creating a subdomain and hosting them there.


19. Avoid AlphaImageLoader filter

The IE-proprietary AlphaImageLoader filter attempts to fix a problem with semi-transparent true color PNG files in IE versions less than Version 7. However, this filter blocks rendering and freezes the browser while the image is being downloaded. Additionally, it increases memory consumption. The problem is further multiplied because it is applied per element, not per image.

20. Do not scale images in HTML

Web page designers sometimes set image dimensions by using the width and height attributes of the HTML image element. Avoid doing this since it can result in images being larger than needed. For example, if your page requires image myimg.jpg which has dimensions 240x720 but displays it with dimensions 120x360 using the width and height attributes, then the browser will download an image that is larger than necessary.

21. Make favicon small and cacheable

A favicon is an icon associated with a web page; this icon resides in the favicon.ico file in the server's root. Since the browser requests this file, it needs to be present; if it is missing, the browser returns a 404 error (see "Avoid HTTP 404 (Not Found) error" above). Since favicon.ico resides in the server's root, each time the browser requests this file, the cookies for the server's root are sent. Making the favicon small and reducing the cookie size for the server's root cookies improves performance for retrieving the favicon. Making favicon.ico cacheable avoids frequent requests for it.

Regex for Indian Phone Numbers

Posted by Venkat | Labels: ,

Today , we are going to discuss about the Regular Expression for Indian Phone Numbers.
Default there is only few Regex available on .net Regularexperssion validator controls.
so if we want to validate our textbox field like indian phone numbers, landline number we have write it own Expression.

There is expression tools available to - Check the Expression is valid or not. I have no idea about this because i have not used.

To accept Indian (Landline) phone numbers check this Regex   :   /^[0-9]\d{2,4}-\d{6,8}$/

This is indian phone number. where it will take a format of std code 3 to 4 digits, hypen and rest of the 6 to 8 digits.
Ex: 0222-8345622 or 09786-567567


This one is for eight digit no ::  \d{8}    eg: 26440050

This one is for mobile no:: \d{10}     eg: 9998945678

This one is for mobile no with india code \d{13}   eg 9109998945678

This one is for Mobile no with india code then space and then mobile no whith zero as starting :: +\d{2}\s\d{9}    eg:+91 09998945678

Extract the EmailID from the Text File

Posted by Venkat | Labels: ,

Here is the another article ie: which is going to find the emailID on the Text File and assign to a string.

Here i have the Textfile ie: Notepad File on the Server folder.

in the notepad file i have some content and emailID too, so i want to get the EmailID from the file so i have to send email to that user.

For this i am using REGEX so its easy to find the emailID on the text file and add or store it on arrays.

Here i am using the Two Method both are using REGEX pattern.


Here you go.. I tested - its working fine.

First Method:

using System.Text.RegularExpressions;
using System.IO;

try
{
//the file is in the root - you may need to change it
string filePath = MapPath("~") + "/EmailText.txt";

using (StreamReader sr = new StreamReader( filePath) )
{
string content = sr.ReadToEnd();
if (content.Length > 0)
{
//this pattern is taken from Asp.Net regular expression validators library
string pattern = @"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*";
MatchCollection mc = Regex.Matches(content, pattern);
for (int i = 0; i < mc.Count; i++)
{
//here am just printing it.. You can send mails to mc[i].Value in thsi loop
Response.Write(mc[i].Value + "
");
}
}
}
}
catch (Exception ee)
{
Response.Write(ee.Message);
}

------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Second Method:

string pattern = @"[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?";

System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex(pattern);

//Read file
string sFileContents =System.IO.File.ReadAllText(Server.MapPath("Email.txt"));

System.Text.RegularExpressions.MatchCollection mc = reg.Matches(sFileContents);

//string array for stroing
System.Collections.Generic.List str = new System.Collections.Generic.List();foreach (System.Text.RegularExpressions.Match m in mc)

{

str.Add(m.Value);

}

OUTPUT

input file
----------

jeevan@test.com This e-mail address is being protected from spambots. You need JavaScript enabled to view it ,

Welcome yo Hyderabadtechies.info
test@test.com This e-mail address is being protected from spambots. You need JavaScript enabled to view it ,
its really cool....

Chandrasekarthotta@gmail.com This e-mail address is being protected from spambots. You need JavaScript enabled to view it

sdf

sdfs

dfsd



output :


jeevan@test.com This e-mail address is being protected from spambots. You need JavaScript enabled to view it , test@test.com This e-mail address is being protected from spambots. You need JavaScript enabled to view it , Chandrasekarthotta@gmail.com

Difference between TypeOf and GetType

Posted by Venkat | Labels: ,

Here I am going to discuss about the  -  Difference between typeof and GetType ? - typeof and GetType produce the exact same information. But the difference is where they get this information from:

* typeof is used to get the type based on a class. That means if you use typeof with object, it will gives you error. You must pass class as parameter.
* Where GetType is used to get the type based on an object (an instance of a class). Means GetType needs parameter of object rather than class name.

You can understand more with example.

The following code will output “True”:

string instance = “”;

Type type1 = typeof(string);

Type type2 = instance.GetType();

Console.WriteLine(type1 == type2);

Generate 16 Digit Unique Number in CSharp

Posted by Venkat | Labels: ,

Now i am going ot discuss about how to Generate 16 digit Unique number
So ,

5 digit Random using System.Random Class

5 digit number by using TimeSpan

6 numbers by System Time (HH:MM:SS)

This is the Code

System.Random fiveRandom = new Random();
TimeSpan tsFive = new TimeSpan();
tsFive = DateTime .Now.Subtract (Convert.ToDateTime ("01/01/1900"));
string rad = fiveRandom.Next(10000, 99999) +  tsFive.Days.ToString() +   System.DateTime.Now.Hour.ToString ("00") +          System.DateTime.Now.Minute.ToString ("00") +   System.DateTime.Now.Second.ToString ("00")  ;

Compare Datetime Objects

Posted by Venkat | Labels: ,

Here i am going to share
1) How to Compare two Datetime object ( here i am mentioning some ways to Compare Datetime Variables )
2) How to get the timeSpan Values from the Hours and add hours to the Datetime its easy.

It can be expressed as a date and time of day.

It compares Date with time.

DateTime chkExpireDateTime = new DateTime(2009, 8, 1, 0, 0, 0);

if (DateTime.Compare(DateTime.Now , chkExpireDateTime)< 0)
{
// the Current Datetime.now is less than ChkExpireDateTime
}
else if (DateTime.Compare(DateTime.Now, chkExpireDateTime) > 0)
{
// the Current Datetime.now is Greater than ChkExpireDateTime
}
else if (DateTime.Compare(DateTime.Now, DateTime.Now) == 0)
{
// the Current Datetime.now and ChkExpireDateTime are Equal
}

You can also Compare this way.

DateTime systemDate = DateTime.Now;
DateTime compareDate = DateTime.Today.AddHours(11D);

// less than
if (compareDate < systemDate)
Console.WriteLine("Less Than");

// equal to
if (compareDate == systemDate)
Console.WriteLine("Equal To");

// greater than
if (compareDate > systemDate)
Console.WriteLine("Greater Than");

// basically you can compare it in all the normal ways
// using !=, ==, , =, etc



The below code is used to get the Timespan for the for the hours and minutes given through the string.

string time = "02:10";
string[] pieces = time.Split(new char[] { '.' },

StringSplitOptions.RemoveEmptyEntries);
TimeSpan difference2 = new TimeSpan(Convert.ToInt32(pieces[0]),

Convert.ToInt32(pieces[1]), 0);
double minutes2 = difference2.TotalMinutes; // 130
double totalSeconds = difference2.TotalSeconds; // 7800

// this will add the seconds to the Datetime

DateTime getOutTime = new DateTime();
getOutTime = DateTime.Now.AddHours(Convert.ToDouble (getHours ));
getOutTime = DateTime.Now.AddSeconds(totalSeconds);

Response.Redirect Vs Server.Transfer

Posted by Venkat | Labels:

1) Response.Redirect(“newpage.aspx”)

In some case , if i use like this it shows ThreadAborExecution error, when the above line execute it Calls the Response.End() and it's Response.End() that calls Thread.Abort() this makes the error.

Response.Redirect(“newpage.aspx”,false) // whereas the second parameter is false / true

Ref: http://www.c6software.com/articles/ThreadAbortException.aspx

and Server.Transfer(“newpage.aspx”)

2) Server.Transfer -  redirects the client with in the same application ie, from one ASP page to other ASP page with in the application. This will not update the history.

Response.Redirect: - This redirects the client to the other URL ie, from one ASP page to other applications page. This will update the history.

3) Response.Redirect involves a roundtrip to the server

whereas Server.Transfer conserves server resources by avoiding the roundtrip. It just changes the focus of the webserver to a different page and transfers the page processing to a different page.

4) Roundtrip means in case of Response.Redirect it first sends the request for the new page to the browser then browser sends the request for the new page to the webserver then after your page changes.

But in case of Server.Transfer it directly communicate with the server to change the page hence it saves a roundtrip in the whole process.

5) If you are using Server.Transfer then you can directly access the values, controls and properties of the previous page - using Context.Item collections

- which you can’t do with Response.Redirect.

6) Response.Redirect changes the URL in the browser’s address bar. So they can be bookmarked.

Whereas Server.Transfer retains the original URL in the browser’s address bar. It just replaces the contents of the previous page with the new one.

7) Response.Redirect can be used to redirect a user to an external websites.
Ex: www.Google.com,www.hyderabadtechies.info..,

Server.Transfer can be used only on sites running on the same server. You cannot use Server.Transfer to redirect the user to a page running on a different server.

Paths/URLs are incorrect, I want absolute/relative URLs? while using TinyMCE

Posted by Venkat | Labels:

Hi Normally if you upload the images on Admin Side - you are going to use the images on General or User folder.so this will take relative Path of the images or file, place the folder inside the Project folder - While giving path to the image on TinyMCE - use Absolute path or Relative path - it will take Relative path of the Images of files.

this is sample TinyMCE Initialization.

<script language="javascript" type="text/javascript" src="../tiny_mce/tiny_mce.js"></script>

<script type="text/javascript">
tinyMCE.init({
    // General options
    mode : "textareas",
     elements: "top1_TextBox,top2_TextBox,top3_TextBox,top4_TextBox,mid1_TextBox,mid2_TextBox,mid3_TextBox,mid4_TextBox,bot1_TextBox,bot2_TextBox,bot3_TextBox,bot4_TextBox",
    theme : "advanced",
     force_p_newlines: false,
            remove_linebreaks : true,
            force_br_newlines : true,
            paste_remove_styles : true,


    plugins : "safari,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template",


    // Theme options
    theme_advanced_buttons1 : "link,image,|,code",
    theme_advanced_buttons2 : "",
    theme_advanced_buttons3 : "",
    theme_advanced_buttons4 : "",
    theme_advanced_toolbar_location : "top",
    theme_advanced_toolbar_align : "left",
    //theme_advanced_statusbar_location : "bottom"
});
</script>

So get the upDated TinyMCE folder version 3.2.7 download the file from TinyMCE Download latest TinyMCE Editor

This link may help u  Path Url Issue

If you anyone face some issue let you comment here..

Visible the Textbox when User Select Others on the Dropdownlist using Javascript

Posted by Venkat | Labels: ,

Hi i have came across one task, ie: I have dropdownlist that has some items along with 'Others' So if the user Choose the value Others -  i have to visible the Textbox and Validator so user should enter somthing on the textbox else it show Validation error if the user choose any other item , i have to disable the Textbox and the Validator.

Using Javascript its easy to do this , i am not good in Javascript i got a help from the Expert to make it work.

ASPX

<asp:DropDownList ID="EducationLevel_DropDownList" runat="server" Width="202px"
                                            Font-Names="Verdana" Font-Size="10pt" AppendDataBoundItems="True">
                                            <asp:ListItem Value="-1">Select</asp:ListItem>
                                            <asp:ListItem Value="1">PhD</asp:ListItem>
                                            <asp:ListItem Value="2">PhD Student</asp:ListItem>
                                            <asp:ListItem Value="3">Master Degree</asp:ListItem>
                                            <asp:ListItem Value="4">Bachelor Degree</asp:ListItem>
                                            <asp:ListItem Value="5">Under Graduate Student</asp:ListItem>
                                            <asp:ListItem Value="6">Others</asp:ListItem>
                                        </asp:DropDownList>
                                        <asp:RequiredFieldValidator ID="RequiredFieldValidator5" runat="server" ControlToValidate="EducationLevel_DropDownList"
                                            Display="Dynamic" ErrorMessage="Education Leve required !" InitialValue="-1"
                                            SetFocusOnError="True" ValidationGroup="Profile" Font-Size="8pt">*</asp:RequiredFieldValidator><asp:TextBox ID="TextBox1"
                                                runat="server"></asp:TextBox> <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="TextBox1"
                                            Display="Dynamic" ErrorMessage="Education Leve required !" 
                                            SetFocusOnError="True" ValidationGroup="Profile" Font-Size="8pt">*</asp:RequiredFieldValidator>

And the Javascript is given below so here i am pass the Valuefield of Other ie: 6 , when a textbox has validators, they are stored in the Validators collection , so no need to pass the ValidatorID.


JAVASCRIPT


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


function getSelectValue(sel) {
   
    var val;
    // only if there is a selected item
    if (sel.selectedIndex>-1) {
        // get the value from the select element
        val=sel.options[sel.selectedIndex].value;
       // alert(val);
    }
   
    return val;
}


        function ddlChange(DropDownID,TextBoxID)
        {
            var c=document.getElementById(DropDownID);
            var div=document.getElementById(TextBoxID);
            if(getSelectValue(c)=='6')
            {
                div.value='';
                div.style.visibility="visible";
                if (div.Validators&&div.Validators.length) {
                   for (var i=0; i<div.Validators.length; i++)
                       ValidatorEnable(div.Validators[i], true)
                }
            }
            else
            {
                div.value='6';
                div.style.visibility="hidden";
                if (div.Validators&&div.Validators.length) {
                   for (var i=0; i<div.Validators.length; i++)
                       ValidatorEnable(div.Validators[i], false)
                }
            }
        }
    </script>

Then On_PageLoad you have to pass the TextboxID and DropdownlistID to the Javascript Function.


EducationLevel_DropDownList.Attributes.Add("onchange", "ddlChange('" + EducationLevel_DropDownList.ClientID + "','" + TextBox1.ClientID + "');");
        TextBox1.Style.Add("visibility", "hidden");

Bind Images from Folder to Datalist

Posted by Venkat | Labels: ,

Here we are going to see how to bind the images from the folder to Datalist. I am storing the images on Server Folder , so i have to show what are the images available on the Folder it may be .png,.jpg or any ...

ASPX

<asp:DataList ID="DataList1" runat="server" RepeatColumns="5" CellPadding="5">
            <ItemTemplate>
            <asp:Image Width="100" ID="Image1" ImageUrl='<%# Bind("Name", "~/images/{0}") %>' runat="server" />
                <br />
                <asp:HyperLink ID="HyperLink1" Text='<%# Bind("Name") %>' NavigateUrl='<%# Bind("Name", "~/images/{0}") %>' runat="server"/>
            </ItemTemplate>
                <ItemStyle BorderColor="Silver" BorderStyle="Dotted" BorderWidth="1px" HorizontalAlign="Center"
                    VerticalAlign="Bottom" />
</asp:DataList> 

see here, we get the files from the folder using System.IO Namesapce  , then i am checking the images on the folder ie: checking the extension that i am going to allow - to show it on Datalist. you can include the Extension whatever you want so that is going to add it on arrayList, then pass the array list to DataSource of the Datalist.


Code-Behind

protected void Page_Load(object sender, EventArgs e)
    {
        ListImages();
    }

    private void ListImages()
    {
        DirectoryInfo dir = new DirectoryInfo(MapPath("~/images"));
        FileInfo[] file = dir.GetFiles();
        ArrayList list = new ArrayList();
        foreach (FileInfo file2 in file)
        {
            if (file2.Extension == ".jpg" || file2.Extension == ".jpeg" || file2.Extension == ".gif")
            {
                list.Add(file2);
            }
        }
        DataList1.DataSource = list;
        DataList1.DataBind();
    }

Validate Checkbox and Checkboxlist

Posted by Venkat | Labels:

If we want to Validate the Textbox, Dropdownlist we used Validation Server Controls available in ASP.NET
Suppose if we want to validate Checboxlist or checkbox , some member validate through Javascript its good , some feed if its similar to Validator controls it should be easy to validate,.

so here is the link its similar to validation Server controls just Download the skmValidator Controls and add it on toolbox just drag and drop and set the errormessage , validationgroup, controltovalidate etc..

http://aspnet.4guysfromrolla.com/articles/092006-1.aspx 

If you want to do on Client side check this link

http://www.dotnetcurry.com/ShowArticle.aspx?ID=197&AspxAutoDetectCookieSupport=1

How to get Control Value From CreateUserWizard Control

Posted by Venkat | Labels: ,

Now I am going to discuss how to get the Controls Values ( ie:  Textbox , Dropdownlist etc.. ) inside the CreateUserWizard control, In CreateUserWizard Control on first view you can't able to get the Controls value directly.

Using FindControl i am getting the control value.

Write these Code on CreateUserWizard_CreatingUser Event

 DropDownList Questionddl = (DropDownList)CreateUserWizard.CreateUserStep.ContentTemplateContainer.FindControl("Question_DropDownList");
CreateUserWizard.Question = Questionddl.SelectedValue;

Set the Value has Selected to Listbox by getting value from Database

Posted by Venkat | Labels:

As we already saw how to get the items(Multiple selection item) from the Listbox. Suppose If we store that value like this(2,4,6,) ie: I concatenate the (,) for each valu -  2,4,6 are the value of the listbox so we are going to rebind this value to List and set it has Selected.

Here the subject is the field on the Table where the [ 2,4,6, ] was stored.

1) First we get the database value to string Variable

2) Then using Split property - remove the (,) from the String and assign to StringArray

3) Atlast use foreach loop to set the item to be selected.

  string subjectList = getUserProfile_SqlDataReader["subject"].ToString();
                            string[] subjectListItems = subjectList.Split(',');
                            foreach (string s in subjectListItems)
                            {
                                foreach (ListItem item in Subject_ListBox.Items)
                                {
                                    if (item.Value == s) item.Selected = true;
                                }
                            }

ETHERPAD

Posted by Venkat |

I Came across new EtherPad , which user can chat and , also edit the code simaltaneously both users

This is my etherPad - Come Here Chat Here..


http://venkat.etherpad.com/1

How to download a file from Server folder

Posted by Venkat | Labels:

Now we are going to see how to download a file or image from the Server folder ie: showing file/open dialog box. For this we have to use Response object to show or get the file.

Sample Code:

        private void WriteFileToResponse()
        {
            Response.Clear();
            Response.AddHeader("Content-Disposition", "attachment; filename=" + Server.MapPath("~/Download/" + FileName));
            //                    Response.AddHeader("Content-Length", file.Length.ToString());
            Response.ContentType = "application/octet-stream";

            //Write the file to the Response Output stream without buffering. 
            //This is new to ASP.NET 2.0. Prior to that use WriteFile. 
            Response.TransmitFile(Server.MapPath("~/Download/" + FileName));
            Response.Flush();
            Response.End();
        }

HTML Validation

Posted by Venkat | Labels: ,

As we used the Embed tag for embed the Flash files , on home or master page as this tag not support for HTML Validation (W3C) . but still we used this tag for showing flash file , if you want to do HTML validation for your site - this makes an error , so you have to avoid this.


Instead use Object tag for placing Flash files

Example:

 <object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" data="the-swf-file.swf" type="application/x-shockwave-flash" width="600" height="420"> <param name="movie" value="the-swf-file.swf" /> <param name="quality" value="high" /> </object>

Wrap the text on Gridview.

Posted by Venkat | Labels:

Hi Good day to All

After a long time , i am back  - i have no time to post the Resources here . now , i will try to post atleast one Resource per day.

I wish you all a Very Happy Diwali

Now i am going to see how to Wrap the text show in the Gridview , I had searched many links & sites finally i got one javascript.
place the javascript at the Top of the page ie: loaded when the page Loads.

<script type="text/javascript"> 
       window.onload = function()
        { 
        if (window.attachEvent == undefined) 
        {
         var tag = document.getElementsByTagName("td"); 
         for (var i = 0; i < tag.length; i++)
          {
           if (tag.item(i).className == "wordwrap") 
           {
            var text = tag.item(i).innerHTML; 
            tag.item(i).innerHTML = text.replace(/(.*?)/g, "<wbr/>"); 
            } 
           } 
          }
         }
    </script>
And one thing you are going to consider , here you have to apply the class="wordwrap" on your td tag at where you want text wrap or which column wants the text wrap then you have to specify the width in px not in % or any.
This is my Sample Gridview code

<asp:GridView ID="userList_GridView" runat="server" AllowPaging="True" AutoGenerateColumns="False"
                                          BorderColor="WhiteSmoke" BorderWidth="0px" CellPadding="5" 
                                            EmptyDataText="User not found...!" Font-Names="Verdana" Font-Size="8pt" ForeColor="Black"
                                            PageSize="30" ToolTip="User List....!" Width="100%" GridLines="None" BackColor="WhiteSmoke" >
                                            <Columns>
                                                <asp:TemplateField>
                                                    <HeaderTemplate>
                                                        <table border="0" cellpadding="0" cellspacing="0" width="100%">
                                                            <tr style=" color: Black;" class ="fbtxt">
                                                                <td align="left" style="width: 18%">
                                                                 Username
                                                                </td>
                                                                <td align="left" style="width: 14%">
                                                                    Email
                                                                </td>
                                                                
                                                                
                                                               <td align="center" style="width: 15%">
                                                                   Resource Permission
                                                                </td>
                                                                <td align="center" style="width: 11%">
                                                                    Permission
                                                                </td>
                                                                  <td align="center" style="width: 7%">
                                                                     Edit
                                                                    </td>
                                                                <td align="center" style="width: 8%">
                                                                    Delete
                                                                </td>
                                                            </tr>
                                                        </table>
                                                    </HeaderTemplate>
                                                    <HeaderStyle BackColor="LightSteelBlue"  Font-Bold="True" Font-Size="10pt" ForeColor="Black" />
                                                    <ItemTemplate>
                                                    <div style ="width :100%;table-layout:fixed;border:0px;">
                                                    <div class ="fntxt">
                                                    <div align="left" style="width: 165px; word-wrap:break; float:left ;" class="wordwrap">
                                                      <%# Eval("username")%>
                                                    </div> 
                                                    <div align="left" style="width: 150px;float:left;" class="wordwrap" >
                                                     <%#Eval("email")%>
                                                    </div> 
                                                    
                                                   <div align="left" style="width: 20%;float:left;" >
                                               <a href ='<%# "resourceaccess.aspx?userResource=" +  Eval("username")   %>' class ="WhiteLink"> Resource Access</a>
                                                    </div>
                                                      <div align="left" style="width: 13%;float:left;" >
                                                      <a href= '<%# "userlist.aspx?userPermission=" +  Eval("username")  %>' class ="WhiteLink"> <%# Eval("approve") %></a>
                                                 
                                                    </div>
                                                    <div align="center" style="width: 12%;float:left;"  >
                                                    <asp:HyperLink ID="Edit_HyperLink"  runat="server" NavigateUrl='<%# "~/Admin/userlist.aspx?editUser=" +  Eval("username")  %>'
                                                                      CssClass ="WhiteLink"  OnClick="return confirm('Are you sure want to Edit this record ?');" Text="Edit"
                                                                        ToolTip="Edit user list....!"></asp:HyperLink>
                                                    </div> 
                                                    <div align="center" style="width: 7%;float:left;"  >
                                                    <asp:HyperLink ID="Delete_Button"  runat="server" NavigateUrl='<%# "~/Admin/userlist.aspx?delUname=" +  Eval("username")  %>'
                                                                      CssClass ="WhiteLink"  OnClick="return confirm('Are you sure want to Delete this record ?');" Text="Delete"
                                                                        ToolTip="Delete user list....!"></asp:HyperLink>
                                                    </div> 
                                                    
                                                    </div>
                                                    </div>
                                                        
                                                    </ItemTemplate>
                                                </asp:TemplateField>
                                            </Columns>
                                            <PagerStyle BackColor="WhiteSmoke" Font-Bold="False" Font-Names="verdana" Font-Size="8pt"
                                                ForeColor="Red" HorizontalAlign="Center" />
                                        </asp:GridView>

Refresh the Parent Page after Closing PopUp Page (window)

Posted by Venkat | Labels: ,

Good Day to all

And also I wish you a Very Happy FriendShip Day..

Now we have to discuss the How to Refresh the parent window by Closing the popup window

Passing the function on your button ie: place Close button on you popup If you click the Close Button , it will close the popup and refresh the parent page.


<script>
function refreshParent() {
window.opener.location.href = window.opener.location.href;

if (window.opener.progressWindow)

{
window.opener.progressWindow.close()
}
window.close();

}
</script>

Email with Attachment

Posted by Venkat | Labels:

Now we will see , how to send an attachment to the email.

for the you have to create an instance for Attachment class and pass the filename and specify the media type information for an email message attachements and set the ContentDisposition which specify the file type whether its txt , doc, gif,jpg etc..,

Import NameSpace

using System.Net.Mail;
using System.Net.MIME;
using System.Net;

Code

try
{

MailMessage mail = new MailMessage();

mail.To.Add("venkat@gmail.com");

mail.From = new MailAddress("admin@Support.com");

mail.Subject = "Testing Email Attachment";

string file = Server.MapPath("~/files/findemai_ontextfile.txt");

Attachment attachFile = new Attachment(file, MediaTypeNames.Application.Octet);

ContentDisposition disposition = attachFile.ContentDisposition;

mail.Attachments.Add(attachFile);

SmtpClient smtp = new SmtpClient();

smtp.Host = "smtp.gmail.com";

smtp.EnableSsl = true;

smtp.Credentials = new NetworkCredential("xxxxxxx@gmail.com", "*********");
s;

smtp.Send(mail);

}

catch (Exception ex)
{

Response.Write(ex.Message);

}

This link helps you :
http://msdn.microsoft.com/en-us/library/system.net.mail.attachment.aspx

Checkboxlist sample code

Posted by Venkat | Labels: ,

Now we are going to discuss about the Checkbox list Control so Checkboxlist allows user to select Multiple values , we will see how to retrieve the selected values from the Checkboxlist.

Here is the HTML Code


<asp:CheckBoxList ID="cblPlanets" runat="server" Width="109px">
<asp:ListItem Value="1">Mercury</asp:ListItem>
<asp:ListItem Value="2">Venus</asp:ListItem>
<asp:ListItem Value="3">Earth</asp:ListItem>
<asp:ListItem Value="4">Mars</asp:ListItem>
<asp:ListItem Value="5">Jupiter</asp:ListItem>
<asp:ListItem Value="6">Saturn</asp:ListItem>
<asp:ListItem Value="7">Uranus</asp:ListItem>
<asp:ListItem Value="8">Neptune</asp:ListItem>
</asp:CheckBoxList>
in Code behind , then place one label control to get the selectedvalue of checkboxlist

C# SOURCE

protected void btnSubmit_Click(object sender, EventArgs e)
{
lblText.Text = "You selected: ";

foreach (ListItem li in cblPlanets.Items)
{
if (li.Selected == true)
{
lblText.Text = lblText.Text += "~" + li.Text;
}
}
}

"The state information is invalid for this page and might be corrupted" With ASP.NET AJAX

Posted by Venkat | Labels:

If you got this error while you working with Asp.Net AJAX.

This seems to be caused by Firefox's methods for saving session information in its cache. There is many way to solve this problem it’s depending on how extensive you want to disable the cache. In my case, I just wanted to do it on one page, so at the top of Page_Load I added:

Response.Cache.SetNoStore();


Set the page Declaration with

<%@ Page Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="Page.aspx.cs" Inherits="Main" Title=My Home" EnableViewStateMac ="false" EnableSessionState="True" EnableEventValidation ="false" ValidateRequest ="false" ViewStateEncryptionMode ="Never" %>
You can also add with web.config file

<pages validaterequest="false" enableeventvalidation="false" viewstateencryptionmode="Never">
</pages>

DeCompress the file using asp.net

Posted by Venkat | Labels: , ,

In previous post we seen how to compress the file this will helpful when the file is large you can
compress the file.

Now we will see how to Decompress the file

Button_Click event.


DecompressFile(Server.MapPath("~/Decompressed/FindEmai_onTextfile.zip"),Server.MapPath("~/Decompressed/FindEmai_onTextfile.txt"));

Here i just swap the filename so it may confuse so use some different path(Folder) or filename

Decompress Method

public static void DecompressFile(string sourceFileName, string destinationFileName)
{

FileStream outStream;

FileStream inStream;

//Check if the source file exist.

if (File.Exists(sourceFileName))
{

//Read teh input file

inStream = File.OpenRead(sourceFileName);

//Check if the destination file exist else create once

outStream = File.Open(destinationFileName, FileMode.OpenOrCreate);

//Now create a byte array to hold the contents of the file

//Now increase the filecontent size more since the compressed file

//size will always be less then the actuak file.

byte[] fileContents = new byte[(inStream.Length * 100)];

//Read the file and decompress

GZipStream zipStream = new GZipStream(inStream, CompressionMode.Decompress, false);

//Read the contents to this byte array

int totalBytesRead = zipStream.Read(fileContents, 0, fileContents.Length);

outStream.Write(fileContents, 0, totalBytesRead);

//Now close all the streams.

zipStream.Close();

inStream.Close();

outStream.Close();

}

}

Compress the file using asp.net

Posted by Venkat | Labels: , ,

Good day to all today we are going to discuss about how to compress the file using asp.net application , ie: for compression there are some third party tools like CSharpZip (not sue about the name of the tools..) ,gzip, etc..

Asp.net has inbuilt with Compression ie: derive from the Class

using System.IO.Compression;

There are two compression derived from this namespace.
1) Gzipstream
2) Deflate stream

Deflate seems to be must faster than the Gzipstream but Deflate doesn't uncompress other formats , but Gzipstream decompress the other files like winzip, winrar .

Now we are going to see Gzipstream it has a class which contains filename and compression mode , Compression mode has two values Compress and Decompress.

Button_ClickEvent

CompressFile(Server.MapPath("~/Decompressed/FindEmai_onTextfile.txt"),Server.MapPath("~/Decompressed/FindEmai_onTextfile.zip"));

Here you have to give two parameter first one is Sourcefilename to be compressed , second is path where you have to place the compressed file. it will check if the file exists the compressed file has been placed there, else it will create on the fly.

Method definition

public static void CompressFile(string sourceFileName, string destinationFileName)
{

FileStream outStream;

FileStream inStream;

//Check if the source file exist.

if (File.Exists(sourceFileName))
{

//Read teh input file

//Check if the destination file exist else create once

outStream = File.Open(destinationFileName, FileMode.OpenOrCreate);

GZipStream zipStream = new GZipStream(outStream, CompressionMode.Compress);

//Now create a byte array to hold the contents of the file

byte[] fileContents = new byte[inStream.Length];

//Read the contents to this byte array

inStream.Read(fileContents, 0, fileContents.Length);

zipStream.Write(fileContents, 0, fileContents.Length);

//Now close all the streams.

zipStream.Close();

inStream.Close();

outStream.Close();

}

}

PayOffers.in