Catch the Phillies Phever World Series 2008 Unique Collectibles and T's

Archive for the 'C# / VS' Category

DBconn config file

Thursday, June 19th, 2008

An application configuration file follows a specific XML schema. The appSettings section is a predefined section of the configuration file designed to make it very easy to retrieve a value based on a given name. This is the easiest way to add application-specific settings into an application configuration file. The appSettings section of the configuration file consists of a series of “add” elements with “key” and “value” attributes. While the appSettings section is predefined, it is not included in a configuration file by default and must be manually added.

A simple example of a configuration file would be the following:

< ?xml version="1.0" encoding="utf-8" ?>

The AppSettings property of the ConfigurationSettings object in the System.Configuration namespace is used to get the settings.

For example, to read either of the settings above,
the following sample code would do the trick:

// Read appSettings string title = ConfigurationSettings.AppSettings[”ApplicationTitle”];

string connectString = ConfigurationSettings.AppSettings[”ConnectionString”];

Now, you could easily set a dynamic title value or read database connection string information from the application configuration file. This gives you the freedom to adjust settings without having to recompile any code. then just pass it into say a SQL connection like so :

SQLConnection cnn = new SQLConnection ( connectString );
// there ya go !

Code Access

Friday, June 13th, 2008

Code Access Security Facts

Code access security restricts the resources a particular piece of code can access, thus protecting the system from untrusted or possibly buggy code. Code access security allows varying degrees of trust to be applied to those code segments.

As with role-based security, code-access security follows two models: imperative and declarative. These models reflect the models of the role-based security, namely, imperative security demands and permissions are made in the code, while declarative demands and permissions are attributes which are tagged onto assemblies, classes and members.

There are a number of classes that you can use in the imperative model, each inherits from System.Security.CodeAccessPermission. To use imperative code-access security, select the class that best fits your needs, or create your own custom permission class by inheriting from System.Security.CodeAccessPermission. Common permissions include:

  • DirectoryServicesPermission to control access to data in Windows Directory Service.
  • FileIOPermission to control access to files.
  • SqlClientPermission to control access to a SQL data source.
  • RegistryPermission to control access to registry variables.

The following example defines an access level (Read permission) and uses the PermitOnly method to check the user’s permissions. If permissions do not match those specified, a SecurityException will be thrown.

public void Process()
{
FileIOPermission fp =
new FileIOPermission(FileIOPermissionAccess.Read,
@"C:\");
try
{
fp.PermitOnly();
// Correct permission process
}
catch (SecurityException ex)
{
// Incorrect permission process
}
}

To used declarative code access security use one of the CodeAccessSecurityAttribute classes to tag an assembly, class or class member. There are a number of attribute classes that derive from System.Security.Permissions.CodeAccessSecurityAttribute. In fact, they basically mirror the CodeAccessSecurity classes.

Any assembly, class, or class member tagged with a CodeAccessSecurityAttribute must have the specified permission(s), otherwise a SecurityException will be thrown.

[FileIOPermissionAttribute(SecurityAction.PermitOnly,
Read=@"C:\")]
public void Process()
{
// process here
}

Role Management

Friday, June 13th, 2008

Role-based Security Facts

The table below describes three role-based security terms you should know.

Security Term Description
Identity Analogous to a Windows user. The identity includes the user name and is used to reference the role and permissions of each user.
Role Analogous to a Windows group. Used to reference the permissions of a group of users.
Principal A Principal object encapsulates a security context, including user name, role, and permissions.

In .NET, role-based security includes the process of checking a user’s authentication information against the roles (or permissions) that the user is assigned. It is up to the programmer to enforce role-based security in the application.

The table below describes the four class and attribute implementations upon which role-based security relies.

Implementation Description
Identity Classes Identity classes inherit from the IIdentity interface and keep track of the username, whether the user is authenticated, and the authentication type used.
Principal Classes Principal classes inherit from the IPrincipal interface. They reference the user Identity and include methods for getting the roles membership for the user. There are two principal classes in the .NET libraries: WindowsPrincipal and GenericPrincipal.
PrincipalPermission Class The PrincipalPermission class allows programmatic security checks to be made. Use methods in this class to identify whether users have the necessary permissions to gain access.
PrincipalPermissionAttribute Use the PrincipalPermissionAttribute to tag assemblies, classes or class members. The user of the assembly, class or member must have the permissions specified in the attribute tag.

Identity and Principal classes represent passive objects; they simply encapsulate user and permission information. PrincipalPermission and the PrincipalPermissionAttribute are active objects; they perform the security demands when appropriate.

The following table lists several methods and properties available through these classes.

Class Members Description
Identity Classes AuthenticationType Property Indicates the type of authentication used (for example: Basic, NTLM, Kerberos, etc.).
IsAuthenticated Property Indicates if the user is authenticated.
Name Property Stores the username
Principal Classes Identity Property References the IIdentity object associated with the IPrincipal object.
IsInRole() Method Returns true if the associated IIdentity object is in the specified role.
PrincipalPermission Class Demand() Method Throws a SecurityException if the current principal does not match the PrincipalPermission instance. Note that this is the method that you use to enforce security using the imperative model.
Intersect() Method Returns a new PrincipalPermission object that is the intersection of the calling object and the object passed in. Calling Demand on intersected PrincipalPermission objects has the effect of requiring the current user to be authenticated by both PrincipalPermission objects.
Union() Method Returns a new PrincipalPermission object that is the union of the calling object and the object passed in. Calling Demand on unioned PrincipalPermission objects has the effect of requiring the current user to be authenticated by either of the PrincipalPermission objects.

The exact mechanisms you use to implement security depends on whether you will be using imperative or declarative security. The following table shows implementation examples of each approach:

Implementation Method Description
Imperative Security The imperative method of implementing security uses the PrincipalPermission class and involves placing the security calls directly in the program code. The following example creates a PrincipalPermission object and demands to know if the DEMO/demo is a member of the User role.

try
{
PrincipalPermission permissions =
new PrincipalPermission("DEMO/demo", "User");
permissions.Demand();
// If the user is a member of the role,
// additional statements will run
}
// If the user is not a member of the role,
// an exception will be thrown
catch(SecurityException ex)
{
// Actions based on invalid security credentials
}

Note that the following using statements are presumed to be included at the top of the file for the example:

using System.Security;
using System.Security.Permissions;
Declarative Declarative security involves placing attributes on the assembly, class or class member you wish to protect. Use the PrincipalPermissionAttribute to tag assemblies, classes or class members. The user of the assembly, class or member must have the permissions specified in the attribute tag.

[PrincipalPermissionAttribute(
SecurityAction.Demand,
Name="DEMO/demo",
Role="User")]
public void SecureProcess()
{
// The code will only be executed if
// the security checks are passed
}

The actual parameter, which you must pass to the attribute constructor, is the SecurityAction you wish the attribute to enforce. SecurityAction.Demand enforces the same level of security as the Demand method of the PrincipalPermission class. The named parameters in the above example set the Name and Role which the permission requires in order to execute.

The following table describes the members of the enumeration.

Member Description
Assert Ensures that the calling code has the correct permissions, but disregards callers higher in the call stack.
Demand Demands that the caller and all previous calling methods have the correct permissions.
Deny Access is denied even if the caller has the correct permissions.
Inheritance
Demand
Ensures that a class derived from the caller has the correct permissions.
LinkDemand Requires that permissions at both the class and member level be met.
PermitOnly Only the resources specified can be accessed if permissions are correct.

Code Security

Friday, June 13th, 2008

Security Facts

When working with application security, it’s important to understand the difference between authentication and authorization:

  • Authentication is the process of ensuring that users are who they say they are. Authentication typically uses a user name and a password.
  • Authorization happens after authentication and identifies the level of access allowed to a given user. For example, authorization might identify specific files to which the user has access.

.NET uses two mechanisms for controlling security:

  • Code access security allows you to specify what resources your code should and should not be able to access and what operations your code can and cannot perform. Code access security in .NET allows different segments of code to be trusted at different degrees, thus minimizing the need for full trust (which is dangerous) of the system.
  • Role-based security allows you to specify what permissions a particular user has, often based on the role (or Windows group) of the user.

    If you get an error like “System.Security.Policy.Exception: Failed to aquire required permissions” you can run the Permissions View Tool (Permview.exe) on the Server to view the permissions required by components you are trying to configure to run…

There are two models of implementing each type of security: declarative and imperative.

  • With declarative security, assemblies, classes, and class members are tagged with security attributes that identify the security rules to apply to the assembly, class, or class member. .NET automatically controls access based on the security attributes.
  • With imperative security, the permissions and demands are placed directly in the code. They are applied at runtime as the code is encountered. The programmer is responsible for identifying when and how to apply security restrictions.

In general, not only the caller must meet the security criteria, but also the entire call stack is also traced (or walked) and each subsequent caller is required to have the appropriate permissions. This prevents untrusted methods from using more trusted objects and methods to access secure resources. This behavior can be overridden

openWYSIWYG

Monday, June 9th, 2008

great text editor controls for users to provide feedback

openWYSIWYG link here 

AutoRun

Saturday, March 22nd, 2008

a buddy of mine at work wanted the script to launch and autorun a target when a peripheral sped up a CD

in short, here’s how :: make a new notpad file; name it autorun.inf

write the next lines of code ::.

[AutoRun]
open=launch.exe

Globalization and Localization Facts

Saturday, March 15th, 2008

If your application will be used in multiple countries or languages, you should consider the following aspects when creating the application:

  • Globalization is the formatting of data based on a locale or region. It only deals with formatting the output of data, it does not change the value of the data. For example, globalization will not convert U.S. dollars to Japanese yen, but globalization will format the output as U.S. dollars or Japanese yen.
  • Localization is the process of adapting an application to a region and includes changing the user interface (such as moving buttons) and providing translated or otherwise different versions of the application. Different versions share the same logic, but have different interfaces.

With both globalization and localization, various elements within the user interface are modified based on the current culture. The culture definition accommodates both language and regional (often country) differences. Culture information is set and modified using the following:

Construct Description
CultureInfo Class The System.Globalization.CultureInfo class is used to hold information about different cultures such as:

  • The name of the culture.
  • The writing system.
  • The calendar used.
  • Other culture specific information such as date and currency formats.

The CultureInfo class requires that a culture code be passed to its constructor on creation.

  • The culture code can be passed as a string or an int.
  • The string for a culture code generally looks like: en-us. The first two characters specify the language and the last two specify the region. In this case the language is English and the region is the United States.
Thread.CurrentCulture Property CurrentCulture is a property of a thread that identifies the cultural settings used for globalization by the thread. The CurrentCulture property returns a CultureInfo object that includes the culture information.You can get this property as shown in the following example:

CultureInfo culture =
System.Threading.Thread.CurrentThread.CurrentCulture;

The CurrentCulture Property also allows setting the CurrentCulture programmatically. For example:

CultureInfo culture = new CultureInfo("en-us");
System.Threading.CurrentThread.CurrentCulture = culture;

The default setting is the user’s Locale set through the Regional Options applet in the Control Panel.

Thread.CurrentUICulture Property CurrentUICulture is a property of a thread that identifies the cultural settings used for localization. You can get and set this property in the same way you get and set the CurrentCulture property.The default value for the CurrentUICulture is the operating system’s UI Language. For multi-language versions, the user UI Language settings are used.

The following table describes how to customize your application for a specific culture.

Action Description
Globalization As you globalize an application, consider cases in your code where data is displayed in given format (such as currency, dates, and decimal numbers). It’s common in a non-globalized application to hard-code the display and formatting of these values. The following example forces the display of the value 5000:

txtNonGlobalized.Text = "$5,000";

To globalize this data, use the ToString method passing the formatting character. The following example displays the value 5000 as currency (the system will format the display based on the current culture).

txtGlobalized.Text = (5000).ToString("C");
Localization Localization involves creating alternate user interface layouts (and text) for different cultures.

  • Localization uses resource files (*.resx) to hold the language, culture, and locale-specific contents.
  • The resource files are used to populate the text properties for the controls on the user interface for a particular language and culture.
  • In addition to storing text, resource files can also store icons and graphics that are specific to different regions or cultures.
  • The correct resources will be loaded at runtime based on the CurrentUICulture.

The following steps outline how to localize a form.

  1. Create the default culture version.
  2. Set the form’s Localize property to true.
  3. Set the form’s Language property to the desired language.
  4. Modify the form for the specified language by changing text and moving, adding, or deleting controls.
  5. Build the application. This will create the corresponding .resx files.

When the application runs, the appropriate resources will be loaded for the CurrentUICulture.

Application ToolTip

Saturday, March 15th, 2008

You’re writing a book reading list application. You’ve already created a main menu and coded event handlers to handle adding and removing book items and changing the book summary font size. Now you want to add tool tips to the book list and text boxes.

Add a ToolTip component to the BooksForm and name it toolTips. Then set the following tooltips:

Control Tooltip
titleTextBox Enter the title of the book
authorTextBox Enter the author of the book
summaryTextBox Enter a summary of the book
booksListBox Click a book to view its details

Run the program to verify your code. You should see the appropriate tool tip when you hover over the book list and edit boxes.

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;

namespace Books
{
///


/// Summary description for Form1.
///

public class BooksForm : System.Windows.Forms.Form
{
private System.Windows.Forms.ListBox booksListBox;
private System.Windows.Forms.Panel bookPanel;
private System.Windows.Forms.Label titleLabel;
private System.Windows.Forms.TextBox titleTextBox;
private System.Windows.Forms.Label authorLabel;
private System.Windows.Forms.TextBox authorTextBox;
private System.Windows.Forms.Label summaryLabel;
private System.Windows.Forms.TextBox summaryTextBox;
private System.Windows.Forms.MainMenu mainMenu;
private System.Windows.Forms.MenuItem fileMenuItem;
private System.Windows.Forms.MenuItem editMenuItem;
private System.Windows.Forms.MenuItem viewMenuItem;
private System.Windows.Forms.MenuItem helpMenuItem;
private System.Windows.Forms.MenuItem aboutMenuItem;
private System.Windows.Forms.MenuItem smallFontMenuItem;
private System.Windows.Forms.MenuItem normalFontMenuItem;
private System.Windows.Forms.MenuItem largeFontMenuItem;
private System.Windows.Forms.MenuItem deleteMenuItem;
private System.Windows.Forms.MenuItem newMenuItem;
private System.Windows.Forms.MenuItem sepMenuItem;
private System.Windows.Forms.MenuItem exitMenuItem;
private System.Windows.Forms.ToolTip toolTips;
///
/// Required designer variable.
///

private System.ComponentModel.Container components = null;

private int lastSelectedIndex = -1;

public BooksForm()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();

//
// TODO: Add any constructor code after InitializeComponent call
//
}

///


/// Clean up any resources being used.
///

protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}

#region Windows Form Designer generated code
///


/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
///

private void InitializeComponent()
{

this.components = new System.ComponentModel.Container();
this.summaryTextBox = new System.Windows.Forms.TextBox();
this.summaryLabel = new System.Windows.Forms.Label();
this.authorTextBox = new System.Windows.Forms.TextBox();
this.authorLabel = new System.Windows.Forms.Label();
this.titleTextBox = new System.Windows.Forms.TextBox();
this.titleLabel = new System.Windows.Forms.Label();
this.bookPanel = new System.Windows.Forms.Panel();
this.booksListBox = new System.Windows.Forms.ListBox();
this.helpMenuItem = new System.Windows.Forms.MenuItem();
this.exitMenuItem = new System.Windows.Forms.MenuItem();
this.viewMenuItem = new System.Windows.Forms.MenuItem();
this.smallFontMenuItem = new System.Windows.Forms.MenuItem();
this.sepMenuItem = new System.Windows.Forms.MenuItem();
this.aboutMenuItem = new System.Windows.Forms.MenuItem();
this.normalFontMenuItem = new System.Windows.Forms.MenuItem();
this.deleteMenuItem = new System.Windows.Forms.MenuItem();
this.newMenuItem = new System.Windows.Forms.MenuItem();
this.fileMenuItem = new System.Windows.Forms.MenuItem();
this.toolTips = new System.Windows.Forms.ToolTip(this.components);
this.editMenuItem = new System.Windows.Forms.MenuItem();
this.largeFontMenuItem = new System.Windows.Forms.MenuItem();
this.mainMenu = new System.Windows.Forms.MainMenu();
this.bookPanel.SuspendLayout();
this.SuspendLayout();
//
// summaryTextBox
//
this.summaryTextBox.Text = “”;
this.summaryTextBox.Font = new System.Drawing.Font(”Microsoft Sans Serif”, 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
this.summaryTextBox.Multiline = true;
this.summaryTextBox.Size = new System.Drawing.Size(312, 278);
this.toolTips.SetToolTip(this.summaryTextBox, “Enter a summary of the book”);
this.summaryTextBox.Location = new System.Drawing.Point(16, 128);
this.summaryTextBox.TabIndex = 5;
this.summaryTextBox.Anchor = ((System.Windows.Forms.AnchorStyles)(System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right));
this.summaryTextBox.Name = “summaryTextBox”;
//
// summaryLabel
//
this.summaryLabel.Location = new System.Drawing.Point(16, 112);
this.summaryLabel.Size = new System.Drawing.Size(100, 16);
this.summaryLabel.TabIndex = 4;
this.summaryLabel.Name = “summaryLabel”;
this.summaryLabel.Text = “Summary”;
//
// authorTextBox
//
this.authorTextBox.Text = “”;
this.authorTextBox.Size = new System.Drawing.Size(312, 20);
this.toolTips.SetToolTip(this.authorTextBox, “Enter the author of the book”);
this.authorTextBox.Location = new System.Drawing.Point(16, 80);
this.authorTextBox.TabIndex = 3;
this.authorTextBox.Anchor = ((System.Windows.Forms.AnchorStyles)(System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right));
this.authorTextBox.Name = “authorTextBox”;
//
// authorLabel
//
this.authorLabel.Location = new System.Drawing.Point(16, 64);
this.authorLabel.Size = new System.Drawing.Size(100, 16);
this.authorLabel.TabIndex = 2;
this.authorLabel.Name = “authorLabel”;
this.authorLabel.Text = “Author”;
//
// titleTextBox
//
this.titleTextBox.Text = “”;
this.titleTextBox.Size = new System.Drawing.Size(312, 20);
this.toolTips.SetToolTip(this.titleTextBox, “Enter the title of the book”);
this.titleTextBox.Location = new System.Drawing.Point(16, 32);
this.titleTextBox.TabIndex = 1;
this.titleTextBox.Anchor = ((System.Windows.Forms.AnchorStyles)(System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right));
this.titleTextBox.Name = “titleTextBox”;
//
// titleLabel
//
this.titleLabel.Location = new System.Drawing.Point(16, 16);
this.titleLabel.Size = new System.Drawing.Size(100, 16);
this.titleLabel.TabIndex = 0;
this.titleLabel.Name = “titleLabel”;
this.titleLabel.Text = “Title”;
//
// bookPanel
//
this.bookPanel.Dock = System.Windows.Forms.DockStyle.Fill;
this.bookPanel.TabIndex = 2;
this.bookPanel.Controls.Add(this.summaryTextBox);
this.bookPanel.Controls.Add(this.summaryLabel);
this.bookPanel.Controls.Add(this.authorTextBox);
this.bookPanel.Controls.Add(this.authorLabel);
this.bookPanel.Controls.Add(this.titleTextBox);
this.bookPanel.Controls.Add(this.titleLabel);
this.bookPanel.Name = “bookPanel”;
this.bookPanel.Size = new System.Drawing.Size(344, 422);
this.bookPanel.Location = new System.Drawing.Point(200, 0);
//
// booksListBox
//
this.booksListBox.Name = “booksListBox”;
this.toolTips.SetToolTip(this.booksListBox, “Click a book to view its details”);
this.booksListBox.Location = new System.Drawing.Point(0, 0);
this.booksListBox.TabIndex = 1;
this.booksListBox.Dock = System.Windows.Forms.DockStyle.Left;
this.booksListBox.Size = new System.Drawing.Size(200, 422);
this.booksListBox.IntegralHeight = false;
this.booksListBox.SelectedIndexChanged += new System.EventHandler(booksListBox_SelectedIndexChanged);
//
// helpMenuItem
//
this.helpMenuItem.MenuItems.Add(this.aboutMenuItem);
this.helpMenuItem.Index = 3;
this.helpMenuItem.Text = “&Help”;
//
// exitMenuItem
//
this.exitMenuItem.Index = 2;
this.exitMenuItem.Text = “E&xit”;
this.exitMenuItem.Click += new System.EventHandler(exitMenuItem_Click);
//
// viewMenuItem
//
this.viewMenuItem.MenuItems.Add(this.smallFontMenuItem);
this.viewMenuItem.MenuItems.Add(this.normalFontMenuItem);
this.viewMenuItem.MenuItems.Add(this.largeFontMenuItem);
this.viewMenuItem.Index = 2;
this.viewMenuItem.Text = “&View”;
//
// smallFontMenuItem
//
this.smallFontMenuItem.RadioCheck = true;
this.smallFontMenuItem.Index = 0;
this.smallFontMenuItem.Text = “Small Font”;
this.smallFontMenuItem.Click += new System.EventHandler(smallFontMenuItem_Click);
//
// sepMenuItem
//
this.sepMenuItem.Index = 1;
this.sepMenuItem.Text = “-”;
//
// aboutMenuItem
//
this.aboutMenuItem.Index = 0;
this.aboutMenuItem.Text = “&About”;
//
// normalFontMenuItem
//
this.normalFontMenuItem.Checked = true;
this.normalFontMenuItem.RadioCheck = true;
this.normalFontMenuItem.Index = 1;
this.normalFontMenuItem.Text = “Normal Font”;
this.normalFontMenuItem.Click += new System.EventHandler(normalFontMenuItem_Click);
//
// deleteMenuItem
//
this.deleteMenuItem.Index = 0;
this.deleteMenuItem.Text = “&Delete”;
this.deleteMenuItem.Click += new System.EventHandler(deleteMenuItem_Click);
//
// newMenuItem
//
this.newMenuItem.Index = 0;
this.newMenuItem.Text = “&New”;
this.newMenuItem.Click += new System.EventHandler(newMenuItem_Click);
//
// fileMenuItem
//
this.fileMenuItem.MenuItems.Add(this.newMenuItem);
this.fileMenuItem.MenuItems.Add(this.sepMenuItem);
this.fileMenuItem.MenuItems.Add(this.exitMenuItem);
this.fileMenuItem.Index = 0;
this.fileMenuItem.Text = “&File”;
//
// editMenuItem
//
this.editMenuItem.MenuItems.Add(this.deleteMenuItem);
this.editMenuItem.Index = 1;
this.editMenuItem.Text = “&Edit”;
//
// largeFontMenuItem
//
this.largeFontMenuItem.RadioCheck = true;
this.largeFontMenuItem.Index = 2;
this.largeFontMenuItem.Text = “Large Font”;
this.largeFontMenuItem.Click += new System.EventHandler(largeFontMenuItem_Click);
//
// mainMenu
//
this.mainMenu.MenuItems.Add(this.fileMenuItem);
this.mainMenu.MenuItems.Add(this.editMenuItem);
this.mainMenu.MenuItems.Add(this.viewMenuItem);
this.mainMenu.MenuItems.Add(this.helpMenuItem);
//
// BooksForm
//
this.Controls.Add(this.bookPanel);
this.Controls.Add(this.booksListBox);
this.ClientSize = new System.Drawing.Size(544, 422);
this.Name = “BooksForm”;
this.Menu = this.mainMenu;
this.Text = “Book Reading List”;
this.Load += new System.EventHandler(booksForm_Load);
this.bookPanel.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion

///


/// The main entry point for the application.
///

[STAThread]
static void Main()
{
Application.Run(new BooksForm());
}

private void booksForm_Load(object sender, System.EventArgs e)
{
booksListBox.Items.AddRange(new object[] {
new Book(”Babe: The Gallant Pig”, “Dick King-Smith”, “How an engaging pig with impeccable manners avoids the fate of most porkers by becoming a champion sheep-herder is the remarkably believable premise of an outstanding animal fantasy. Written with a genuine feeling for English farm life, the book creates a cast of memorable characters captured as well in Mary Rayner?s black-and-white drawings.”),
new Book(”The Best Christmas Pageant Ever”, “Barbara Robinson”, “When the Herdmans ? ?the worst kids in the world? ? decide that they want to be part of the traditional Christmas pageant, the townsfolk anticipate a disaster. Surprisingly, they discover that this unusual interpretation adds new meaning to the Christmas story in the conclusion of a wildly funny, fast-moving book.”),
new Book(”The Book of Three”, “Lloyd Alexander”, “The first of five books in The Prydain Chronicles introduces the principal characters who appear in the series including Assistant Pig Keeper Taran, the Princess Ellowny, Prince Gwydion, the faithful complaining Gurgi, and the vainglorious harpist Fflewddur Fflam. Indirectly inspired by Welsh mythology, flavored with humor, the tales depict the development of Taran into a heroic figure as he and his companions battle the forces of evil in a series of impelling adventures.”),
new Book(”The Borrowers”, “Mary Norton”, “A fully realized miniature world is the setting for an unusual fantasy based on the premise that a diminutive race of people lives by ?borrowing? the necessities of life from human beings. Their ingenuity in adapting items like postage stamps or pins for their purposes is as intriguing as it is inventive. First in a series.”),
new Book(”Bridge to Terabithia”, “Katherine Paterson”, “Ten-year-old Jess Arons never envisioned the possibilities which the world might hold for him until Leslie Burke moved to his rural community in Virginia. First, she proved superior as a runner; then she introduced him to the joys of literature and the imagination as they worked together to create their own special kingdom — Terabithia. Although a tragic accident ends their idyll, Leslie’s legacy endures in the hopeful ending of a beautifully crafted book.”),
new Book(”Charlotte’s Web”, “E. B. White”, “The nature of friendship, the power of advertising, and the foibles of society are deftly explored in an unforgettable story featuring a runt pig who is saved from becoming pork chops by the intervention of a remarkable spider. Expressive black-and-white illustrations, executed in harmony with the text, add further distinction.”),
new Book(”Harriet the Spy”, “Louise Fitzhugh”, “Determined to be a writer, Manhattan-raised sixth-grader Harriet M. Welsch records her gimlet-eyed observations of her world in a notebook which when discovered leads her into an unusual dilemma. With the help of Ole Golly, her eccentric but perceptive ex-nanny, she is able to resolve the situation to her advantage. A milestone in contemporary realism for children.”),
new Book(”The Hobbit; or, There and Back Again”, “J. R. R. Tolkien”, “Bilbo Baggins, a home-loving mild little creature, finds himself enticed by the wizard Gandalf into a series of hazardous adventures involving goblins, Wargs, trolls, and a dragon named Smaug. A hero in spite of himself, Bilbo shows that ordinary individuals are sometimes capable of extraordinary feats. The blending of humor and suspense with a cast of distinctive characters make this unforgettable.”),
new Book(”Humbug Mountain”, “Sid Fleischman”, “A humorous frontier story written in an engaging tall-tale style chronicles the adventures of an itinerant newspaperman and his family as they journey westward in search of a missing relative. Dastardly villains, the unpredictable Missouri River, and an unexpected gold rush guarantee suspense as incidents follow one another at a frenzied pace.”),
new Book(”The Hundred Dresses”, “Eleanor Estes”, “When shabby Wanda Petronski claims that she has one hundred dresses at home, she becomes a target for teasing by classmates who scorn her because she is different. Despite their cruelty, it is Wanda who triumphs and is remembered for her sterling character.”),
new Book(”The Incredible Journey”, “Sheila Burnford”, “Seeking their family, two dogs and a cat traverse over two hundred miles of Canadian wilderness in a breathtaking saga of endurance that creates suspense without sentimentality.”),
new Book(”Island of the Blue Dolphins”, “Scott O’Dell”, “When her tribe leaves their island home, a young Indian girl remains behind with her brother. After his death, she struggles alone to stay alive until rescuers arrive eighteen years later. Based on a true story, this unforgettable first person narrative is one of the great survival stories of the twentieth century.”),
new Book(”Johnny Tremain”, “Esther Forbes”, “When a jealous fellow apprentice precipitates the accident which maims his hand, a bright, observant teenager, unable to continue his training as a silversmith, becomes embroiled in events leading to the opening battle of the American Revolution.”),
new Book(”The Lion, the Witch and the Wardrobe”, “C. S. Lewis”, “Four siblings, evacuees from London during World War II, discover the magic land of Narnia behind a wardrobe in the country home where they are staying with an elderly professor. Drawn into the story of a kingdom under the spell of a white witch, they join forces with the lion Aslan to defeat her in a classic confrontation between good and evil. Perhaps the most familiar of a series which concludes with The Last Battle, 1956.”),
new Book(”Little House in the Big Woods”, “Laura Ingalls Wilder”, “Family solidarity is the memorable element in a story of pioneer life based on the author’s recollections of her own childhood. Details of daily living, the conquest of hardships through faith and determination, and above all the sense of security created by loving parents have endeared the Ingalls family to countless readers. First in a series.”),
new Book(”Many Moons”, “By James Thurber”, “When cosseted Princess Leonore insists that she must have the moon in order to recover from the illness that has incapacitated her, she plunges the court into a frenetic search for a solution. After all the great minds have failed, the court jester triumphs in a logical conclusion to a sparkling spoof of the conventional fairy tale by one of America’s foremost humorists.”),
new Book(”Mary Poppins”, “P. L. Travers”, “The storytelling tone immediately draws readers into events at Number Seventeen Cherry Tree Lane when that impeccable nursemaid Mary Poppins arrives on the East Wind and transforms the lives of her young charges. The episodic structure makes the book suited for reading aloud; the combination of Mary Poppins’s acerbic personality and her magical powers guarantees adventures whether on a trip to the zoo or having afternoon tea. First of a series.”)
});
}

private void booksListBox_SelectedIndexChanged(object sender, System.EventArgs e)
{
Book book;
// Update the current item (if there is one)
if ( lastSelectedIndex >= 0 )
{
book = (Book)booksListBox.Items[lastSelectedIndex];
book.Title = titleTextBox.Text;
book.Author = authorTextBox.Text;
book.Summary = summaryTextBox.Text;
booksListBox.Items[lastSelectedIndex] = book; // Refresh the item in list
}

// Set the new current item
lastSelectedIndex = booksListBox.SelectedIndex;

// Initialize the edit fields
if ( lastSelectedIndex >= 0 )
{
book = (Book)booksListBox.Items[lastSelectedIndex];
titleTextBox.Text = book.Title;
authorTextBox.Text = book.Author;
summaryTextBox.Text = book.Summary;
}
else
{
titleTextBox.Text = “”;
authorTextBox.Text = “”;
summaryTextBox.Text = “”;
}
}

private void exitMenuItem_Click(object sender, System.EventArgs e)
{
Close();
}

private void newMenuItem_Click(object sender, System.EventArgs e)
{
// Add new book to list
int index = booksListBox.Items.Add(new Book(”untitled”, “”, “”));
booksListBox.SelectedIndex = index;
titleTextBox.Focus();
}

private void deleteMenuItem_Click(object sender, System.EventArgs e)
{
// Delete current book from list
int index = booksListBox.SelectedIndex;
if ( index >= 0 ) booksListBox.Items.RemoveAt(index);
}

private void smallFontMenuItem_Click(object sender, System.EventArgs e)
{
smallFontMenuItem.Checked = true;
normalFontMenuItem.Checked = false;
largeFontMenuItem.Checked = false;
// set font small
summaryTextBox.Font = new Font(”Microsoft Sans Serif”, 8) ;
}

private void normalFontMenuItem_Click(object sender, System.EventArgs e)
{
smallFontMenuItem.Checked = false;
normalFontMenuItem.Checked = true;
largeFontMenuItem.Checked = false;
// set font normal
summaryTextBox.Font = new Font(”Microsoft Sans Serif”, 12);
}

private void largeFontMenuItem_Click(object sender, System.EventArgs e)
{
smallFontMenuItem.Checked = false;
normalFontMenuItem.Checked = false;
largeFontMenuItem.Checked = true;
// set font large
summaryTextBox.Font = new Font(”Microsoft Sans Serif”, 16);
}
}
}

Configure a Web Service Client

Saturday, March 15th, 2008

You are creating a client application that will use a Web service to perform basic math functions. The BasicMathService Web Service is in the BasicMath namespace and has the following two methods:

  • Add accepts two integer values and returns the sum as a long.
  • Subtract accepts two integer values and returns the difference as a long.

You already completed the following tasks:

  • Started the project.
  • Created the user interface with TextBoxes for entering numbers, Labels for holding the return value, and Buttons for calling the methods.
  • Added a reference to the Web Service.

In form AppMath, add Click event handlers for the Add and Subtract buttons to do the following:

  • Call the corresponding method, passing the values entered in the TextBoxes.
  • Place the return value in the corresponding label (lblAddResult or lblSubtractResult).
  • Handle any errors if the values entered in the TextBoxes are not valid integers.

static void Main()
{
Application.Run(new AppMath());
}
#region Answer
// Add button handler
private void btnAdd_Click(object sender, System.EventArgs e)
{
try
{
// Call the Add method and return the result
BasicMath.BasicMathService basicMath = new BasicMath.BasicMathService();
lblAddResult.Text = basicMath.Add(Convert.ToInt32(tbxAddNumber1.Text), Convert.ToInt32(tbxAddNumber2.Text)).ToString();
}
// Handle errors
catch
{
lblAddResult.Text = “Invalid input values”;
}
}

// Subtract button handler
private void btnSubtract_Click(object sender, System.EventArgs e)
{
try
{
// Call the Subtract method and return the result
BasicMath.BasicMathService basicMath = new BasicMath.BasicMathService();
lblSubtractResult.Text = basicMath.Subtract(Convert.ToInt32(tbxSubtractNumber1.Text), Convert.ToInt32(tbxSubtractNumber2.Text)).ToString();
}
// Handle errors
catch
{
lblAddResult.Text = “Invalid input values”;
}
}
#endregion
}
}

Open ID

Friday, February 22nd, 2008

http://openid.net/

this may be an answer for Single Sign On more many situations…

COM Facts

Saturday, February 9th, 2008

Prior to .NET, Windows development was done in an unmanaged environment using COM technologies or the Windows API. COM focused on creating components called COM components. For example, Microsoft Word is an application, but also a COM component. This means that other applications can access the Microsoft Word interface using COM. COM components allow some level of language independence. For example, a COM component written in C++ can be used in Visual Basic.

COM and .NET may have many similarities, but they also have many differences. The following table contrasts COM and .NET.

COM .NET
Clients of COM objects must manage the lifetime of those objects. In .NET, the Common Language Runtime (CLR) manages the lifetime of objects in its environment.
Clients of COM objects discover whether a service is available by requesting an interface that provides that service and by getting back a pointer to that interface. Clients of .NET objects can obtain a description of an object’s functionality using reflection. This refers to the fact that a .NET assembly is self-describing.
COM (and any unmanaged program) relies on objects remaining stationary in memory, otherwise, any pointer in that code is invalidated. .NET objects reside in memory managed by the CLR execution environment. The execution environment can move objects around in memory for performance reasons and update all references to the objects it moves.

.NET provides a way to interact with COM components.

  • COM interop requires the existence of a Primary Interop Assembly.
  • The Primary Interop Assembly typically contains no code, just MetaData that describes existing COM types.
  • Generally, the Primary Interop Assembly is provided by the vendor of the COM component.
  • Visual Studio .NET will generate a Primary Interop Assembly when a reference to a COM component is added if a Primary Interop Assembly has not already been created.
  • Primary Interop Assemblies can also be created using Tlbimp.exe.
  • In order to allow managed .NET components to communicate with unmanaged COM components .NET will create a Runtime Callable Wrapper (RCW).
  • The RCW is a .NET class that acts as a proxy to the COM object and handles the complexities of COM interop.
  • The .NET client calls methods from the RCW in order to interact with the COM component.

The following diagram shows how COM and .NET interact.

XML Basics

Saturday, February 9th, 2008

XML (Extensible Markup Language) is the industry standard for the interchange of data. Be aware of the following about XML:

  • XML is a universal language for the representation of data.
  • XML facilitates sharing data between computers across a network, software applications, databases, etc.
  • XML is plain text, easy to read, create, and parse.
  • XML data is stored as Unicode UTF-8.
  • XML is an open standard that anyone can use.
  • XML is not a data presentation language like HTML. It only describes the data, not the layout or format of the data.

XML is a self-describing tagged markup language and a subset of SGML. The following table describes the components of XML.

Component Description
XML Declaration The XML declaration is typically the first line in an XML document.


  • The declaration is optional, but when it appears, it must be the first line in the document.
  • It begins with .
  • It includes a version number (currently 1.0) and, optionally, an encoding scheme. Unicode UTF-8 encoding is usually used.
Elements XML elements are tagged sections of data.


Some Data;
  • Tags look like HTML tags except each opening tag is required to have a closing tag or be closed explicitly.
  • Elements may have any name with the only restriction that the closing tag has the same name.
  • Tags surround the data and, optionally, other tags.
  • The first element in the file is called the root element.
  • Closing tags contain the tag name preceded by a forward slash /.
  • A self-closing tag ends with /> and cannot have a separate closing tag. In the example to the right, is a self-closing tag. Note that self-closing tags cannot contain data.
  • Tag names do not have to be unique in a given file.
Attributes Attributes reside inside a tag and are used to describe the data.

Some Data;
  • Attributes can hold any value but should only be used to describe the data (they should not contain the data directly.)
  • Attributes are inside a tag after the tag name.
  • An attribute consists of the attribute name followed by the attribute information.
Data Data is stored between element opening and closing tags. It is in plain text, usually UTF-8 Unicode.
Some Data;
Comments Comments are elements that are not read as data or otherwise displayed.

To be valid, XML must be well-formed; that is it must adhere to the following rules:

  • The document must have exactly one root element.
  • Elements must be open and closed in the same context. In other words, elements must be nested without overlapping opening and closing tags.
  • Each element must have an opening tag and a closing tag or else be self-closing.
  • Data must appear inside elements.

XML allows for a description of the XML document itself to be created called a schema. A schema describes a contract that both the transmitter and the receiver of the XML document agree to follow. While the XML document holds the data, the schema defines the structure of that data. It is the schema that allows both parties to understand fully what the tags and attributes mean and defines the context that the data structure is allowed within the XML document. XML schemas are used to create thousands of XML-based languages in use today. Some of these languages include SOAP, WSDL, and many other open source and proprietary languages.