Using The .NET Framework

Page 1

Using the .NET Framework

Learn More @ http://www.learnnowonline.com Copyright Š by Application Developers Training Company


Objectives • • • •

Review using .NET Framework classes Explore basic file IO operations Learn how to work with strings See how to work with dates and times

Learn More @ http://www.learnnowonline.com Copyright © by Application Developers Training Company


.NET Framework Base Class Library • BCL consists of classes that provide base functionality for .NET Framework  Many classes that make your life as a developer easier  Library of classes used by all .NET applications

• Contains large number of classes (blocks of functionality, including properties, methods, and events) • Namespaces group classes into common blocks of functionality  Each class within a namespace has a unique name Learn More @ http://www.learnnowonline.com Copyright © by Application Developers Training Company


Some BCL Namespaces • • • • • • • • • •

System System.Data System.Diagnostics System.Globalization System.IO System.Text System.Text.RegularExpressions System.Web System.Windows.Forms System.Xml Learn More @ http://www.learnnowonline.com Copyright © by Application Developers Training Company


Using .NET Framework Classes • Code you write in applications will be a mix of code that is specific to a language and code that uses .NET Framework classes Dim amount As Decimal = 45.61D Dim dollars, cents As Decimal

decimal amount = 45.61M; decimal dollars, cents;

dollars = Decimal.Truncate(amount) cents = amount - dollars

dollars = decimal.Truncate(amount); cents = amount - collars;

Console.WriteLine( _ "The restaurant bill is {0:C}", _ amount) Console.WriteLine( _ "You pay the {0:C} and " & _ "I'll pay the {1:C}", _ dollars, cents)

Console.WriteLine( "The restaurant bill is {0:C}", amount); Console.WriteLine( "You pay the {0:C} and " + "I'll pay the {1:C}", dollars, cents);

Learn More @ http://www.learnnowonline.com Copyright Š by Application Developers Training Company


Generating Random Numbers • Use Random class to generate a series of random numbers  Generated random numbers start with seed value  Specify seed value or use default seed value

• Next generates the next random number in a sequence

Learn More @ http://www.learnnowonline.com Copyright © by Application Developers Training Company


Getting Information about the Computer

• Environment class provides information on the computer and the environment in which the computer is running • Properties     

MachineName returns name of computer UserName returns name of user OSVersion returns operating system name and version CurrentDirectory returns program’s directory at runtime Version returns version of the CLR

• Use GetFolderPath and SpecialFolder enumeration to refer to My Documents, desktop, etc. Learn More @ http://www.learnnowonline.com Copyright © by Application Developers Training Company


Working with XML • System.Xml namespace contains classes that support reading and writing XML • Quick review of XML    

XML documents are based on elements Element comprised of start tag, content, and end tag Elements can contain other elements Attributes contain information about elements <chapters total = "2"> <chapter>Variables and Data Types</chapter> <chapter>Using the .NET Framework</chapter> </chapters>

Learn More @ http://www.learnnowonline.com Copyright © by Application Developers Training Company


Writing XML Files • Use XmlWriter class to write XML to file or in memory  Use Create to create a new instance and pass the name of an XML file as a parameter

• Use XmlWriterSettings class to control how XML is written  Indent specifies that elements should be indented  IndentChars specifies the character to use  NewLineChars specifies the character for line breaks

Learn More @ http://www.learnnowonline.com Copyright © by Application Developers Training Company


Writing XML Files • WriteStartDocument writes XML declaration <?xml version="1.0" encoding="utf-8" standalone="yes"?> • WriteStartElement adds an XML tag <chapters> • WriteEndElement adds a closing tag </chapters> • WriteAttributeString writes an attribute and its value <chapters total = "2“> • WriteElement adds an element and its value <chapter>Using the .NET Framework</chapter> Learn More @ http://www.learnnowonline.com Copyright © by Application Developers Training Company


Reading XML Files • Use XmlReader class to read XML from file or from memory  Use Create to create a new instance and pass name of XML file as parameter

• Read reads each node in the XML one at a time  Use NodeType to determine if a node is an element or text, etc.

• ReadToFollowing reads through XML until it finds the next element with a specified name • ReadInnerXml reads the content of an element Learn More @ http://www.learnnowonline.com Copyright © by Application Developers Training Company


File Input/Output • System.IO namespace contains classes for writing to and reading from files and for managing drives, directories, and files

Learn More @ http://www.learnnowonline.com Copyright Š by Application Developers Training Company


Writing to and Reading from Files • StreamWriter class creates and writes to file  Write adds text to file  WriteLine adds text and line break to file

• StreamReader class reads from file  Read reads text from file  ReadLine reads lines of text from file

Learn More @ http://www.learnnowonline.com Copyright © by Application Developers Training Company


Managing Files • FileInfo class contains methods for copying, moving, renaming, creating, opening, deleting, and appending to files • Exists returns true if file exists • Create creates a file  Returns an instance of FileStream class o o o

Use AppendText to add text to a file Use CreateText to add text after removing existing text Both of these return an instance of StreamWriter class • Use Write and WriteLine to write text to a file

Learn More @ http://www.learnnowonline.com Copyright © by Application Developers Training Company


Managing Files • FileInfo properties to retrieve file information      

Name returns file name FullName returns full path including file name Length returns file size IsReadOnly returns true if file is read-only CreationTime returns when file was created LastAccessTime returns when file was last accessed

• CopyTo copies a file • Delete deletes a file Learn More @ http://www.learnnowonline.com Copyright © by Application Developers Training Company


Managing Directories • DirectoryInfo class contains methods for creating, moving, and deleting directories, as well as getting a list of files in the directory • Exists returns true if a directory exists • Create creates a directory • Delete removes a directory • Name returns the name of a directory • FullName returns the full path and name of a directory Learn More @ http://www.learnnowonline.com Copyright © by Application Developers Training Company


Getting Information from Drives • DriveInfo class returns information from a drive • GetDrives returns a list of all drives on a computer • Properties to view drive information Name returns drive name DriveType returns drive type, e.g., Fixed, Network, CDRom DriveFormat returns file system name, e.g., NTFS or FAT32 VolumeLabel returns volume label IsReady returns true if drive is ready for read or read/write operations  TotalSize returns total storage capacity  TotalFreeSpace returns total amount of free space available  AvailableFreeSpace returns total amount of free space available after taking into account disk quotas     

Learn More @ http://www.learnnowonline.com Copyright © by Application Developers Training Company


Working with Strings • Wide variety of tasks you might want to accomplish when working with strings  Separate out first and last name from string representing someone’s full name  Convert string to all uppercase  Concatenate two strings representing a first and last name and create a string containing a last name, followed by a comma, followed by a first name  Display a number in currency format, for example $9,999.99  Replace some of a string with another string Learn More @ http://www.learnnowonline.com Copyright © by Application Developers Training Company


String Class Fields and Properties • Empty represents an empty string • Length returns the number of characters • Chars returns a character at a position in a string

Learn More @ http://www.learnnowonline.com Copyright © by Application Developers Training Company


String Class Methods • String class includes methods for a variety of tasks     

Comparing two strings Searching for a string in another string Modifying all or some of a string Extracting part of a string from a string Formatting the display of a string

Learn More @ http://www.learnnowonline.com Copyright © by Application Developers Training Company


Comparing Strings • Compare takes as parameters two strings  Returns negative number if the first string is less than the second, 0 if they are equal, and a positive number if the first string is greater than the second

• Equals takes as parameters two strings  Returns true if two strings are equal

• CompareTo method of a string takes as parameter a string to compare  Returns a negative number if the first string is less than second, 0 if they are equal, and a positive number if the first string is greater than the second Learn More @ http://www.learnnowonline.com Copyright © by Application Developers Training Company


Searching in Strings • StartsWith, EndsWith, Contains and IndexOf all test for the existence of one string within another string  All are methods of the first string and take the second string as the parameter  StartsWith, EndsWith, and Contains return true if the second string is found in the first string  IndexOf returns an integer representing the starting point of the second string

Learn More @ http://www.learnnowonline.com Copyright © by Application Developers Training Company


Modifying Strings • Insert adds a string at a specified position • Remove removes all characters between two positions  Specify the start position to remove all characters from the start to the end of a string  Specify the start and end position to remove all characters from the start through the end position

• Replace replaces part of a string with another string  Replace a character with another character  Replace a string with another string Learn More @ http://www.learnnowonline.com Copyright © by Application Developers Training Company


Modifying Strings • Trim eliminates white space from beginning and end • TrimStart eliminates white space from beginning • TrimEnd eliminates white space from end • PadLeft adds white space or character to beginning • PadRight adds white space or character to end • ToUpper converts string to uppercase • ToLower converts string to lowercase Learn More @ http://www.learnnowonline.com Copyright © by Application Developers Training Company


Extracting Strings • Substring retrieves part of a string  First parameter specifies position representing start of string you want to retrieve  Optional second parameter specifies length of string you want to retrieve

• Split retrieves multiple parts of a string  Takes as parameter an array containing characters used as delimiters, or separators (e.g. , or | or tab)  Returns an array containing parts of the string separated by characters listed in an array Learn More @ http://www.learnnowonline.com Copyright © by Application Developers Training Company


Formatting Strings • Use format specifiers to control how a string is displayed • Formatting numbers  C or c displays as currency: $121,246,424.00  D or d displays a string as a decimal: 121246424  E or e displays in scientific (exponential) form: 1.212464E+008  F or f displays as a fixed-point number: 121246424.00  G or g displays in general format: 121246424  N or n displays as a number: 121,246,424.00  P or p displays as a percent: 12,124,642,400.00 % Learn More @ http://www.learnnowonline.com Copyright © by Application Developers Training Company


Formatting Strings • Formatting dates          

d displays in short date pattern: 1/1/2100 D displays in long date pattern: Friday, January 01, 2100 t displays in short time pattern: 12:00 AM T displays in long time pattern: 12:00:00 AM f displays in full date/time pattern (short time): Friday, January 01, 2100 12:00 AM F displays in full date/time pattern (long time): Friday, January 01, 2100 12:00:00 AM g displays in general date/time pattern (short time): 1/1/2100 12:00 AM G displays in general date/time pattern (long time): 1/1/2100 12:00:00 AM M or m displays in month day pattern: January 01 Y or y displays in month year pattern: January, 2100 Learn More @ http://www.learnnowonline.com Copyright © by Application Developers Training Company


Using the StringBuilder Class • Strings are immutable so each time you use a string operator a new string is created • StringBuilder is more efficient and represents one string in memory • Append adds a string to the end of an existing string • AppendLine adds a string followed by a line break to an existing string • Insert adds a string to an existing string at a specific position • Replace replaces all occurrences of one string with another string • Remove removes a string from an existing string Learn More @ http://www.learnnowonline.com Copyright © by Application Developers Training Company


Working with Dates and Times • Dates and times are represented by DateTime structure • Date and time intervals are represented by TimeSpan structure

Learn More @ http://www.learnnowonline.com Copyright © by Application Developers Training Company


DateTime Structure Properties • Today returns current date • Now returns current date and time • To determine the components of date or time use           

Date Month Day Year DayOfWeek DayOfYear TimeOfDay Hour Minute Second Millisecond

Learn More @ http://www.learnnowonline.com Copyright © by Application Developers Training Company


DateTime Structure Methods • To convert DateTime variable to string use    

ToLongDateString, displays date in long format ToLongTimeString, displays time in long format ToShortDateString, displays date in short format ToShortTimeString, displays time in short format

• To find date in future or past use       

AddDays AddMonths AddYears AddHours AddMinutes AddSeconds AddMilliseconds Learn More @ http://www.learnnowonline.com Copyright © by Application Developers Training Company


Using the TimeSpan Structure • TimeSpan represents the duration of time measured in ticks (100 nanoseconds) • To determine the components of date or time use          

Days - # of whole days in interval Hours - # of whole hours in interval Minutes - # of whole minutes in interval Seconds - # of whole seconds in interval Milliseconds - # of whole milliseconds in interval TotalDays - # of whole and fractional days in interval TotalHours - # of whole and fractional hours in interval TotalMinutes - # of whole and fractional minutes in interval TotalSeconds - # of whole and fractional seconds in interval TotalMilliseconds - # of whole and fractional milliseconds in interval Learn More @ http://www.learnnowonline.com Copyright © by Application Developers Training Company


Learn More! • This is an excerpt from a larger course. Visit www.learnnowonline.com for the full details! • Learn more about .NET on SlideShare: • Getting Started with .NET • .NET Variables and Data Types

Learn More @ http://www.learnnowonline.com Copyright © by Application Developers Training Company


Turn static files into dynamic content formats.

Create a flipbook
Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.