Maintain the Scroll Position on the ASPX page

Hi Friend ,
you know what ,By Default postback property of the page  set the scroll position at top position of the page but we can use a the following statatement to retain the position. 

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebAgain._Default" MaintainScrollPositionOnPostback="true" %> 

Hope this is help you 

Regards,

Rajesh 

1 comments:

Date time format in ASP.Net


Here are some custom formats of date time in ASP.Net:

 string date = DateTime.Now.Date; //This will show the Current Date

 
1) date.DayOfWeek + " " + date.Day + " " + date.ToString("MMMM") + " " + date.Year.ToString()

Example it will shown as “Monday 18 October 2010 ”

 2) date.DayOfWeek + " " + date.Day + " " + date.ToString("MMMM") + " " + date.ToString("HH:mm:ss")

It will show time as “Monday 18 October 21:00:13 ” with Hr format

 3) date.DayOfWeek + " " + date.Day + " " + date.ToString("MMMM") + " " + date.ToString("hh:PM:mm:ss:tt")

It will show time as “Monday 18 October 21:00:13 PM” with Hr format with AM/PM

You also set format like this :-

DateTime.Now.ToString("MM/dd/yyyy");

DateTime.Now.ToString("MMM dd yyyy");

DateTime.Now.ToString("dd/MM/yyyy

0 comments:

Send mail with an Attachment

Hi friend

Hers is the code which show the Email Send with the attached file .Have a look..


using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Net.Mail;
 
public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {
 
    }
    protected void btnMailSend_Click(object sender, EventArgs e)
    {
        MailMessage mail = new MailMessage();
        mail.To.Add(“SendToMail@gmail.com”);
        //To whome you want to send mail
        mail.From = new MailAddress(“SemderMailId@yahoo.com”);
        mail.Subject = “This is a Subject of the Mail”;
        mail.Body = “Here We Add the Body of the mail”;
        mail.IsBodyHtml = true;
//Here We attached the File 
        if (FileUpload1.HasFile)
        {
            mail.Attachments.Add(new Attachment(FileUpload1.PostedFile.InputStream, FileUpload1.FileName));
        }
        SmtpClient smtp = new SmtpClient();
        smtp.Host = "smtp.gmail.com"; 
        smtp.Credentials = new System.Net.NetworkCredential
             ("YourMailID@gmail.com", "Password");
 //It may be your Smtp Email ID and Password
        smtp.EnableSsl = true;
        smtp.Send(mail);
 
    }
}

1 comments:

How to render any web site page on Your web page

Hi friends
 To day i have some thing new code for you in this i'll show you how to get or render any web page like yahoo.com home page  or any xyz web page on your web application .aspx page . hope it sound interesting to you.  


 1) Lets start first create any web application and create a web page ex. New.aspx thats my aspx page where i want to render http://itneeds4u.blogspot.com/ website home page .
2) After creation of that page put a lable on it and set Text property =This is a Lable . after this run this page you will get a page out put like this ..

After this put a code at the page load of New.aspx.cs

public partial class New : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            // The System.Text.StringBuilder class can be used when you want to modify a string without creating a new object. Here we used to create entire input
            StringBuilder sb = new StringBuilder();

            // used on each read operation
            byte[] buf = new byte[8192];

            // Here We requet for that page which we want to render on our web page
            HttpWebRequest request = (HttpWebRequest)
            WebRequest.Create("http://itneeds4u.blogspot.com");//Put your url here

            // This wil execute the request
            HttpWebResponse response = (HttpWebResponse)
            request.GetResponse();

            // Here this object read data from responce strem
            Stream responseStream = response.GetResponseStream();

            string tempString = null;
            int count = 0;

            do
            {
                // Here fill the Buffer with data
                 count = responseStream.Read(buf, 0, buf.Length);

               
                if (count != 0)
                {
                    // Here we translate  bytes to ASCII text
                    tempString = Encoding.ASCII.GetString(buf, 0, count);

                    // Create a Proper web text.
                    sb.Append(tempString);

                }
            }
            while (count > 0); // any more data to read?


          lblOutput.Text = sb.ToString();         

        }
    }
after this the web site page will render on your simple aspx page and it will show on the lable .and after this your New.aspx  will be look like this .


this kind of code also help you to find any specify information from other page also..
hope this information is helpful to you.

Regards,

Rajesh

1 comments:

Search Engine Optimization



Search Engine Optimization(SEO), is a technique which can make websites search engine friendly and ensure high ranking in search engine results pages. High ranking in means more targeted visitors and excellent business opportunities for free of cost.
By following are  SEO strategies that apply on the web page.
1.        Your website Should indexed in search engines and directories.
2.        Your websites are being displayed & ranking high in Search result pages.
3.        Your page rank should increased and it  getting more traffic.
4.        Check your web site orientation that must be in order to support SEO tactics .
Some important factor which makes SEO perfect at your web site.

Website Design Factor

You should design the web site including links, headers, alternative image text, alternative frame text and content text in such a way that it is easily crawled by the web crawler.

User Friendliness

Your web site should be user friendly its means it maintain proper page path means should not take more time to navigate on any page.


Content of the Website

Should avoid the copied content on your web site. You should create your own content for your website. You web site page title, page description, keywords, and file name should be well optimized in order to get high ranking in the search engines.

These days google is one of the best search engine and if your site is get indexed in the google, you will start getting tons of hits to your web site.

SEO are of two kind :-
1)      On-page optimization
2)      Off- page optimization.

On-page optimization

In search engine optimization, on-page optimization refers to factors that have an effect on your Web site or Web page listing in natural search results. These factors are controlled by you or by coding on your page. Examples of on-page optimization include actual HTML code, meta tags, keyword placement and keyword density.
Some Point to be remember for on page optimization
Ø      Title Tag :- The first thing to add a Page title having a right keyword of that web site which have to place at the header teg , always combile a keyword with the title.
Ex.<Title> This is a Title of the page</Title>
Ø      Header:- You should highlight the web site keyword with the Header tag .
Ø      Robots Text File - robots.txt The robots.txt file is a set of instructions for visiting robots (spiders) that index the content of your web site pages. For those spiders that obey the file, it provides a map for what they can, and cannot index. The file must reside in the root directory of your web. The URL path (web address) of your robots.txt file should look like this...
User-agent: *
Disallow:
User-agent: *
The asterisk (*) or wildcard represents a special value and means any robot.
Disallow:
The Disallow: line without a / (forward slash) tells the robots that they can index the entire site.
Ø      META Tags - Metadata Elements :- Meta tags are often part of the coding of a website, although they are being found less and less these days. Meta tags are elements of the web page language HTML or XHTML that provide metadata, data or information for the search engines about that webpage. Meta tags can be used to detail the page description, keywords and other data not specified in the head elements of the page.

Meta Tag should be in between head tag in which we maintain a mata tag
Example:-

i)                    <meta name="description" content="Some search engines will index the META Description Tag. These indexing search engines may present the content of your meta description tag as the result of a search query.">
ii)                   <meta name="keywords" content="META Keywords Tag, Metadata Elements, Indexing, Search Engines, Meta Data Elements">
iii)                 <meta http-equiv="content-language" content="en">
          
Ø       Keyword intensity :-Higher intensity of key work on the page will support a better page rank on the search engine . make it confirm that every page have the better density on keyword.
Ø       Keywork location :-Website Key word should be mention at the top-left corner and at the bottom right because search engine will search at both the locations.


Off Page Optimization

In search engine optimization, off-page optimization refers to factors that have an effect on your Web site or Web page listing in natural search results. These factors are off-site in that they are not controlled by you or the coding on your page. Examples of off-page optimization include things such as link popularity and page rank.


This includes,

o       Which website link to you.
o       Number of website link to you.
o       Higher google page rank site linking to you.
o       Some API of Web site linking to you.
o       Other refer sites linking to you.
o       The title of the page your link is on
o       Anchor text used in the link
o       Online promotion of your site.


8 comments:

Send mail Using Gmail Account

Hi Friends,

Here i am posting a function which help to send a email from gmail account to your customer's account . in which you maintain account details and a complete format of mail .  


private void Email_User(string Account_No, string Email, string userName)
        {
            // Here Account_No is the New Account No that you what to send
           //Email is a email address of that person whom you want to send mail
          // userName is the name of that person
            try
            {
                string mail_id = Email;
                MailMessage mm = new MailMessage("dummy@gmail.com", mail_id);
                mm.Subject = "Successful Account Registration";
                mm.Body = "Dear " + userName + "," + "\n" + "Your registration is NOT yet complete! You must login to your account to activate it and complete your registration!" + "\n" + "" + "\n" + "===========================================" + "\n\n\n" + "Your  Account account number: " + Account_No + " \n\n\n" + "============================================" + "\n\n" + "Reminder: You must login to your account in order to activate it." + "\n\n" + "For inqueries and support please use our contact form." + "\n\n" + "Thank you." + "\n\n" + "===========================================" + "\n" + "Keep your account secure by following these simple rules:" + "\n" + "Do NOT click on any links!" + "\n" + "We will always address you by your first name." + "\n" + "We will never send you attached files or ask you to update your login information." + "\n" + "Contact us if you are unsure about an email you received." + "\n" + "============================================";
                SmtpClient smtp = new SmtpClient();
                smtp.Host = "smtp.gmail.com";
                smtp.EnableSsl = true;
                System.Net.NetworkCredential NetworkCred = new System.Net.NetworkCredential();
                NetworkCred.UserName = "dummy@gmail.com ";//Sender mailid
                NetworkCred.Password = "dummy123";//Sender Mail password
                smtp.UseDefaultCredentials = true;
                smtp.Credentials = NetworkCred;
                smtp.Port = 587;
                smtp.Send(mm);
               
            }
            catch (Exception ex)
            {
            }
        }

This Email Should be look like this 

Regards ,
Rajesh

1 comments:

Random Password Generator

Hi friend ,
Here i am giving you a C# function which is used to generate random password . It might be between 1 to 9,a to z, A to Z . new password is a combination of all these characters.
 look @ the function,


private string Random_Password()
   { 
 int passwordLength = 8; //This is the length of your password
      string passwordChar = "";
      passwordChar = "a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,";
      passwordChar += "A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,";
      passwordChar += "1,2,3,4,5,6,7,8,9,0";
      char[] sep = { ',' };
      string[] arr = passwordChar.Split(sep);
      string passwordString = "";
      string temp = "";             
      Random rand = new Random();
      for(int i = 0; i < Convert.ToInt32(passwordLength.ToString()); i++)
           {
             temp = arr[rand.Next(0, arr.Length)];
             passwordString += temp;
            }

            return passwordString;
   }

This function will return a 8 digit alpha numeric password . hope this will help you in your project.

Regards,

Rajesh

1 comments:

Multithreading in C#

What is Multithreading in C#.

Multithreading gives programs the ability to do several things at a time. Each stream of execution is called a thread. Multithreading is used to divide lengthy tasks into different segments that would Secondary  threadwise abort programs. Threads are mainly used to utilize the processor to a maximum extent by avoiding it's idle time. Threading lets a program seem as if it is executing several tasks at once. What actually happens is, the time gets divided by the computer into parts and when a new thread starts, that thread gets a portion of the divided time. Threads in VB .NET are based on the namespace System.Threading. Represents a thread that executes with in theCLR. Using this type, one can able to spawn additional threads in theowning AppDomain.This type defines a number of methods (both static andshared) that allow us to create new threads from a current thread, aswell as suspend, stop, and destroy a given thread.
The following example will demonstrate threads using C#.
using System;
using System.Threading;
 
public class Test
{
    static void Main()
    {
        ThreadStart NewThred = new ThreadStart(NewThread);
        Thread thread = new Thread(NewThred);
        thread.Start();
        
        for (int i=0; i < 5; i++)
        {
            Console.WriteLine ("Primary  thread: {0}", i);
            Thread.Sleep(1000);
        }
    }
    
    static void NewThread ()
    {
        for (int i=0; i < 10; i++)
        {
            Console.WriteLine ("Secondary thread: {0}", i);
            Thread.Sleep(500);
        }
    }
}
 
Here we creates a new thread which runs the NewThread method, and starts it. That thread counts from 0 to 9 fairly fast while the Primary thread counts from 0 to 4 fairly slowly The way they count at different speeds is by each of them including a call to Thread.Sleep, which just makes the current thread sleep for the specified period of time. Between each count in the Primary  thread we sleep for 1000ms, and between each count in the Secondary  thread we sleep for 500ms. Here are the results from one test run on my machine:
Primary thread: 0
Secondary thread: 0
Secondary thread: 1
Primary thread: 1
Secondary thread: 2
Secondary thread: 3
Primary thread: 2
Secondary thread: 4
Secondary thread: 5
Primary thread: 3
Secondary thread: 6
Secondary thread: 7
Primary thread: 4
Secondary thread: 8
Secondary thread: 9
 

1 comments:

State Management in Asp.Net Using C#

State Management in Asp.Net Using C#
HTTP is a State less Protocol that’s  why State Management is  used to maintain the state of between HTTP Request and Response.
There are two ways one can maintain state.
1) Client Side State Management: It includes Cookies, Query String, Hidden Field, View State, Control State
2) Server Side State Management: It Includes Application Object,  Session State .

Client Side State Management

1) Data Transfer Using Cookies :-

A cookie is a small bit of text that accompanies requests and pages as they go between the Web server and browser. The cookie contains information the Web application can read whenever the user visits the site.  To store value from textbox.
protected void btnSubmit_Click(object sender, EventArgs e)
{
HttpCookie CookieName = new HttpCookie("Value");
CookieName.Value = txtData.Text;
CookieName.Expires = DateTime.Now.AddDays(1);
Response.Cookies.Add(CookieName);
Response.Redirect("RedirectPage.aspx");
}

And to retrieve data from cookie in RedirectPage.aspx page
In the Page_Load event write
String strData = Request.Cookies["CookieName "].Value);

Another way to use Cookies,

//Here we set a value of cookies
Response.Cookies["CookieName"].Value = "This is a Value of cookies";

//Here we set the age of cookies,in the form of Day ,Month,Years

Response.Cookies[“CookieName"].Expires = DateTime.Now.AddDays(1);

//Here We Get the value of cookies
Value of cookies= Request.Cookies["CookieName"].Value;           
//Hear expires the cookies
Response.Cookies[“CookieName"].Expires = DateTime.Now.AddDays(-1);



2)Query String:-

Query strings are usually used to send information from one page to another page. They are passed along with URL in clear text.
Example,

Response.Redirect("Nextpage.aspx?Name="txtName.Text + "&LastName=" +txtLastName.Text);

 Now get the value on Next.aspx

String Value1=Request.QueryString[“Name“];
String Value2=Request.QueryString[“Lastname“];

3)Hidden Field

ASP.NET allows you to store information in a Hidden Field control, which renders as a standard HTML hidden field. A hidden field does not render visibly in the browser, but you can set its properties just as you can with a standard control. When a page is submitted to the server, the content of a hidden field is sent in the HTTP form collection along with the values of other controls. A hidden field acts as a repository for any page-specific information that you want to store directly in the page.

Example,

 Using System.Web.UI.HtmlControls.HtmlInputHidden Hidden1;
 
//to assign a value to Hidden field
Hidden1.Value="This is a Hidden Field Value";
//to retrieve a value
string str=Hidden1.Value;

System.Web.UI.HtmlControls.HtmlInputHidden Hidden1;
 
//to assign a value to Hidden field
Hidden1.Value="Create hidden fields";
//to retrieve a value
string str=Hidden1.Value;

4) View State

In this View State the object of view state can hold the value on the single page .

Example,
ViewState[“ViewState_Value”]=”This is a Value of View State”;

//Retrieve the value
String value= ViewState[“ViewState_Value”].ToString();

5 Control State

Control State is new mechanism in ASP.NET which addresses some of the shortcomings of View State. Control state can be used to store critical, private information across post backs. Control state is another type of state container reserved for controls to maintain their core behavioral functionality whereas View State only contains state to maintain control's contents (UI). Control State shares same memory data structures with View State. Control State can be propagated even though the View State for the control is disabled.



Server Side State Management
1)      Session State
Session hold the value throught out the whole application . In this , the Session object is create on the Server and Manage at the client .
Example ,
//Create a Session
Session[“Session_Obj”] =”This is a Value of Session”;
//Retrive the value of session
String Value=Session[“Session_Obj”].ToString();
//How to Expire the Session
This Method Used to remove session when the specific session have to remove.
Session.Contents.Remove("Session_Obj");
This Method is Used When we need to remove all session objects in the application.
Session.Abandon();

2)      Application State
ASP.NET allows you to save values using application state  which is an instance of the HTTPApplication class — for each active Web application. Application state is a global storage mechanism that is accessible from all pages in the Web application. Thus, application state is useful for storing information that needs to be maintained between server round trips and between requests for pages.
Example.
//We Use application. lock event to avoid data conflicts.
Application.Lock();
Application["App_Data"]="Value  of the Application State";
Application.UnLock();


 I hope this will help you the understand how to Manage State in Asp.Net
Regards,
Rajesh 




1 comments:

New Features of .NET Framework 4.0 at Microsoft .NET Support

Hi Friends,

This post contains information about key features and improvements in the .NET Framework version 4.0

The Microsoft .NET Framework 4 coming up with many new features for enabling developers to create applications faster than ever and fully compatible with the older versions of .NET Framework. Some of the New Features in the .NET Framework Version 4.0 are as follows:
  • Improved Security
  • Parallel Computing
  • Visual Basic and C# languages innovations
  • Performance and Diagnostics
  • Dynamic Language Run-time
  • In-Process Side-by-Side Execution
  • Interoperability
  • Profiling
  • Garbage Collection
  • Exceptions Handling
    • Corrupted State Exceptions
  • Covariance and Contra-variance
    • Base Class Libraries
  • Collections and Data Structures
    • BigInteger
    • SortedSet Generic Class
    • Tuples
  • I/O
    • File System Enumeration Improvements
    • Memory-Mapped Files
    • Isolated Storage Improvements
    • Compression Improvements
  • Reflection
    • Application Domain Resource Monitoring
  • 64-bit View and Other Registry Improvements
  • Threading
    • Unified Model for Cancellation
    • Thread-Safe Collection Classes
    • Synchronization Primitives
  • Networking
  • Web
    • Core Services
    • New Features in ASP.NET AJAX 4
    • Web Forms
    • ASP.NET MVC
    • Dynamic Data
    • Visual Studio 2010 Web Designer Improvements
    • Web Application Deployment with Visual Studio 2010
  • Windows Presentation Foundation (WPF) Improvement
  • Windows Communication Foundation (WCF) Improvement
  • Managed Extensibility Framework
  • ADO.NET Improvement
    • Expression Trees
  • Support for WS-Discovery
  • Standard Endpoints
  • Workflow Services
  • Workflow Activity Model
  • Richer Composite Activity Options
  • Expanded Built-in Activity Library
  • Enhanced Persistence and Unloading
Bibliography:-



Security Changes in the .NET Framework 4:
http://msdn.microsoft.com/en-us/library/dd233103%28VS.100%29.aspx
Parallel Programming in the .NET Framework:
http://msdn.microsoft.com/en-us/library/dd460693%28VS.100%29.aspx
Performance Counters in the .NET Framework
http://msdn.microsoft.com/en-us/library/w8f5kw2e%28VS.100%29.aspx
Dynamic Language Runtime Overview
http://msdn.microsoft.com/en-us/library/dd233052%28VS.100%29.aspx
What’s New in Windows Presentation Foundation Version 4
http://msdn.microsoft.com/en-us/library/bb613588%28VS.100%29.aspx
Managed Extensibility Framework
http://www.codeplex.com/MEF/
What’s New in ADO.NET
http://msdn.microsoft.com/en-us/library/ex6y04yf%28VS.100%29.aspx
 
http://msdotnetsupport.blogspot.com/2009/06/27-new-features-of-net-framework-40.html

http://www.tutorialized.com/view/tutorial/New-Features-in-the-.NET-Framework-Version-4.0/53612

Regards,

Rajesh

0 comments:

Make a Multiline label in Asp.Net

Hi Firends,

In this post , I am explaining you how to make a multiline lable in Asp.net.

This code help us for set a label value multiline .
Lets take an example that we have a label having ID lbl_Text now just write the code

string value=””;
string final_result;
for (int i = 0; i < 10; i++)
{
value=value+”Demo”+ Environment.NewLine;
final_result=value.Replace(Environment.NewLine, "
");
}
lbl_Text.Text= final;

// If you want to set label property dynamically Use this

protected void btn_click_Click(object sender, EventArgs e)
{
lbl_Name.Text = "Rajesh";
lbl_Name.BackColor = System.Drawing.Color.Red;
lbl_Name.ForeColor = Color.Black;
lbl_Name.Font.Bold = false;
lbl_Name.Font.Italic = false;
lbl_Name.Font.Underline = true;
lbl_Name.BorderColor = Color.White;
lbl_Name.BorderStyle = BorderStyle.Solid;
lbl_result.Text = lbl_Name.Text;
}

1 comments:

How to Use a Session variable in the class files in c#

Hi Friends,

Here i'll explain you , how to use Session variable in .cs class using C# . because session variable is not directly use in the Class , so we have to use this statement,

System.Web.HttpContext.Current.Session["Session_variable"].ToString();

This Statement help to use Session variable in .cs Class.

Warm Regards,

Rajesh

0 comments: