Sample Programs in VB

Sample Programs in VB

Program to check the range of a datatype

Public Class Max_Min_Values
Public Shared Sub Main()
Console.WriteLine(Integer.MaxValue)
Console.WriteLine(Integer.MinValue)
Console.WriteLine(Double.MaxValue)
Console.WriteLine(Double.MinValue)
End Sub
End Class

Prog to demonstrate In-Built AscW and ChrW Functions:

Class GetAscii
Shared Sub Main()
Dim str As String = Console.ReadLine()
Dim ch As Char = CChar(str)
Dim n As Integer = AscW(ch)
Console.WriteLine(n)
End Sub
End Class

Program to demonstrate If Statement

Public Class IfDemo
Shared Sub Main()
Dim a, b, c As Integer
Console.WriteLine("Enter 3 Numbers")
a = Integer.Parse(Console.ReadLine())
b = Integer.Parse(Console.ReadLine())
c = Integer.Parse(Console.ReadLine())
Dim max As Integer = a
If (b > max) Then max = b
If (c > max) Then max = c
Console.WriteLine("Greatest No is " & max)
End Sub
End Class

Class IfDemo2

Public Shared Sub Main(ByVal args() As String)
If (args.Length = 0) Then
Console.WriteLine("Please provide a number")
ElseIf (Not Integer.TryParse(args(0), 0)) Then
Console.WriteLine("Not a number")
ElseIf (Integer.Parse(args(0)) Mod 2 = 0) Then
Console.WriteLine("Even number")
Else
Console.WriteLine("Odd number")
End If
End Sub
End Class

Program to demonstrate Select statement

Public Class SelectDemo
Shared Sub Main()
Dim grade As String
Console.WriteLine("Enter a grade")
grade = Console.ReadLine()
Select Case (grade)
Case "E" , "e"
Console.WriteLine("Excellent")
Case "G" , "g"
Console.WriteLine("Good")
Case Else
Console.WriteLine("No Such Grades")
End Select
End Sub
End Class
Public Class SelectCases
Shared Sub Main()
Dim n As Integer
Console.WriteLine("Enter a Number")
n = Integer.Parse(Console.ReadLine())
Select Case (n)
Case 1
Console.WriteLine("Case 1")
Case 2, 3
Console.WriteLine("Case 2,3")
Case 4 To 7
Console.WriteLine("Case 4 To 7")
Case Is < 9
Console.WriteLine("Case Is < 9") Case Is > 9
Console.WriteLine("Case Is > 9")
End Select
End Sub
End Class

Program to demonstrate While loop

Public Class WhileDemo
Shared Sub Main()
Dim marks, count, total As Integer
Dim avg as Double
Console.WriteLine("Enter 6 Subject marks")
While (count < 6)
marks = Integer.Parse(Console.ReadLine())
total += marks
count += 1
End While
avg = total / 6
Console.WriteLine("Total is " & total)
Console.WriteLine("Average is " & avg)
End Sub
End Class

Program to demonstrate While loop

Public Class WhileDemo
Shared Sub Main()
Dim marks, count, total As Integer
Dim avg as Double
Console.WriteLine("Enter 6 Subject marks")
While (count < 6)
marks = Integer.Parse(Console.ReadLine())
total += marks
count += 1
End While
avg = total / 6
Console.WriteLine("Total is " & total)
Console.WriteLine("Average is " & avg)
End Sub
End Class

Program to generate table using For loop

Class Table
Shared Sub Main()
Dim n As Integer
Console.Write("Table of: ")
n = Integer.Parse(Console.ReadLine())
Dim s As String = ""
For i As Integer = 1 To 10
s &= n & "*" & i & "=" & n * i & vbCrLf
Next
Console.WriteLine(s)
End Sub
End Class

Program to print a range of numbers

Dim m, n, incr As Integer
Console.Write("Enter Starting Number: ")
m = Integer.Parse(Console.ReadLine())
Console.Write("Enter Ending Number: ")
n = Integer.Parse(Console.ReadLine())
Console.Write("Increment By: ")
incr = Integer.Parse(Console.ReadLine())
For i As Integer = m To n Step incr
Console.WriteLine(i)
Next i

Program to generate a triangle using For loop

Class Triangle
Public Shared Sub Main()
For i As Integer = 1 To 10
For j As Integer = 1 To i
Console.Write("*" & " ")
Next
Console.WriteLine()
Next
Dim n, m, o As Integer
For n = 10 To 1 Step -1
For o = 0 To n - 1
Console.Write(" ")
Next
For m = n To 10
Console.Write("* ")
Next
Console.WriteLine()
Next
End Sub
End Class

Class PalindromeProgram
Shared Sub Main(ByVal args As String())
Dim str As String
str = Console.ReadLine()
Dim n As Integer = str.Length
For i As Integer = 0 To n \ 2
If (str(i) <> str(n – i – 1)) Then
Console.WriteLine(“Its not a palindrome”)
Return
End If
Next
Console.WriteLine(“Its a palindrome”)
End Sub
End Class

Program to demonstrate Arrays

Public Class Array_Example
Public Shared Sub Main()
Dim ar() As Integer = {1, 2, 3, 4, 5}
Console.WriteLine(ar.Length)
For Each tmp As Integer In ar
Console.WriteLine(tmp)
Next
ReDim ar(10)
For Each tmp As Integer In ar
Console.WriteLine(tmp)
Next
End Sub
End Class

Program to demonstrate Arrays and Array class

Class Program
Shared Sub Main()
Dim ar(-1) As Integer
While (True)
Select Case GetOption()
Case 1
ar = CreateArray()
Case 2
Array.Sort(ar)
Case 3
Array.Reverse(ar)
Case 4
PrintArray(ar)
Case 5
Console.WriteLine("Thank you")
Return
Case Else
Console.WriteLine("Invalid option")
End Select
End While
End Sub
Shared Function GetOption() As Integer
Console.WriteLine("1. Create")
Console.WriteLine("2. Sort")
Console.WriteLine("3. Reverse")
Console.WriteLine("4. Print")
Console.WriteLine("5. Exit")
Console.Write("Enter your option: ")
Return Integer.Parse(Console.ReadLine())
End Function
Shared Function CreateArray() As Integer()
Console.Write("Enter the array length: ")
Dim n As Integer
n = Integer.Parse(Console.ReadLine())
Dim ar(n - 1) As Integer
For i As Integer = 0 To n - 1
Console.Write("Enter the " & i & "th value: ")
ar(i) = CInt(Console.ReadLine())
Next
Return ar
End Function
Shared Sub PrintArray(ByVal ar As Integer())
For Each value As Integer In ar
Console.Write(value & " ")
Next
Console.WriteLine()
End Sub
End Class

ASP.NET MVC framework uses the ASP.NET routing engine

URL Routing

Agenda

  • Overview
  • Mapping URL to Controller Action Method
  • Applying Constraints on Route parameters
  • Resolving Namespace Ambiguity
  • Ignoring Routes

URL Routing Overview

The ASP.NET MVC framework uses the ASP.NET routing engine, which provides flexibility for mapping URLs to controller classes. You can define routing rules that the ASP.NET MVC framework uses in order to evaluate incoming URLs and to select the appropriate controller. You can also have the routing engine automatically parse variables that are defined in the URL, and have the ASP.NET MVC framework pass the values to the controller action methods as parameters.

Global URL Routing Defaults:

Routes are initialized in the Application_Start method of the Global.asax file. The following example shows a typical Global.asax file that class RourteConfig.RegisterRoutes which includes default routing logic.

public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
// . . .
RouteConfig.RegisterRoutes(RouteTable.Routes);
// . . .
}
}
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

routes.MapRoute(
name: “Default”,
url: “{controller}/{action}/{id}”,
defaults: new { controller = “Home”, action = “Index”, id = UrlParameter.Optional }
);
}
}

Implementing Routing for Employee Application:

Add following route methods to the Global.asax file

routes.MapRoute(
"Create", // Route name
"Create", // URL with parameters
new { controller = "Employee", action = "Create" } // Parameter defaults
);
routes.MapRoute(
"Edit", // Route name
"Edit/{Id}", // URL with parameters
new { controller = "Employee", action = "Edit" } // Parameter defaults
);
routes.MapRoute(
"Delete", // Route name
"Delete/{id}", // URL with parameters
new { controller = "Employee", action = "Delete" } // Parameter defaults
);

Note:All the entries must be above “Default” route because otherwise it will take precedence and others will not be useful.

Applying Constraints on Route parameters

routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{name}/{id}",
defaults: new { controller = "Home", action = "Index", name="test", id = UrlParameter.Optional },
constraints: new { name="[a-z]{5}", id = @"\d{1,8}" }
);

The above route puts a constraint on ID that it should be between 1 and 8 digits only.

Example 2: Overloaded version of MapRoute

routes.MapRoute("Default ",
"{controller}/{action}/{id}",
new RouteValueDictionary { //Default Values
controller = "Home",
action = "Index",
name="test",
id = UrlParameter.Optional },
new RouteValueDictionary { //Contraints
{ "name", "[a-z]{5}" },
{ "id", @"\d{4}" } });

 Resolving Namespace Ambiguity

If we have two HomeController Classes in different namespaces.

routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
namespaces: new[] { "MyDemoApp.Controllers" }
);
//OR
ControllerBuilder.Current.DefaultNamespaces.Add("MyDemoApp.Controllers");

Ignoring Route URL’s

If routes.IgnoreRoute(“Home/Index/123”); is added to RegisterRoutes method

the url: http://localhost:49165/Home/Index/123

will render HTTP Error 404.0 – Not Found

soap request and response example in asp.net

  • Every SOAP request and response are made up of SOAPEnvelope. SOAPEnvelope has SOAPHeader, SOAPBody, SOAPFault.
  • SOAP always uses Http Post method and the SOAPEnvelope is submitted as MessageBody.
  • o A Webservice developed in .Net can be used by an Http Client also. Here the method name is submitted as the PathInfo and the parameters are posted as a string of Name-Value pairs.

http:// ServerName/ApplicationName/ DemoService.asmx/ MethodName

SOAP Request

POST /DecWebServices/DemoService.asmx HTTP/1.1

Host: localhost

Content-Type: text/xml; charset=utf-8

Content-Length: length

SOAPAction: “http://tempuri.org/Add”

<?xml version=”1.0″ encoding=”utf-8″?>

<soap:Envelope xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance” xmlns:xsd=”http://www.w3.org/2001/XMLSchema” xmlns:soap=”http://schemas.xmlsoap.org/soap/envelope/”>

<soap:Body>

<Add xmlns=”http://tempuri.org/”>

<a>int</a>

<b>int</b>

</Add>

</soap:Body>

</soap:Envelope>

SOAP Response

HTTP/1.1 200 OK

Content-Type: text/xml; charset=utf-8

Content-Length: length

<?xml version=”1.0″ encoding=”utf-8″?>

<soap:Envelope xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”xmlns:xsd=”http://www.w3.org/2001/XMLSchema” xmlns:soap=”http://schemas.xmlsoap.org/soap/envelope/”>

<soap:Body>

<AddResponse xmlns=”http://tempuri.org/”>

<AddResult>int</AddResult>

</AddResponse>

</soap:Body>

</soap:Envelope>

Note: To view the WSDL document we can use the following URL
http://localhost/SepWebServices/Service.asmx?wsdl

Client Application: (In New Instance of VS.NET)

Step 3: File –> New Project –> Windows Application
Step 4: In the Solution Explorer –> References –> Right Click –> Add Service Reference –> In URL give the Url of Web Service(can copy from browser where we can see the webservice methods) –> Click on Go.
Step 5: In the same dialog: Namespace = localhost (name of domain on which the webservice is hosted is used) –> Click on Add Reference
Note: When a WebService reference is added in VS.Net that is using add Web reference it automatically creates a proxy class in the current project using a utility program called asWSDL.EXE. The same can be viewed by opening the file Reference.cs. (Before this click on Show All Files in Solution Explorer).
Step 6:
using WebServiceClientAppName.localhost
private void btnDemo_Click(object sender, EventArgs e)
{
DemoServiceSoapClient ds = new DemoServiceSoapClient();
MessageBox.Show(ds.Add(20, 50).ToString());
}

Step 7: Run the Client Application
Note: If a new method is added to the webservice class, right click on web reference of the webservice and select Update ervice Reference to reflect the new method in the proxy class.