Step by Step

Wednesday, June 15, 2011

How server see attributes



  How server attributes end up in the browser?
 Example:
 TextBox server control:

<asp:TextBox AccessKey=”a” BackColor=”Black” ForeColor=”White” Font-Size=”30px” 
  BorderColor=”Yellow” BorderStyle=”Dashed” BorderWidth=”4” CssClass=”TextBox”
  Enabled=”True” Height=”40” Width=”200” TabIndex=”1” ToolTip=”Hover text here”
  Visible=”True” ID=”TextBox1” runat=”server” Text=”Hello World”>
</asp:TextBox>

When you request the page with this control in the browser, you end up with the following HTML:

<input name=”TextBox1” type=”text” value=”Hello World” id=”TextBox1” accesskey=”a”
  tabindex=”1” title=”Hover text here” class=”TextBox” style=”color:White;
  background-color:Black;border-color:Yellow;border-width:4px;
  border-style:Dashed;font-size:30px;height:40px;width:200px;” />




List Of Common Server Properties




Common properties for all Server Controls


Common properties for all Server Controls
Most of the server controls share some common behavior.
Part of this behavior includes the so-called properties that define the data a control can contain and expose.
ID-> uniquely identify it in the page
 Runat-> attribute that set to Server to indicate the control should be processed on the server
 ClientID-> contains the client-side ID attribute that will be assigned to the element in the final HTML.
Note:
 In versions of ASP.NET up to 3.5 this ClientID was always generated for you automatically. However, in ASP.NET 4 a new ClientIDMode property has been introduced that gives you more control over the ID of an element at the client.  

Tuesday, June 14, 2011

Customizing Keyboard shortcuts


Customizing Keyboard shortcuts

Keyboard shortcuts are a good way to save time because they allow you to perform a task with a simple keyboard command instead of using mouse.
 To change the keyboard shortcuts, choose Tools Options, expand Environment, and click Keyboard. Locate the command for which you want to change the shortcut in the list with commands.
Next, in the Press Shortcut Keys field, type a new shortcut and click Assign. VWD allows you to enter a double shortcut key for a single command. For example, you can bind the command Close All Documents to the command Ctrl+K, Ctrl+O. To perform this command, you need to press both key combinations in rapid succession. Although a double shortcut key may seem like overkill, it greatly increases the number of available shortcut keys.





Sunday, June 12, 2011

Different Windows you work with it in VS


Different Windows you work with it
1-The Error List
The Error List gives you a list of the things that are currently somehow broken in your site, including incorrect markup in your ASPX or HTML files and programming errors in VB or C# flies. This window can even show you errors in XML and CSS flies. The Error List shows its messages in three categories — Errors, Warnings, and Messages — that signify the severity of the problem


2-The Output Window
When you try to build your site using the Build menu, the Output window tells you whether or not the build succeeded. If the build failed, for example because you have a programming error, it tells you why the build failed. In the commercial versions of Visual Studio, the Output window is used for other information as well, including the status of external plug-in programs. Building — or compiling — web sites is discussed later in this book, including Chapter 19, which deals with deployment of your web site.
3-The Find Results Window
The Find and Replace features of VWD are invaluable tools when it comes to managing the content of your site. You will often need to replace some text in the current document or even in the entire site. Find in Files (Ctrl+Shift+F) and Replace in Files (Ctrl+Shift+H) both output their results in the



Monday, May 23, 2011

To be able to style an element on a page, a browser has to know three things [Part 2]

4-The Class Selector
Style multiple HTML elements through the class attribute. This is handy when you want to give the same type of formatting to a number of unrelated HTML elements.
.Highlight
{
font-weight: bold;
color: Red;
}
The class attribute can be reused a piece of CSS for many different purposes, regardless of the HTML element that uses the class.

Grouping and Combining Selectors

CSS also enables you to group multiple selectors by separating them with a comma. This is handy if you want to apply the same styles to different elements. The following rule turns all headings in the page to red:
h1, h2, h3, h4, h5, h6
{
color: Red;
}

To be able to style an element on a page, a browser has to know three things:


What element of the page must be styled?
What part of that element must be styled?
How do you want that part of the selected element to look?
The answers to these questions are given by selectors, properties, and values.
Selectors
Used to select or point to one or more specific elements within your page.
The selector answers the first question: What element of the page must be styled?

Types OF CSS Selector:

1-The Universal Selector
Indicated by an asterisk (*), applies to all elements in your page.
The Universal selector can be used to set global settings like a font family.
*
{
font-family: Arial;
}
2-The Type Selector
Point to an HTML element of a specific type.
h1
{
color: Green;
}
This Type selector now applies to all

elements in your code and gives them a green color. Type selectorsare not case sensitive, so you can use both h1 and H1 to refer to the same heading.
3-The ID Selector
Always prefixed by a hash symbol (#) and enables you to refer to a single element in the page. Within an HTML or ASPX page, you can give an element a unique ID using the id attribute.
#IntroText
{
font-style: italic;
}
Because you can reuse this ID across multiple pages in your site (it only has to be unique within a single page)
ID selectors are case sensitive, so make sure that the id attribute and the selector always use the same casing.

Sunday, May 22, 2011

How css Fixes HTML Formatting problems


1-It offers a rich set of options to change every little aspect of your web page, including fonts (size, color, family, and so on), colors and background colors, borders around HTML elements, positioning of elements in your page, and much more.
2-CSS is widely understood by all major browsers today, so it’s the language for visual presentation of web pages and very popular among web developers.
3-CSS overcomes the problem of mixed data and presentation by enabling you to define all formatting information in external files. Your ASPX or HTML pages can then reference these files and the browser will apply the correct styles for you.
4- CSS can be placed directly in an HTML or ASPX page, which gives you a chance to add small snippets of CSS exactly where you need them.
5-Because all CSS code can be placed in a separate file, it’s easy to offer the user a choice between different styles — for example, one with a larger font size. You can create a copy of the external style sheet, make the necessary changes, and then offer this alternative style sheet to the user.
6-The decrease in bandwidth that is required for your site. Style sheets don’t change with each request, so a browser saves a local copy of the style sheet the first time it downloads it. From then on, it uses this cached copy instead of requesting it from the server over and over again.

Problems of html Formatting:


1-Limiting the formatting possibilities that your pages require.
You can use tags like , and <font> to change the appearance of text and use attributes like bgcolor to change the background color of HTML elements. You also have a number of other attributes at your disposal for changing the way links appear in your page.
2-Data and presentation are mixed within the same file
<font face=”Arial” color=”red” size=”+1”> </font>
3- HTML doesn’t allow you to easily switch formatting at runtime in the browser.
Difficult change the formatting at runtime in the user’s browser. There is no way to let your visitor change things like the font size or color.
4-The required formatting tags and attributes make your pages larger and thus slower to load and display. This makes it slower to download and display because the information


Cascading Style Sheets (CSS) language.


CSS is the language for formatting and designing information on the Web.
With CSS you can quickly change the appearance of your web pages, giving them that great look that your design or corporate identity dictates

Why do you need css?
In the early days of the Internet, web pages consisted mostly of text and images. The text was formatted using plain HTML, using tags like to make the text bold, and the <font> tag to change the font family, size, and color.
Web developers realized needs for more power to format their pages, so CSS was created to address some of HTML’s styling shortcomings.

Saturday, May 21, 2011

The Difference between HTML and XHTML


The Difference between HTML and XHTML
  HTML and XHTML have very similar names; they have some interesting differences that you need to be aware of.
 XHTML is a reformulation of HTML in XML — extensible Markup Language. This is a generic, text- and tag-based language used to describe data and is used as the base language for many other languages, including XHTML.
So, XHTML is in fact largely just HTML rewritten with XML rules. These rules are pretty simple, and most of the time VWD will help you get it right or show you a list of errors and suggestions on how to fix them.
1-Always Close Your Elements
In XHTML, all elements must be closed. So when you start a paragraph with <p>, you must use 
</p> somewhere later in your page to close the paragraph. This is also the case for elements that don’t have their own closing tags, like <img> or <br> (to enter a line break). In XHTML, these tags are written as self-closing tags, where the closing slash is embedded directly in the tag itself as in
<img src=”Logo.gif” /> or <br />.
2-Always Use Lowercase for Your Tag and Attribute Names
XML is case sensitive, and XHTML applies that rule by forcing you to write all your tags in lo
Although the tags and attributes must be in all lowercase, the actual value doesn’t have to be preceding example that displays the logo image is perfectly valid XHTML, despite the upper the image name.
3-Always Enclose Attribute Values in Quotes
Whenever you write an attribute in a tag, make sure you wrap its value in quotes.
For example when writing out the <img> tag and its src attribute, write it like this:
<img src=”Logo.gif” />
And not like this:
<img src=Logo.gif />
You could also use single quotes to enclose the attribute value, as in this example:
<img src=’Logo.gif’ />
It’s also sometimes necessary to nest single and double quotes. When some special ASP.NET syntax requires the use of double quotes, you should use single quotes to wrap the attribute’s value:
<asp:Label ID=”TitleLabel” runat=”server” Text=’<%# Eval(“Title”) %>’ />
For consistency, this book uses double quotes where possible in all HTML that ends up in the client.
4- Nest Your Elements Correctly
When you write nested elements, make sure that you frst close the inner element you opened last, and then close the outer element. Consider this correct example that formats a piece of text with both bold and italic fonts:
<b><i>This is some formatted text</i></b>
Notice how the <i> tag is closed before the <b> tag. Swapping the order of the closing tags leads to invalid XHTML:
<b><i>This is some formatted text</b></i>
5-Always Add a DOCTYPE Declaration to Your Page
A DOCTYPE gives the browser information about the kind of HTML it can expect. By default, VWD adds a DOCTYPE for XHTML 1.0 Transitional to your page:
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN”
       “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
The DOCTYPE greatly influences the way browsers like Internet Explorer render the page. VWD’s default DOCTYPE of XHTML 1.0 Transitional gives you a good mix between valid markup and pages that render the same in all major browsers.

Thursday, May 19, 2011

Choosing the right Web site template



The New Web Site dialog box in VWD contains different web site templates, each one serving a distinct purpose.
ASP.NET Web Site

This template enables you to set up a basic ASP.NET web site. It contains a number of files and folders to jump start the development of your site.
This template is a good starting point once you start developing real-world ASP.NET web sites.
ASP.NET Empty Web Site
The ASP.NET Empty Web Site template gives you nothing but single configuration file (web .config).
The ASP.NET Empty Web Site template is useful if you have a bunch of existing files you want to use to create a new web site or when you want to create your site from scratch. You use this template as the basis for the sample web site you build in the book and add files and folders as you progress through the site.
WCF Service
This template enables you to create a web site containing one or more WCF Services. A WCF Service is somewhat similar to a web service in that it enables you to create methods that are callable over a network. However, WCF Services, or Windows Communication Foundation Services go much further than simple web services and offer you a lot more flexibility.
Dynamic Data Web Sites
The two templates for Dynamic Data enable you to create a flexible yet powerful web site to manage data in a database without a lot of manual code.
Although it seems you have to make a clear choice up front for the right web site template, this isn’t really the case. Because an ASP.NET web site in VWD is essentially just a reference to a folder, it’s easy to add types from one template to another.
For example, it’s perfectly acceptable (and very common) to add a web service file to a standard ASP.NET Web Site or an ASP.NET Empty Web Site.

Web Application Projects


Web Application Projects make it easier for developers who work in teams or who need more control over the contents of the site and their compilation and deployment processes to build web sites with VWD, because the whole web site is managed as a project with a single project file that keeps track of all the content of the web site.
In VWD 2010, you create a new Web Application Project through the File ➪ New Project dialog box.

Web Site Projects


Web Site Projects represent a project in VWD for a web site. You create a new Web Site Project by choosing File ➪ New Web Site or File ➪ New ➪ Web Site from Visual Web Developer’s main menu.
Web Site Projects were introduced in Visual Studio 2005 and provide some new flexibility in creating and working with web sites. In contrast to web sites built with earlier versions of Visual Studio .NET, a Web Site Project site is simply a Windows folder with a bunch of flies and subfolders in it.
There is no collective file (known as the project file with a .vbproj or .csproj extension) that keeps track of all the individual files in the web site. You just point VWD to a folder, and it instantly opens it as a web site. This makes it very easy to create copies of the site, move them, and share them with others, because there are no dependencies with files on your local system.
Because of the lack of a central project file, Web Site Projects are usually simply referred to as web sites.
But Microsoft also received a lot of negative response from developers who complained that Web Site Projects were too limiting for their development environment.
Because there is no container file that keeps track of everything in the site, it became
much harder to exclude files or folders from the site and work with source control systems a centralized system that enables developers to work on a project collaboratively and that keeps track of changes in the project automatically.
Also, Web Site Projects influenced the way web sites are compiled and deployed, making it harder for developers accustomed to the previous model to apply their knowledge and skills to the new project type.
Microsoft released the Web Application Project template in May 2006 as an add-on for Visual Studio 2005 Standard Edition and up.
The Web Application Project is now an integral part of all versions of Visual Web Developer, free and commercial

Different project types

In the initial release of Visual Web Developer 2008 Express there was one project type: the Web Site Project. The commercial versions of Visual Studio has the second project type — the Web Application Project. In August 2008, Microsoft released Service Pack 1 for Visual Web Developer 2008, which gave users of the free Express edition access to the Web Application Project template as well. This addition is still present in VWD 2010 so you have two options to choose from Web Site Projects and Web Application Project

Tuesday, May 17, 2011

Customizing Keyboard shortcuts


Customizing Keyboard shortcuts
Keyboard shortcuts are a good way to save time because they allow you to perform a task with a simple keyboard command instead of reaching for the mouse and selecting the appropriate item from the menu.
To change the keyboard shortcuts, choose Tools Options, expand Environment, and click Keyboard. Locate the command for which you want to change the shortcut in the list with commands.
Because this list contains many items, you can filter the list by typing a few letters from the command. For example, typing print in the Show Commands Containing field gives you a list of all print-related commands.
Next, in the Press Shortcut Keys field, type a new shortcut and click Assign. VWD allows you to enter a double shortcut key for a single command. For example, you can bind the command Close All Documents to the command Ctrl+K, Ctrl+O. To perform this command, you need to press both key combinations in rapid succession. Although a double shortcut key may seem like overkill, it greatly increases the number of available shortcut keys.

Stack and Heap


There are two places where your data can be on
1-Stack
2-Heap
*Stack
Where your static data saved in it
Like integer as we now that the integer size is 8 bytes
Also like Array as we set its size at declaration
-So to read from it you actually go to the address in stack and read data directly
Ok that's sound good, what about Array List [like array but its size is variables]
So we need huge place to can save our data in that case [as we didn't know how much of bytes we need]
To solve that we need to use heap
*Heap
undetermined space to save our data in it
But as our data is variable we need pointer for that place.
 We save pointer for data in stack and actual data in heep
-So to read from it you actually go to the address in stack and take the indirect address
Then with that address go to heap to read your data

Friday, May 13, 2011

How to send mail using Asp.net



Default to send mail
using System.Net.Mail;




MailMessage email = new MailMessage();


email.Subject = "My first test email";
email.SubjectEncoding = System.Text.Encoding.UTF8;
email.Body = body;
email.BodyEncoding = System.Text.Encoding.UTF8;
email.To.Add(new MailAddress("recipient@domain.com"));
email.Sender = new MailAddress("sender@domain.com");
email.From = new MailAddress("sender@domain.com");
email.Attachments.Add(new Attachment("c:\\my-attachment.pdf"));


try {
SmtpClient client = new SmtpClient("mail.my-domain.com", 25);
// 25 is the default SMTP port
client.Send(email);
} catch (SmtpException ex) {
...
}


Email Address Validation
Another common problem - validating email address input - can be handled easilly in ASP .NET
Validation is important. It reduces the amount of incorrect or fabricated email addresses clogging up your database.
At a very minimum, the format of the address should be tested, and this is typically accomplished using regular expressions.
using System.Text.RegularExpressions;


...


private bool EmailAddressIsValid(string email) {
string regExPattern = @"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}" +
@"\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\" +
@".)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$";
Regex regEx = new Regex(regExPattern);
return regEx.IsMatch(email);
}
Note that this can be tested client-side using Javascript as well.
Socket to 'em
But let's say you want to be extra sure that bogus addresses will not violate your precious database space.
There are two other aspects you can test, and here ASP .NET comes into its own, using its socket functionality.
(SMTP emails are sent using socket connections. In fact you can write your own version of the SmtpClient class using sockets. But why re-invent the wheel? Unless you're really bored. Or drunk. Or both.)
Domain validation


First, test whether the email domain (the part after the @) exists.
All you have to do is open a socket connection with the domain, and see what happens.
using System.Net;
using System.Net.Sockets;


string email = "recipient@some-domain.com";
string[] host = email.Split('@');
string hostName = host[1];
Socket socket;
try {
IPHostEntry entry = Dns.GetHostEntry(hostName);
IPEndPoint endPoint = new IPEndPoint(entry.AddressList[0], 25);
socket = new Socket(endPoint.AddressFamily, SocketType.Stream,
ProtocolType.Tcp);
socket.Connect(endPoint);
//Yippee - the email domain exists!
} catch (SocketException se) {
//Oops - the email domain is not valid!
}


Account validation


Even if the domain exists and is willing to receive mail, we still don't know whether the mail account exists for the domain. The only way to be sure of this is to try to connect to the account.
We continue with the socket communication process that we started in the previous stage (domain validation). This is the very process used to send an email, and we stop only very short of sending email content. This requires a series of interactions with the email server. We use utility functions to help us: SendData and

CheckSmtpResponse

if (!CheckSmtpResponse(SmtpResponse.CONNECT_SUCCESS)) { //account is invalid! }


//test HELO server
SendData(string.Format("HELO {0}\r\n", Dns.GetHostName()));
if (!CheckSmtpResponse(SmtpResponse.GENERIC_SUCCESS)) { //account is invalid! }


//test for sender domain on blacklist
SendData(string.Format("MAIL From: {0}\r\n", _SenderEmail));
if (!CheckSmtpResponse(SmtpResponse.GENERIC_SUCCESS)) { //account is invalid! }


//test send
SendData(string.Format("RCPT TO: {0}\r\n", email));
if (!CheckSmtpResponse(SmtpResponse.GENERIC_SUCCESS)) { //account is invalid! }


//account is valid!


//utility funtions:


void SendData(string message) {
byte[] bytes = System.Text.Encoding.ASCII.GetBytes(message);
socket.Send(bytes, 0, bytes.Length, SocketFlags.None);
}


enum SmtpResponse : int {
CONNECT_SUCCESS = 220,
GENERIC_SUCCESS = 250,
DATA_SUCCESS = 354,
QUIT_SUCCESS = 221
}


bool CheckSmtpResponse(SmtpResponse code) {
string responseString;
int responseCode;
byte[] bytes = new byte[1024];
while (socket.Available == 0) {
System.Threading.Thread.Sleep(100);
}
socket.Receive(bytes, socket.Available, SocketFlags.None);
responseString = System.Text.Encoding.ASCII.GetString(bytes);
responseCode = Convert.ToInt32(responseString.Substring(0, 3));
return responseCode.Equals(Convert.ToInt32(code));
}

Tuesday, May 10, 2011

Var Vis Dynamic in C# 4


C# 3.0 introduced the implicit type "var". I've explained var as saying:
"I'm too lazy to tell you the type of this variable, so you figure it out, compiler."
However, it's more useful than just promoting terseness or laziness:
1
2
var i = 10; // implicitly typed
int i = 10; //explicitly typed
Although var is a great way to start arguments about coding standards at your work, there are times when it is required around anonymous types. Here's an example from MSDN:
1
2
3
4
5
6
7
8
9
10
11
12
/ Example: var is required because
// the select clause specifies an anonymous type
var custQuery = from cust in customers
                where cust.City == "Phoenix"
                select new { cust.Name, cust.Phone };
// var must be used because each item
// in the sequence is an anonymous type
foreach (var item in custQuery)
{
    Console.WriteLine("Name={0}, Phone={1}", item.Name, item.Phone);
}
C# 4 (not 4.0, the marketing folks say it's .NET 4, etc.) adds the dynamic keyword. I've explained this saying:
"There's no way for you or I to know the type of this now, compiler, so let's hope that the runtime figures it out."
Here's how this looks from an Intellisense point of view. Here I'm hovering over the dynamic keyword:
dynamiccalc1
And here is the tooltip after pressing "." after "calc."
dynamiccalc2
Now, to the interesting question of the day. Christoff Turner asked this question, essentially:
"I noticed the following while doing some research within C# 4.0:"
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
using System;
namespace ConsoleApplication1
{
  class Program
  {
      static void f(Int32 x) { }
      static void f(dynamic x) {}
      static void f(Int32 x, dynamic y) {}
      static void f(dynamic x, Int32 y) {}
      static void f(Int32 x, dynamic y, Int32 z) {}
      static void f(dynamic x, Int32 y, dynamic z) {}
      static void Main(string[] args)
      {
          f(10); // Works - obvious
          f(10, 10); // Ambiguous - obvious
          f(10, 10, 10); // Ambiguous - not so obvious - since it should be possible to resolve
      }
  }
}
"Looking at f(10,10,10), what is the reasoning behind this call being ambiguous?"
I stared it it a while longer, then realized what is happening, and called Mads Torgersen to confirm. Mads says this.
In short, the behavior is totally by design:
  • dynamic in method signatures doesn’t come into it: it behaves like System.Object does.
  • Given that, neither of the ternary signatures is better because each fits better than the other on some arguments (Int32 fits 10 better than object does)
The key point here, in bold, because it's significant is: having the type dynamic means “use my runtime type for binding”.
The problem in the context of method calls is that you can't use the runtime type of something until, um, runtime. ;) Binding with dynamic expressions (dynamic binding) happens at runtime.  In this case, we're compiling against method signatures that are known at compile type and we're compiling with a (mostly) static language, so there's no dynamic method dispatching happening that could select a different method overload at runtime.
The dynamic type is statically-typed as dynamic. The compile-time type is "dynamic" (but really it's object, hence the method overloading trouble.)
Another way to look at this is with Reflector. This C# code:
1
static void f(Int32 x, dynamic y, Int32 z) {}
is essentially this, from a method signature point of view:
1
static void f(int x, [Dynamic] object y, int z) {}
and if there was a method that returned dynamic, it'd look like this:
1
2
[return: Dynamic]
private static object GetCalculator() {}
So, given how dynamic works as a type, how the DLR works in the context of method dispatching, etc, you can see why things didn't work like Christoff thought they would.