Content by Category
.NET 1.x
.NET 2.0
.NET 3.0
.NET 3.5
.NET 4.0
.NET 4.5
.NET Assemblies
.NET Framework
.NET Getting Started
Accessibility
ADO.NET
Advertorials
Agile Development
AJAX
Amazon Web Services
Analysis Services
Android
Architecture
Arduino
ASP .NET Web API
ASP.NET
ASP.NET MVC
ASP.NET WebForms
Azure
B2B (Business Integration)
BDD
Big Data
Bing
BizTalk
Book Excerpts
Build and Deploy
Business Intelligence
C#
C++
ClickOnce
Cloud Computing
Code Contracts
CODE Framework Info - non Technical
CODE on the Road!
COM+
Community
Conferences
Continuous Integration
Crystal Reports
CSLA.NET
CSS
Data
Debugger
Design Patterns
Development Process
Display Technologies
Distributed Computing
Document Database
DotNetNuke
DSL
Dynamic Languages
Dynamic Programming
Editorials
Enterprise Services ("COM+")
Entity Framework
Events
Expression Blend
F#
Fox to Fox
Frameworks
Functional Programming
Git
Graphics
HTML 5
Internet Explorer 8.0
Interviews
IOS
iPhone
Iron Ruby
Java
Java Script
JavaScript
jQuery
JSON
Lightswitch
LINQ
Linux
LUA
Mac OS X
MDX
Messaging
Metro
Microsoft Application Blocks
Microsoft Business Rules Framework
Microsoft Dynamics
Microsoft Expression
Microsoft Office
Mobile Development
Mobile PC
Mono
MsBuild
MVVM
MySQL
Network
NHibernate
node.js
NOSQL
Nuget
Object Oriented Development
Objective C
Odata
OLAP
Open Source
Opinion
Opinions
Oracle
ORM
Other Languages
Parallel Programming
Patterns
PHP
Podcasts
Post Mortem
PowerPoint
Print/Output
Prism
Product News
Product Reviews
Project Management
Prolog
Python
Q&A
Rails
Rake
Razor
Reporting Services
REST
RIA Services
Ruby
Ruby on Rails
Scheme
Search
Security
Services
SharePoint
SignalR
Silverlight
SOA
Social Networks
Software & Law
Software Business
Source Control
Speech-Enabled Applications
SQL Server
SQL Server 2000
SQL Server 2005
SQL Server 2008
SQL Server 2012
SQL Server CE/AnyWhere/Mobile/Compact
SSIS
Subversion
Sync Framework
Tablet PC
TDD
Team System
Techniques
Testing and Quality Control
TFS
Tips
TypeScript
UI Design
UML
User Groups
VB Script
VB.NET
Version Control
VFP and .NET
VFP and SQL Server
Virtual Earth
Vista
Visual Basic
Visual Basic 6 (and older)
Visual FoxPro
Visual Studio .NET
Visual Studio 11
Visual Studio 2005
Visual Studio 2008
Visual Studio 2010
Visual Studio 2011
Visual Studio 2012
Visual Studio Tools for Office
VSX
WCF
Web Development (general)
Web Services
WebMatrix
WF
Whitepapers
Windows 7
Windows 8
Windows Azure
Windows Live
Windows Phone 7
Windows Phone SDK
Windows Server
Windows Vista
WinForms
WinRT
Workflow
WPF
XAML
Xiine Documentation
XML
XNA
XSLT



LearnNow


XAMALOT
 


SSWUG

Reader rating:
Click here to read 1 comment about this article.
Article source: CoDe (2004 - January/February)


Article Pages: < Previous - 1 2 3  4  5 - Next >


Touring Base Class Library Enhancements (Cont.)

Existing Class Enhancements

Not all the enhancements to the BCL are implemented as entirely new classes. After much feedback from clients, Microsoft has started to insert many highly desired improvements to existing BCL classes.

Simplified File Reading and Writing

Reading and writing to a file is easy to accomplish, but certain file access scenarios are not as simplified as they should be. Prior to Whidbey, file access for reading or writing typically involved instantiating a FileStream object with the desired access mode, reading or writing a byte array to or from the file, and then closing the FileStream object. If the file contents consisted of text, the byte array needed to be converted, adding another step. Alternately, the FileInfo class provided methods to create StreamReader and StreamWriter classes allowing the direct reading or writing of text. Using a FileInfo class and StreamReader or StreamWriter classes added extra steps to the process.

In Whidbey, the File class gains several shared methods designed to simplify file access. Previously, the File class was used indirectly to access files by providing methods to create FileStream, StreamReader, or StreamWriter classes that perform the actual file manipulations. The File class is now enhanced with six new methods that directly manipulate file contents in a single method call.

  • ReadAll
  • ReadAllBytes
  • ReadAllLines
  • WriteAll
  • WriteAllBytes
  • WriteAllLines

All six methods open the file specified by a path parameter, read or write the data involved, and then close the file. The write methods create the file and overwrite the file if it already exists. The ReadAll and WriteAll methods operate on a single string, ReadAllBytes and WriteAllBytes operate on byte arrays, and ReadAllLines and WriteAllLines interact with an array of strings. In the following code snippet, the WriteAllLines method is used to write a string array directly to a file with a single method call:

Sub SimplifiedFileAccess()
    Dim lines(3) As String
    lines(0) = "This"
    lines(1) = "     is"
    lines(2) = "        demo"
    lines(3) = "             file"

    File.WriteAllLines("c:\File.txt", lines)
    Console.Write(File.ReadAll("c:\File.txt"))
End Sub

Improving Graphics Performance

The new BufferedGraphics class provided in the BCL is intended for manual double buffering scenarios where manual coding and control is desired. For general-purpose double buffering needs, the easiest route to leverage double buffering for Windows Forms or custom controls is built into the Control class found in the System.Windows.Forms namespace. In prior versions of the BCL, double buffering was enabled for controls by using the SetStyle method of the Control class to set the style bit to True for three different styles.

  • ControlStyles.AllPaintingInWmPaint
  • ControlStyles.DoubleBuffer
  • ControlStyles.UserPaint

Double buffering is now simplified and optimized. The Control class provides a new DoubleBuffered property and the existing SetStyle method is used to set a new style bit of the Control class called OptimizedDoubleBuffering. Set either of these values to True to implement the same behavior as setting the style bits separately for both AllPaintingInWmPaint and UserPaint to True. The existing DoubleBuffer style bit is now deprecated. The OptimizedDoubleBuffering style behavior redirects all painting operations for the control through a default graphics buffering, greatly reducing flickering without additional code required.

Not Your Grandpa's Console

The BCL class that gains the most new features is the Console class. Prior to the new features, the Console class allowed limited input and output buffer access, and interactions limited to very linear scenarios. Reading and writing task interactions with the screen buffer were dictated by the simple Read, Write, ReadLine, and WriteLine methods.

Enhancements to the Console class enable complete control over positioning of the cursor, foreground and background colors, and the ability to move sections of text, including color scheme, around the screen buffer. Moving text around the screen buffer eliminates the need to manually reconstruct the information in the screen buffer at the new location. The new properties supported by the Console class, shown in Table 3, allow extensive abilities to manipulate the buffer screen characteristics. The possible color choices have been expand to 16 choices.

The Console class gains numerous methods and a new event. You can call the Beep method to issue a system beep. You can call the Clear method to move the cursor to the upper-left corner and clear the screen buffer using the current values of the ForegroundColor and BackgroundColor properties. Call the ResetColor method to revert back to the default console color scheme. You can call the SetBufferSize method to programmatically control the size of the screen buffer and call MoveBufferArea to reallocate characters and their current color scheme from one section of the screen buffer to another without manually reconstructing the screen buffer section affected. You use a combination of the KeyAvailable property and the ReadKey method to grab user input character by character without blocking the executing thread. You handle the CancelKeyPress event to perform complex logic in response to the user typing Ctrl-C.

The enhancements to the Console class provide significantly increased options for developing highly interactive console-based applications that are far more visually appealing than the traditional console-based application. These applications don't have the overhead associated with moving to a full-blown graphical-based user interface provided by Windows Forms-based applications.

An example of many of these features in action together is shown in Figure 4, and the complete code listing is in Listing 1.

Click for a larger version of this image.

Figure 4: Console class enhancements enable significantly more control over the screen buffer than previous versions of the class.

&


Additional Changes You Might Find

It is really hard to speculate on what additional features might surface moving forward in the development of Whidbey. If you take a close look at the documentation from Whidbey, use the Object Browser to analyze the namespaces, and take Whidbey for a test drive, you may start to notice many things mentioned, but not fully implemented. If all the items that are partially referenced in the alpha build are actually completed and included, Whidbey will be a very nice step forward indeed.



Table 3: Numerous new Console class properties provide significantly enhanced features for console-based applications.
Console Property nameDescription
BackgroundColorModifies the background color of the console
BufferHeightGets the current height of the buffer area
BufferWidthGets the current width of the buffer area
CursorLeftGets the current column position of the cursor
CursorSizeModifies the current size of the cursor
CursorTopGets the current row position of the cursor
CursorVisibleModifies whether the cursor is visible
ForegroundColorModifies the foreground color of the console
KeyAvailableIndicates whether a key has been pressed
TitleModifies the title of the console title bar
TreatControlCAsInputModifies whether (CTRL+C) is treated as ordinary user input to be processed by the Console class or handled by the operating system as a program execution interruption. If set to False, the CancelKeyPress event can be used to process (CTRL+C).
WindowHeightGets the current height of the console window area
WindowLeftGets the current leftmost position of the console window area relative to the screen buffer
WindowTopGets the current top position of the console window area relative to the screen buffer
WindowWidthGets the current width of the console window


Listing 1: Sample use of the enhanced Console class
Public Class PaddleBall
    Private xB As Integer = 5
    Private yB As Integer = 3
    Private xBDelta As Integer = 1
    Private yBDelta As Integer = 1
    Dim xP As Integer = 2
    Dim Eraser As ConsoleColor = ConsoleColor.Black
    Dim Paddle As ConsoleColor = ConsoleColor.Green
    Dim Ball As ConsoleColor = ConsoleColor.Yellow
    Dim tBall As New Thread(AddressOf MoveBall)

    Public Sub Start()
        ' Setup visual style of console
        InitializeConsole()

        ' Start ball in motion on secondary thread
        tBall.Priority = ThreadPriority.Lowest
        tBall.Start()

        ' Enable paddle control on primary thread
        EnablePaddle()
    End Sub

    Private Sub InitializeConsole()
        ' Setup basic game graphics
        Console.BackgroundColor = Eraser
        Console.ForegroundColor = ConsoleColor.White
        Console.SetWindowSize(30, 20)
        Console.SetBufferSize(30, 20)
        Console.Title = "Enhanced Console Class"
        Console.Clear()
        Console.SetCursorPosition(0, 0)
        Console.BackgroundColor = ConsoleColor.DarkBlue
        Console.ForegroundColor = ConsoleColor.Yellow
        Console.Write("                              ")
        Console.Write("       Paddle Ball .NET       ")
        Console.Write("                   Score: 000 ")
        Console.BackgroundColor = Eraser
        Console.ForegroundColor = ConsoleColor.DarkRed
        Console.Write("                              ")
        Console.Write("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@")
        Console.Write("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@")
        Console.Write("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@")

        ' Draw Paddle
        Console.SetCursorPosition(2, 18)
        Console.ForegroundColor = Paddle
        Console.Write("======")
        Console.CursorVisible = False
    End Sub

    Private Sub MoveBall()
        Do While yB 19
            SyncLock Me
                ' Erase current Ball
                Console.SetCursorPosition(xB, yB)
                Console.Write(" ")

                xB += xBDelta
                yB += yBDelta

                ' Draw new ball
                Console.BackgroundColor = Ball
                Console.SetCursorPosition(xB, yB)
                Console.Write(" ")
                Console.BackgroundColor = Eraser
            End SyncLock
            If xB = 29 Then xBDelta = -1
            If xB = 0 Then xBDelta = 1
            If yB = 17 And xP <= xB And _
               xB <= xP + 5 Then yBDelta = -1
            If yB = 3 Then yBDelta = 1
            Thread.CurrentThread.Sleep(100)
        Loop
        SyncLock Me
            Console.ForegroundColor = ConsoleColor.Red
            Console.SetCursorPosition(10, 8)
            Console.Write("Game Over!")
        End SyncLock
    End Sub

    Private Sub EnablePaddle()
        Dim key As ConsoleKey
        Dim x2 As Integer

        Do While Not key = ConsoleKey.End
            Select Case key
                Case ConsoleKey.LeftArrow
                    x2 = xP + 5
                    If xP Then xP -= 1
                Case ConsoleKey.RightArrow
                    x2 = xP
                    If xP 23 Then xP += 1
                Case Else : x2 = 0
            End Select
            If (key = ConsoleKey.LeftArrow Or _
                ConsoleKey.RightArrow) And x2 Then
                SyncLock Me
                    Console.SetCursorPosition(x2, 18)
                    Console.Write(" ")
                    Console.SetCursorPosition(xP, 18)
                    Console.ForegroundColor = Paddle
                    Console.Write("======")
                    Console.BackgroundColor = Eraser
                End SyncLock
            End If
            key = Console.ReadKey.Key
        Loop
    End Sub
End Class


Article Pages: < Previous - 1 2 3  4  5 - Next Page: 'Enhancing Network Support' >>

Page 1: Touring Base Class Library Enhancements
Page 2: Generating Hash Values
Page 3: Tracing to the Console
Page 4: Existing Class Enhancements
Page 5: Enhancing Network Support

How would you rate the quality of this article?
1 2 3 4 5
Poor      Outstanding

Tell us why you rated the content this way. (optional)

Average rating:
4.1 out of 5

14 people have rated this article.

Instantly Search Terabytes Of Text
“Lightning Fast”
– Redmond Mag
“Covers all data
sources” – eWeek
25+ fielded & full-text search options
dtSearch’s own document filters highlight hits in popular file types
Web Spider supports static & dynamic data
APIs for .NET, Java, C++, SQL, etc.
Win / Linux (64-bit & 32-bit)
www.dtSearch.com
 

      LearnNow

 

SSWUG