Wednesday, August 12, 2009

How to find the size of a Directory

nd the size of a Directory



Working with files and
directories is one of my favorites! With the help of the namespace, System.IO we can parse through the entire hard disk of our
computer. The System.IO namespace has rich inbuilt
methods/functions for every common task that we need to do. With the help of
these functions, we can easily write code for:



Does this file exist?

What is the size of this file?

Delete this file

Get all files in this directory ... and so on.



But the said namespace or other namespace does not provide us with a function
which gives the directory size. One way to find the directory size of any
folder/directory is as follows:



1) Start from the directory/folder that we need to find the size

2) Find all files in the current directory

3) Loop through each file and find the size of
each file

4) Chances are, we may end up with sub-folders.

5) We also need to find the number of files in this sub-folder

6) Since this is a repeating process, we should have a recursive mechanism were
we will parse through the end (until no more sub-directories exists)



The following example consists of three functions. A) Public DirectorySize(ByVal strStartDirectory as String)

B) Private FindDirectorySize(ByVal
strCurrentDir As String)

C) Private Sub RecursiveParseDirectory(ByVal strDirectory As String)



Include all the three functions in aspx or codebehind page and invoke the function, DirectorySize. Pass the folder/directory name as an
argument to this method and it will return you the size of the directory. You
will also need to declare a global variable called: intDirectorySize
which is of type, Integer.








Dim intDirectorySize As Integer



Public Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)

' For this example, I have used "." which represents the current
directory



lblMsg.Text =
"Directory size is " & DirectorySize(".")

End Sub



Public Function DirectorySize(ByVal
strStartDir As String)

Dim strStartDirectory
As String = Server.MapPath(strStartDir)



FindDirectorySize(strStartDirectory)

RecursiveParseDirectory(strStartDirectory)



Return intDirectorySize

End Function



Private Sub RecursiveParseDirectory(ByVal strDirectory As String)

Dim strTemp As String

Dim arrSubDirectories()
As String = Directory.GetDirectories(strDirectory)



For Each strTemp In arrSubDirectories

FindDirectorySize(strTemp)

RecursiveParseDirectory(strTemp)

Next

End Sub



Private Sub FindDirectorySize(ByVal
strCurrentDir As String)

Dim DI As DirectoryInfo
= New DirectoryInfo(strCurrentDir)

Dim arrFiles As Array
= DI.GetFiles()

Dim FI As FileInfo

Dim intDirsize As
Integer = 0



For Each FI In arrFiles

intDirsize += FI.Length

Next



intDirectorySize += intDirsize

End Sub











How to retrieve the properties of file uploaded by the user.


We have already known how to upload the file in the server, in this<br />program we will see How to retrieve the properties of file uploaded by the user
We have already known how to
upload the file in the server, in this program we will see How to retrieve the
properties of file uploaded by the user.


We can retrieve some of
the interesting and useful properties of the file that is uploaded to the
webserver. The PostedFile provides us with three important properties, such as
FileName, ContentType and ContentLength. In our previous example, we already
saw, how to use the property, FileName? Now, we will see, how to know the size
of the file uploaded, and how to know the contentType of the file uploaded.



The following line of code
retrieves the ContentType of the file uploaded.



lblFileContentType.Text = MyFile.PostedFile.ContentType



The following line of code
retrieves the Size of the file uploaded.




lblFileSize.Text = CStr(MyFile.PostedFile.ContentLength)

Now, we will see an example which uses this property.



Example: Uploading a File in ASP .NET








<html>

<head>

<script language="VB" runat="server">



Sub Upload(Source As Object, e As EventArgs)



If Not (myFile.PostedFile Is Nothing) Then



Dim intFileNameLength as Integer

Dim strFileNamePath as String

Dim strFileNameOnly as String



'Logic to find the FileName (excluding
the path)

strFileNamePath =
MyFile.PostedFile.FileName

intFileNameLength = Instr(1,
StrReverse(strFileNamePath), "\")

strFileNameOnly = Mid(strFileNamePath,
(Len(strFileNamePath)-intFileNameLength)+2)



myFile.PostedFile.SaveAs("c:\inetpub\wwwroot\yourwebapp\upload\"
& strFileNameOnly)

lblMsg.Text = "File Upload
Success."

lblFileContentType.Text = "Content type: " &
MyFile.PostedFile.ContentType

lblFileSize.Text = "File size: " &
CStr(MyFile.PostedFile.ContentLength) & " bytes"



End If

End Sub

</script>



</head>

<body>



<h3>File Upload</h3>



<form enctype="multipart/form-data" runat="server">

File: <input id="myFile" type="file"
runat="server"> <input type=button
value="Upload" OnServerClick="Upload"
runat="server">

<asp:label id=lblMsg runat="server" />

<asp:label id=lblFileContentType
runat="server" />

<asp:label id=lblFileSize runat="server" />

</form>



</body>

</html>






Test this Script



How to control the size of file
uploaded to the web server?


While uploading a file to
the web server, we have a limit of 4MB by default. We can either decrease or
increase this value. The value is set in the key, maxRequestLength of machine
config file.



There is a maxRequestLength limit in the machine.config file (look for the
<system.web> section); in the http Runtime settings that you need to
alter/raise if you want to accept anything larger than 4Mb. These are the
standard settings for the httpRuntime:



<httpRuntime executionTimeout="90" maxRequestLength="4096"

useFullyQualifiedRedirectUrl="false" minFreeThreads="8"

minLocalRequestFreeThreads="4"
appRequestQueueLimit="100"/>










Sending an email with asp

Sending email is a very common task in any web application

Sending email is a very common task in any
web application. In almost every web application (web site), their will at
least be an occasion to send email in any fashion. In classic ASP, we worked
with the CDONTS object to send emails from an ASP page. The SMTP Mail class in
ASP .NET provides properties and methods for sending messages using the
Collaboration Data Objects for Windows 2000 (CDOSYS) message component In this
article, we will see, how can we send email from an ASP .NET page. In a nut
shell, today, we will be looking into the following:




  • What we need to send Email
    from an ASP .NET?

  • How to send an email from
    an ASP .NET page?

  • What is new in sending
    email? (SmtpMail.SmtpServer)



What we need to send Email
from an ASP .NET?


The first thing that you need is the SMTP
service. SMTP service should be up and running. And you also need to import the
namespace, System.Web.Mail. To create a mail object, you need to create
an instance of MailMessage. MailMessage has all required properties such
as To, Subject, BCC, CC etc. For a complete list of method and properties, that
you can make use of, please visit



How to send an email from an
ASP .NET page?








<%@ Import Namespace="System.Web.Mail" %>



<html>



<script language="VB" runat="server">

Sub Page_Load(Sender As Object, E As EventArgs)



Dim msg as New MailMessage()



msg.To = "saurav@vb-tek.com"

msg.From = "abhi@vb-tek.com"

msg.Subject = "test"

'msg.BodyFormat = MailFormat.Html

msg.BodyFormat = MailFormat.Text

msg.Body = "hi"



SmtpMail.SmtpServer = "localhost"



SmtpMail.Send(msg)

msg = Nothing

lblMsg.Text = "An Email has been send to
" & "das@silicomm.com"



End Sub

</script>



<body style="font: 10pt verdana">

<form runat=server>

<asp:Label id=lblMsg runat=Server /> </form>

</body>

</html>






In the above example, we
start the coding by importing the namespace, "System.Web.Mail". Then,
in the Page_Load event, we create an instance of MailMessage object. It is
through the MailMessage object, we set all the properties such as To, From,
Subject, Body etc. We can either send a text message or a html message. We need
to specify the bodyformat in the BodyFormat property. One we set all the
properties, it is ready to send the email. Before sending the email, you have
to set another important property, ie; SmtpServer. You have to set this
property. You should assign the name of your SMTP server to this property. In
most cases you can assign this as "localhost". If you do not set this
property, then you will not be able to send email from an ASP .NET page.
Finally we send the email using SmtpMail.Send. This method expects the
MailMessage as an argument. Actually the method Send is overloaded. You can
also send an email by specifiying, SmtpMail.Send (From, To, subject, body).



Monday, August 10, 2009

How to upload files in ASP .NET


Asking the user to upload
a file to the server is a very very common task in
most of the web applications. In classic ASP, uploading file was a very
difficult task, since we need a third party component or we need to write our
component to upload file from client to the server. In ASP .NET Uploading a file from client to the web server is so easy.
To be precise, we can get this done in two lines of code. Yes, two lines of
code. In this article, we will be looking into the following:




  • How to Upload a file from
    Client to the Web server in ASP .NET?




First of all, we need a
HTML server control to allow the user to select the file. This is nothing but
the same old <input tag, with the type set to File, such as <input
type=file id=myFile runat=server
/>
. This will give you the textbox and a browse button. Once you have
this, the user can select any file from their computer (or even from a
network). Then, in the Server side, we need the following line to save the file
to the Web Server.


myFile.PostedFile.SaveAs("DestinationPath")

Example: Uploading a File in ASP .NET




<html>

<head>

<script language="VB" runat="server">



Sub Upload(Source As Object, e As EventArgs)



If Not (myFile.PostedFile Is
Nothing) Then



Dim intFileNameLength
as Integer

Dim strFileNamePath
as String

Dim strFileNameOnly
as String



'Logic to find the FileName
(excluding the path)

strFileNamePath
= MyFile.PostedFile.FileName

intFileNameLength
= Instr(1, StrReverse(strFileNamePath), "\")

strFileNameOnly
= Mid(strFileNamePath, (Len(strFileNamePath)-intFileNameLength)+2)



myFile.PostedFile.SaveAs("c:\inetpub\wwwroot\yourwebapp\upload\"
& strFileNameOnly)

lblMsg.Text =
"File Upload Success."



End If

End Sub

</script>



</head>

<body>



<h3>File Upload</h3>



<form enctype="multipart/form-data" runat="server">

File: <input id="myFile"
type="file" runat="server">

<asp:label id=lblMsg runat="server"
/>

<input type=button value="Upload" OnServerClick="Upload" runat="server">

</form>



</body>

</html>




In the above example, you
should note that, in the FORM tag, we have set the ectype to "multipart/form-data".
This is another important aspect while uploading a file to the web server. We
have a Input
tag which is of type file
. Then we have a button called
"Upload". On the onclick of the button, you
can see that, we are using some string functions to find the FileName (excluding the path). Finally, we invoke the
method SaveAs
to save the file (upload) in the web server.

Simple Registry Editing

In this program we will show you how to work with registry.

this program is going to hide the turnoff option from the start menu

Just Copy and paste this simple code into your vb.net application and log off your computer and next log on having the same user account then will not be able to shutdown your computer.

In code window above the class Form1 write following line to import


Imports Mycrosoft.Win32


Then take a button and write down the following code into Button1_Click Subroutine



Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)


Handles Button1.Click


Dim regvar As RegistryKey


Dim keyvalue As String


keyvalue = "Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer"


regvar = Registry.CurrentUser.OpenSubKey(keyvalue, True)


regvar.SetValue("NoClose", 1)


Dim x As Integer = regvar.GetValue("NoClose")


End Sub


End Class

Solution: - If you want to get back your turnoff option just change the following line and run the vb.net program again.



regvar.SetValue("NoClose", 1) to

regvar.SetValue("NoClose", 0)

Sunday, August 2, 2009

Make a simple browser

In this program a browser will be created and we will be able to be

Back, forward, refresh, stop, and go to homepage. The form will

Look as follow.

In code window above the class Form1 write following 4 lines to import


Imports System.IO

Imports System.Net

Imports System.Text

Imports System.Windows.Forms

Now double click the back button and write the following code in side button1_Click sub.



Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

WebBrowser1.GoBack()

TextBox1.Text = WebBrowser1.Url.ToString()

End Sub



Now double click the Forward button and write the following code in side button2_Click sub



Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click

WebBrowser1.GoForward()

TextBox1.Text = WebBrowser1.Url.ToString()

End Sub

Now double click the Stop button and write the following code in side button3_Click sub



Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click

WebBrowser1.Stop()

End Sub

Now double click the Refresh button and write the following code in side button4_Click sub



Private Sub Button5_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click

WebBrowser1.Refresh()

End Sub

Now double click the home button and write the following code in side button5_Click sub



Private Sub Button5_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click

WebBrowser1.GoHome()

TextBox1.Text = WebBrowser1.Url.ToString()

End Sub

Now double click the form and write the following code in side from load Click sub



Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

Button1.Enabled = False

Button2.Enabled = False

Button3.Enabled = False

End Sub

Now double click the web browser1 and choose from the Dropdown event to


CanGoBackChanged”.

Now write the following code in sub


WebBrowser1_CanGoBackChanged



Private Sub WebBrowser1_CanGoBackChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles WebBrowser1.CanGoBackChanged

If WebBrowser1.CanGoBack = True Then

Button1.Enabled = True

Else

Button1.Enabled = False

End If

End Sub

Now do the same and create Sub WebBrowser1_CanGoForwardChanged

And write the following code inside the sub.



Private Sub WebBrowser1_CanGoForwardChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles WebBrowser1.CanGoForwardChanged

If WebBrowser1.CanGoForward = True Then

Button2.Enabled = True

Else

Button2.Enabled = False

End If

End Sub

Again do the same for the following sub WebBrowser1_DocumentCompleted



Private Sub WebBrowser1_DocumentCompleted(ByVal sender As System.Object, ByVal e As System.Windows.Forms.WebBrowserDocumentCompletedEventArgs) Handles WebBrowser1.DocumentCompleted

Button3.Enabled = False

End Sub

Again do the same for the following WebBrowser1_Navigated



Private Sub WebBrowser1_Navigated(ByVal sender As Object, ByVal e As System.Windows.Forms.WebBrowserNavigatedEventArgs) Handles WebBrowser1.Navigated

TextBox1.Text = WebBrowser1.Url.ToString()

Me.Text = WebBrowser1.DocumentTitle.ToString()

End Sub

Again do the same for the following WebBrowser1_Navigating



Private Sub WebBrowser1_Navigating(ByVal sender As Object, ByVal e As System.Windows.Forms.WebBrowserNavigatingEventArgs) Handles WebBrowser1.Navigating

Button3.Enabled = True

End Sub

End Class

Finally double click the go button and write the following code in side button6_Click sub



Private Sub Button6_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button6.Click

WebBrowser1.Navigate(TextBox1.Text)

End Sub


Friday, July 17, 2009

Visual Studio 2010 Professional Beta 1 – Web Installer

Microsoft Visual Studio 2010 and the .NET Framework 4 are the next generation of Microsoft development tools. Visual Studio 2010 Professional has been engineered to support the development of applications for Windows, the Web, and Office.

Click Here to Download Visual Studio 2010 Professional Beta 1

Enhanced User Experience


Microsoft Visual Studio 2010 delivers a modern, enhanced user experience that makes understanding the current context more natural.

  • Clear UI Organization
  • Reduced clutter and complexity
  • Improved editor
  • Better support for floating documents and windows
  • Enhanced document targeting
  • Focused animations for action feedback

Parallel Programming

Parallel programming is simplified, so both native- and managed-code developers can productively build innovative applications.

  • IDE support for parallel programming
  • Native C++ libraries that use lambda functions and align well with STL
  • Parallel Extensions to the .NET Framework offers support for imperative data and task parallelism, declarative data parallelism, and more
  • Resource management of the multicore hardware and task scheduling enabled by Concurrency Runtime
  • Parallel debugging windows and profiling views
Democratizing Application Lifecycle Management


Visual Studio Team System 2010 delivers new capabilities for everyone on a project, including architects, developers, project managers and testers.

  • Discover existing code assets with the new Architecture Explorer
  • Design and share multiple diagram types, including use case, activity and sequence diagrams
  • Tooling for better documentation of test scenarios and more thorough collection of test data
  • Run tests impacted by a code change with the new Test Impact View
  • Gated check-in, branch visualization and build workflow allow for enhanced version control
Inspiring Developer Delight

Visual Studio has made application development more productive, efficient and flexible for both developers and companies. Visual Studio 2010 continues this legacy.

  • Contextual support helps developers better understand existing code – and write new code more efficiently
  • First class C++ development experience that helps developers navigate and understand complex C++ source bases
  • Build new Windows® 7 applications or upgrade existing applications
  • Enable Office tools to make your solutions more flexible and productive for specific needs

Web Development


With Visual Studio 2010, we're continuing our investment in great Web development tools.

  • A high-performance and standards-compliant JavaScript IntelliSense® engine
  • "One Click Deployment" that quickly publishes files and configuration settings from development machines to the final deployed site
  • Full support for Silverlight™ for cutting-edge, rich Internet applications

Cloud Development

With Windows Azure™ Tools for Visual Studio, it's easy for developers to build, debug and deploy services and applications for Microsoft's new cloud platform.

  • C# and VB Project Templates for building Cloud Services
  • Tools to change the Service Role configuration
  • Integrated local development via Development Fabric and Development Storage services
  • Debugging Cloud Service Roles running in the Development Fabric
  • Building and packaging of Cloud Service Packages
  • Browsing to the Azure Services Developer Portal
More Databases


With the Visual Studio partner ecosystem, developers will now be able to work with IBM DB2 and Oracle databases in addition to Microsoft SQL Server™ databases.

IBM has committed to develop, sell and support a Database Schema Provider (DSP) to let developers working with DB2 on the Windows, Linux or Unix platforms do offline design, development, testing and change management using Visual Studio Team System 2010 Development Edition.

Quest Software have made a similar commitment develop, sell and support a DSP which will enable Oracle Developers to work with their databases just as easily.

Click Here to Download Visual Studio 2010 Professional Beta 1

Thursday, July 16, 2009

Visual Basic .Net Black Book


  • Paperback: 472 pages
  • Publisher: Coriolis Group Books; 1st edition (April 19, 2002)
  • Language: English
  • ISBN-10: 1576108635
  • ISBN-13: 978-1576108635
Product Description
Visual Basic .NET Core Language Little Black Book is an indispensable quick reference guide to Visual Basic .NET syntax and data organization. Readers get a guided tour with an expert programmer who concisely explains how to use the Visual Basic tools, from the Integrated Development Environment to the debugger. It helps readers master common programming tasks, such as working with databases, ASP.NET, ADO.NET, and the core Visual Basic controls. This at-your-fingertips guide focuses on core programming topics and writing code. Plus, it includes a tear-out, quick-reference card summarizing the Visual Basic .NET language.

About the Author
Steven Holzner (Cambridge, MA) is a former contributing editor for PC Magazine and has authored more than 60 books ranging in subject from assembly language to C++. His books have sold over a million copies and have been translated into 15 languages. Steven was on the faculty of Cornell University for 10 years, where he earned his Ph.D., and has also been on the faculty of his undergraduate school, Massachusetts Institute of Technology.

Click here to download

Make GIF image

In this program at first a simple graphics object will be created and then it will be saved as gif image. First open a project as windows application, and then add a button. Form will look as follow


In code window above the class Form1 write following 2 lines to import

Imports System.Drawing
Imports System.Drawing.Imaging

Now double click the button1 and write the following code in side button1_Click sub.

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

Dim bm As New Bitmap(256, 256)

Dim gr As Graphics = Graphics.FromImage(bm)

gr.Clear(Color.White)

gr.FillRectangle(Brushes.Yellow, 5, 5, bm.Width - 10, bm.Height - 10)

gr.DrawLine(Pens.Green, 0, 0, bm.Width - 1, bm.Height - 1)

gr.DrawLine(Pens.Blue, bm.Width - 1, 0, 0, bm.Height - 1)

bm.Save("c:\image.gif", ImageFormat.Gif)

End Sub


The image will be saved as image.gif file in C drive, and the following image will be saved


image.gif

So lets try.


Get Current Running Process in Listbox

This program will show all the running process in a listbox.
Open project as windows application and add one listbox and one button there.
Form will look like this


Now double click the button and just copy paste or write the following code inside button1

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim plist() As Process
Dim myprocess As System.Diagnostics.Process
plist = Process.GetProcesses
ListBox1.Items.Clear()

For Each myprocess In plist
ListBox1.Items.Add(myprocess.ProcessName)
Next
End Sub

Now Run the program and click the button1.