ASP.NET Basics

27. October 2008 20:34

ASP.NET Special Folders

Bin                               Contains assemblies used by the web application

App_Code                      C# or VB source code that is common to the web site.

                                    Utility classes, modules BasePages etc.

App_Data                       SQLExpress databases used by the web site.

App_GlobalResources      Resources shared across all pages and controls.

App_LocalResources        Resources specifi c to a page or control

App_WebReferences       References to web services

App_Themes                 Contains .skin, .css and image fi les used for the themes of the site.

App_Browsers                Optional .browser capabilities files.

ASP.NET Common Page and Control Directives

<%@ Page Language="C#" %>
<%
@ Page Language="VB" %>
<%
@ Page Language="C#" CodeFile="Page1.ascx.cs" Inherits="Control1" %>
<%
@ Page Language="VB" CodeFile="Page1.ascx.vb" Inherits="Control1" %>

<%@ Control Language="C#" %>
<%
@ Control Language="VB" %>
<%
@ Control Language="C#" CodeFile="Page1.ascx.cs" Inherits="Control1" %>
<%
@ Control Language="VB" CodeFile="Page1.ascx.vb" Inherits="Control1" %>

<%
@ Register TagPrefi x="uc1" TagName="Control1" Src="Control1.ascx" %>
<%
@ Register TagPrefi x="lvs" Namespace="Lvs.Web.UI" Assembly="Lvs.Web" %>

<%
@ Import Namespace="System.Data" %>

<%
@ OutputCache Duration="60" VaryByParam="none" %>
<%
@ OutputCache Location="Server" VaryByParam="param1;param2" Duration="60" %>
<%
@ OutputCache Location="None" NoStore="true" %>

ASP.NET Code Blocks

Inline code block                                                                          
<% Response.Write("Hello World"); %>

Inline render bloc                                                                         
<%= string.Format("2+2={0}", 2+2); %>

Data binding expression block                                                        
<%# Container.ItemIndex %>

Expression block                                                                          
<%$ Resources:String, Hello %>

Page level code. Methods, properties, variable and event handlers.   
<script runat="server"></script>

ASP.NET Markup and Code in Separate Files. "code behind model"

<%@ Page Language="C#" ClassName="Page1_aspx" Inherits="Page1" CodeFile="Page1.aspx.cs" %>

ASP.NET Resources

protected void Page_Load(object sender, EventArgs e)
{
Label1.Text=Resources.
Strings.Hello;
}

<asp:Label ID="Label1" Text="<%$ Resources:Strings, Hello %>" runat="server" />

ASP.NET App Settings

<appSettings>
    <add key="MyKey" value="MyValue" />
</
appSettings>

ASP.NET Connection Strings

<connectionStrings>
    <
add
        name="LocalSqlServer"
        connectionString="
            data source=.\SQLEXPRESS;
            Integrated Security=SSPI;
            AttachDBFilename=|DataDirectory|aspnetdb.mdf;
            User Instance=true
"
        providerName="System.Data.SqlClient"
    />
</
connectionStrings>

ASP.NET Authentication

<authentication mode="Windows" />

<
authentication mode="Forms">
    <
forms
       
loginUrl="Login.aspx"
        defautUrl="Page1.aspx"
        cookieless="AutoDetect"
        domain="mydomain.com"
        requireSSL="true"
    />
</
authentication>

ASP.NET Authorization

<authorization>
    <!--
Deny anonymous users -->
    <
deny users="?" />
    <!--
Allow all authed users -->
    <
allow users="*" />
    <!--
Allow admin role -->
    <
allow roles="Admin" />
</
authorization>

ASP.NET Custom Error Pages

<customeErrors mode="RemoteOnly"
                      defaultRedirect="MyErrorPage.htm">
    <
error statusCode="403" redirect="NoAccess.htm" />
    <
error statusCode="404" redirect="FileNotFound.htm" />
</
customErrors>

ASP.NET Default Settings for Pages

<pages
    theme="MyTheme"
    styleSheetTheme="MyTheme"
    autoEventWireup="true"
    masterPageFile="MyMaster"
    pageBaseType="MyBasePage"
    userControlBaseType="MyBaseControl"
>
    <
controls>
        <
add tagPrefix="uc"
                t
agName="MyControl"
                src="~/Controls/MyControl1.ascx" />
       <
add tagPrefix="pfx"
               tagName="MyAssembly"
               src="My.Namespace" />
    </
controls>
    <
namespaces>
        <
add namespace="System.Text" />
    </
namespaces>
</
pages>

ASP.NET Providers

<membership>
    <
providers>
        <
clear />
        <
add
            name="AspNetSqlMembershipProvider"
            type="System.Web.Security.SqlMembershipProvider,
                System.Web,
                Version=2.0.0.0,
                Culture-neutral,
                PublicKeyToken=b03f5f7f11d50a3a" 
            connectionStringName="LocalSqlServer"
            enablePasswordRetrieval="false"
            enablePasswordReset="true"
            requiresQuestionAndAnswer="true"
            applicationName="/"
            requiresUniqueEmail="false"
            passwordFormat="Hashed"
            maxInvalidPasswordAttempt="5"
            minRequiredPasswordLength="7"
            minRequiredNonalphanumericCharacters="1"
            passwordAttemptWindow="10"
            passwordStrengthRegularExpression=""
        />
   
</providers>
</membership>

<profile>
    <providers>"
        <
clear />
        <add
            name="AspNetSqlProfi leProvider"
            connectionStringName="LocalSqlServer"
            applicationName="/"
            type="System.Web.Profi le.SqlProfi leProvider,
                     System.Web,
                     Version=2.0.0.0,
                     Culture-neutral,
                     PublicKeyToken=b03f5f7f11d50a3a"
    </providers>
</profi le>

<
roleManager>
    <providers>
        <
clear />
        <add
            name="AspNetSqlRoleProvider"
            connectionStringName="LocalSqlServer"
            applicationName="/"
            type="System.Web.Profi le.SqlRoleProvider,
                     System.Web,
                     Version=2.0.0.0,
                     Culture-neutral,
                     PublicKeyToken=b03f5f7f11d50a3a"
    </providers>
</roleManager>

 

 

 

Currently rated 4.0 by 1 people

  • Currently 4/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags:

.Net | ASP.NET

Google Earth For Iphone and Ipod

27. October 2008 07:54

Cool application from Google, Google Earth for Iphone, with this application you can view mountainous terrain, browse the millions of geo-located photos from around the world, browse geo-located Wikipedia articles, with 'Location' feature you can fly to your current location, search cities, places and business globely with Google Local Search and best thing is it is available today in 18 languages and 22 countries in the iTunes App Store.
T
o see Google Earch in Action Click here

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags:

.Net VB Language Basic

26. October 2008 13:17

.Net Working With Numbers VB#

Dim i As Integer = 0

i += 10
' add 10 to i
i -= 5 ' subtract 5 from i
i *= 2 ' multiply i by 2
i /= 2 ' divide i by 2

' parse strings as numbers
' all number types have Parse and TryParse shared functions
Try
    i = Integer.Parse(Console.ReadLine())
    Console.WriteLine(
"You typed a number")
Catch ex As FormatException
    Console.WriteLine(
"Please type a number")
End Try

If Integer
.TryParse(Console.ReadLine(), i) Then
    Console.WriteLine("You typed a number")
Else
    Console.WriteLine("Please type a number")
End If

' money
Dim price As Decimal = 19.99
price =
Decimal.Parse("$39.95" NumberStyles.Currency)

.Net Making Decisions VB#

Dim count As Integer = 10

' simple 1 line if then else
Dim oneHand As Boolean = IIf(count <= 5, True, False)
If count <= 5 Then oneHand = True Else oneHand = False

' multiple conditions
If count = 0 Then
    Console.WriteLine("Zero")
ElseIf count > 0 And count < 6 Then
    Console.WriteLine("Count on one hand.")
ElseIf count >= 6 And count <= 10 Then
    Console.WriteLine("Count on two hands.")
Else
    Console.WriteLine("Not enough fi ngers.")
End If

' select case
Select Case count
    Case 0 ' simple value expression
        Console.WriteLine("Zero.")
    Case 1 To 5 ' a range of values
        Console.WriteLine("Count on one hand.")
    Case 6, 7 To 9, 10 ' multiple expressions
        Console.WriteLine("Count on two hands.")
    Case Is > 10, Is <= 20 ' use comparison operators
        Console.WriteLine("Count on hands and feet.")
    Case Else
        Console.WriteLine("Not enough fi ngers and toes.")
End Select

.Net Working With Strings VB# 

Dim s As String = "Hello World"
Debug.Assert(s.Contains("World"))
Debug.Assert(7 = s.IndexOf(
"World"))
Debug.Assert(s.StartsWith(
"Hello"))
Debug.Assert(s.Substring(0, 5) =
"Hello")
' combining and formatting strings
s = "Hello" + " " + "World"
s = String.Format("s is: {0}", s)
Dim sb As New StringBuilder()
For i As Integer = 0 To 100
    sb.AppendFormat(
"{0},", i)
Next
s = sb.ToString()

.Net Working With Dates and Times VB#

Dim now As Date = Date.Now ' date and time
Dim today As Date = Date.Today ' just the date
Dim tomorrow As Date = today.AddDays(1)
Dim yesterday As Date = today.AddDays(-1)

' use parse functions to convert from strings
Dim vb1 As Date = Date.Parse("1991-05-01")

' use culture info to parse dates in regional formats
Dim gb As New CultureInfo("en-GB")
vb1 =
Date.Parse("01-05-1991", gb.DateTimeFormat)

' format dates as strings
vb1.ToLongDateString()          ' Wednesday, May 01, 1991
vb1.ToShortDateString()         ' 5/1/1991
vb1.ToLongTimeString()         ' 12:00:00 AM
vb1.ToShortTimeString()        ' 12:00 AM
vb1.ToString("u")                  ' 1991-05-01 00:00:00Z
vb1.ToString("yyyy-MM-dd")   ' 1991-05-01

' TimeSpan represents differnce between two dates
Dim time As TimeSpan = tomorrow - today
Dim days As Integer = time.Days
Dim hours As Integer = time.Hours
Dim minutes As Integer = time.Minutes
Dim seconds As Integer = time.Seconds
Dim milliseconds As Integer = time.Milliseconds

' Add time using other timespan instances
time.Add(New TimeSpan(days, hours, minutes, seconds,
    milliseconds))
' or
time += New TimeSpan(days, hours, minutes, seconds,
    milliseconds)

' use a timespan to add time to a date
today.Add(time)
' or
today += time
' timespan represented as Days.Hours:Minutes:Seconds:
' Subseconds
time = TimeSpan.Parse("1.2:3:4:5")
' or
If TimeSpan.TryParse(Console.ReadLine(), time) Then
    Console.WriteLine(time)
End If

.Net Making Comparisons VB#

Debug.Assert(1 = 1) ' equal
Debug.Assert(1 <> 2) ' not equal
Debug.Assert(1 <= 2) ' less than or equal
Debug.Assert(1 >= 0) ' greater than or equal
Debug.Assert(1 < 2) ' less than
Debug.Assert(1 > 0) ' greater than

.Net Working With Objects VB#

Dim o As Object = "Hello World"
' check type of object
Debug.Assert(TypeOf o Is String)
' check if reference is not set
Debug.Assert(Not o Is Nothing)

.Net Loops VB#

For i As Integer = 10 To 1 Step -1

    Console.WriteLine(i)
    If i < 5 Then

        Exit For
    End If
Next
Dim start As Integer = 5
For i As Integer = start To start + 10

    Console.WriteLine(i)
Next
Dim
str As String
Do
    str = Console.ReadLine()
    Console.WriteLine(str)
Loop Until str = ""
Do
    str = Console.ReadLine().Trim()
    If String.IsNullOrEmpty(str) Then
        Exit Do
    End If
    Console.WriteLine("You typed:{0}", str)
Loop
Dim names As String() = New String() {"Tom", "Daniel"}
For Each name As String In names
    Console.WriteLine(name)
Next

.Net Working With Text VB#

Imports System.IO
Imports System.Text

Dim name As String = "Daniel"
Dim hello1 As String = "Hello " + name
Dim hello2 As String = String.Format("Hello {0}", name)
Console.WriteLine(
"Hello {0}", name)
Dim sb As New StringBuilder("Hello ")
sb.AppendLine(name)
sb.AppendFormat(
"Goodbye {0}", name)
Console.WriteLine(sb.ToString())

' create a text file
Using w As StreamWriter = File.CreateText("c:\names.txt")
    w.WriteLine(
"Tom")
    w.WriteLine(
"Daniel")
End Using

' read from a text fi le
Using r As StreamReader = File.OpenText("c:\names.txt")
    Do While Not r.EndOfStream
        Console.WriteLine(r.ReadLine())
    Loop
End Using
For Each
s As String In File.ReadAllLines("c:\names.txt")
    Console.WriteLine(s)
Next

.Net Working With XML VB#

Imports System.IO
Imports System.Xml

' create an xml fi le
Using xw As XmlWriter = XmlWriter.Create("c:\names.xml")
    xw.WriteRaw(
"<names>")
    xw.WriteRaw(
"<name>Tom</name>")
    xw.WriteRaw(
"<name>Daniel</name>")
    xw.WriteRaw(
"</names>")
End Using

' load an xml fi le
Dim doc As New XmlDocument()
doc.Load(
"c:\names.xml")
For Each node As XmlNode In doc.SelectNodes("//name/text()")
    Console.WriteLine(node.Value)
Next

.Net Working With a Database VB#

Imports System.Data
Imports System.Data.SqlClient

Dim cs As String = "Data Source=.\SQLEXPRESS;" + _
                          
"Initial Catalog=NamesDB;" + _
                         
"Integrated Security=True;"
Using con As New SqlConnection(cs)
    con.Open()
    ' insert a record
    sql = "INSERT INTO Names(Name) VALUES(@Name)"
    Dim cmd1 As New SqlCommand(sql, con)
    cmd1.Parameters.Add(
"@Name", SqlDbType.NVarChar, 100)
    cmd1.Parameters(
"@Name").Value = "Tom"
    cmd1.ExecuteNonQuery()
    ' insert a second record
    cmd1.Parameters("@Name").Value = "Daniel"
    cmd1.ExecuteNonQuery()
    ' read records
    sql = "SELECT * FROM Names"
    Dim cmd2 As New SqlCommand(sql, con)
    Using r As SqlDataReader = cmd2.ExecuteReader()
        Dim iName As Integer = r.GetOrdinal("Name")
        Do While r.Read()
            If r.IsDbNull(iName) Then
                Console.WriteLine("Null")
            Else
                Console.WriteLine(r.GetString(iName))
            End If
        Loop
    End Using
    ' read a single value
    sql = "SELECT TOP 1 Name FROM Names"
    Dim cmd3 As New SqlCommand(sql, con)
    Console.WriteLine(cmd3.ExecuteScalar())
End Using

.Net Classes VB#

' Fields, properties, methods and constructors
Public Class SomeClass
    ' field
    Private mName As String
    ' read/write property
    Public Property Name() As String
        Get
            Return
mName
        End Get
        Set
(ByVal value As String)
            mName = value
        End Set
    End Property
    ' read only property
    Public ReadOnly Property FormattedName() As String
        Get
            Return
String.Format("Hello {0}", mName)
        End Get
    End Property
    ' methods/procedures
    Public Sub PrintName(ByVal format As String)
        Console.WriteLine(format,
Me.FormattedName)
    End Sub
    ' constructor
    Sub New(ByVal name As String)
        mName = name
    End Sub
End Class

' Inheritance/Subclassing
Public Class BaseClass
    Public Overridable Sub SayHello()
        Console.WriteLine("Hello BaseClass")
    End Sub
End Class
Public Class
DerivedClass
    Inherits BaseClass
    ' override inherited method
    Public Overrides Sub SayHello()
        ' invoke the base class version of the method
        MyBase.SayHello()
        Console.WriteLine(
"Hello DerivedClass")
    End Sub
End Class



 

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags: ,

.Net | .Net VB



Powered by BlogEngine.NET 1.4.5.0