Thursday 7 February 2013

Creating and Configuring FTP Sites in IIS


File Transfer Protocol (FTP) is a standard protocol for moving files from one computer to another across the Internet. The files are stored on a server computer, which runs FTP server software. Remote computers can then connect using FTP and read files from the server or copy files to the server. An FTP server is similar to an HTTP server (that is, a Web server) in that you can communicate with it using an Internet protocol. However, an FTP server does not run Web pages; it only sends and receives files from remote computers.

You can configure Internet Information Services (IIS) to function as an FTP server. This allows other computers to connect to the server and copy files to and from the server. For example, you might configure IIS to act as an FTP server if you are hosting Web sites on your computer and you want to allow remote users to connect to your computer and copy their files to the server.


Typically, FTP credentials are passed as clear text and not encrypted for transmission. It is recommended that you use FTP with Anonymous or Basic authentication. For more information, see the topics "Securing FTP Sites" and "Authentication Methods Supported in IIS 6.0" in the IIS Technical Reference.

IIS as an FTP Server

In addition to acting as a Web server, IIS can act as an FTP server. The FTP service is not installed by default on IIS. Therefore, to use IIS as an FTP server, you must install the FTP service. For more information about installing and configuring IIS as an FTP server, see the Help documentation that is included with IIS, or see the section "Configuring FTP Sites" in the IIS Technical Reference.

Note

You will need your Windows CD.
To set up an FTP server using IIS

    Click the Start button, click Control Panel, and then click Add or Remove Programs.

    Click Add/Remove Windows Components.

    In the Windows Components Wizard dialog box, if you are running at least Windows Server 2003, select Application Server, and then click Details.

    Select Internet Information Services (IIS) and then click Details.

    In the Internet Information Services (IIS) dialog box, select the File Transfer Protocol (FTP) Service check box and click OK.

    In the Windows Components Wizard dialog box, click Next. If prompted, insert your Windows CD.

    When the installation process is finished, you can use the FTP service with IIS.

Creating Folders

After setting up an FTP server, you need to create a folder structure for the server. By default, the FTP server will have a root folder with the following path: C:\inetpub\ftproot.

The FTP root folder acts as the root for your FTP server in the same way that C:\inetpub\wwwroot is the root for your Web server.

You must create the physical folders where the files will reside. This can either be a subfolder of the FTP root or another folder elsewhere on the computer. Then, you create a virtual root, or alias, that the FTP server will use to point to the physical directory in which files will reside.
To configure an FTP folder and virtual root

    Create a new folder to hold files. You can name the folder anything you like. For example, name the new folder ExampleFtpFiles, so that the path of the folder is C:\inetpub\ftproot\ExampleFtpFiles.

    In Windows, from the Administrative Tools menu, select Internet Information Services.
    NoteNote

    In Windows XP, you can also right-click My Computer in the Start menu or on the desktop, and then click Manage. In the Computer Management dialog box, open the Services and Applications node.

    Open the node for your computer, and then open the FTP Sites node.

    Right-click the Default FTP Site node, click New, and then click Virtual Directory.

    In the Virtual Directory Creation Wizard, specify an alias (or name) that users can use to get to the FTP folder that you created in step 1. The name can be anything you like. It is often least confusing to use the directory name as the alias name, so that the virtual directory might be called ExampleFtpFiles.

    For the path, type or browse to the path of the directory from step 1, for example Inetpub\ftproot\ExampleFtpFiles.

    For Access Permissions, specify Read, and then click Next to finish with the wizard.
    NoteNote

    Do not enable Write permissions unless you understand how to secure your IIS FTP server. For more information, see the topic titled "Securing FTP Sites" in the IIS Technical Reference.

Configuring Permissions

You must also grant permissions to users so that they will be able to read and write to the folder.
To establish permissions for the FTP folder

    In Windows, from the Administrative Tools menu, choose Internet Information Services.
    NoteNote

    In Windows XP, you can also right-click My Computer in the Start menu or on the desktop and then select Manage. In the Computer Management dialog box, open the Services and Applications node.

    Open the node for your computer, open the FTP Sites node, and then open the Default FTP Site node.

    Right-click the virtual directory node for the FTP folder that you want (for instance ExampleFtpFiles) and click Permissions.

    On the Security tab, select or add your user account and assign Modify permissions.

    This sets NTFS permissions. To specify IP restrictions, right-click the folder name, click Properties, and add restrictions on the Directory Security tab. For more information, see the topics "Access Control in IIS 6.0" in the IIS Technical Reference.

    Close the Properties dialog box.

Creating a Web Server Virtual Directory

You typically create a virtual directory for the Web server that maps to the FTP site so that the Web server can access the files in the FTP root. The Web virtual directory name can be the same as the FTP virtual directory name, but this is not required.
To create a Web server virtual directory

    In the Internet Information Services dialog box, open the Web Sites node.

    Right-click the Default Web Site node, click New, and then click Virtual Directory.

    In the wizard, specify an alias that users will use with http:// protocol to access the files in the FTP folder. This can be the same as the FTP alias, for instance ExampleFtpFiles.

    For the directory path, type or browse to the path of the FTP directory, for example C:\inetpub\ftproot\ExampleFtpFiles.

    For access permissions, select Read and Run scripts.

    Click Finish to create the virtual directory and close the wizard

Wednesday 6 February 2013

Mocking Frameworks for .NET



The four major competitors in the free/open source .NET mocking framework arena are microsoft .netNMock/NMock2, NMock3, Rhino Mocks and MOQ. NMock and NMock2 were actually built by different teams, but they kept the same design philosophy and are backwards compatible so they can be used almost interchangeably. If you're familiar with NMock/NMock2, you'll see that NMock3 is from the same gene pool, but it starts fresh and has somewhat different syntax from its siblings. All of the major mocking libraries are mature products with a decent-sized user base, so it's not tough to find good examples and help for all of them but NMock3.

Like many other .NET developers, I started using NMock, and then "upgraded' to nMock2, but both use "magic strings" which can't take advantage of Intellisense, and make tests brittle because they're not easily amenable to refactoring without the use of additional tools like ReSharper to replace name-similar text in strings. On the plus side, NMock doesn't rely on the explicit record/replay statements as Rhino Mocks does. The NMock2 codebase hasn't been updated since late in 2009, and should not be expected to see continued development.

On the plus side, Rhino Mocks has a syntax that supports code refactoring and compile-time checking. Unfortunately, I don't find the syntax to be particularly intuitive, and the variety of ways to construct and condition mocks can lead to some confusion when different people are writing tests. There is also the annoying need to write explicit record and replay statements. Another problem with Rhino Mocks is that the project appears to be running out of steam. Aside from a few bug-fix patches, not much has happened since early in 2009.

MOQ is one of the new kids, with an annoying name that needs to be spelled out so that people know what you're talking about. The latest release became available in April of 2011, and MOQ has active developers and community. It's different from the first two in several ways. When using NMock and Rhino you create mock objects of a specific type. When using MOQ you create mocks that contain an objects of a specific type, and that wrapper around the mock objects lends itself to simpler syntax in your tests. MOQ requires .Net 3.5 or greater due to its use of lambdas, so if you haven't learned to use lambda expressions, now is the time. I haven't used it extensively, but so far I like everything about MOQ... except for the name.

NMock3 is the other new kid, and the one who seems less well known. Maybe it isn't on the radar for most folks because NMock/NMock2 seem behind the times, and that may have kept expectations low. Versions of NMock3 are available for .NET 3.5 and 4.0, and the latest RTM became available in January of 2011 with a beta release in July of 2011. Like MOQ, you create mocks that contain objects of a specific type, and that wrapper around the mock objects leverages lambda expressions, so NMock/NMock2 users are in for some culture shock. Since the NMock3 examples are a little thin in the wild I've include sample code below. Note that in conditioning your mocks, the parameters in the lambda expressions are just placeholders, while the "real" parameters are specified in the "With" method.
using NUnit.Framework;
using NMock; /* NMock3 */

namespace Foo.Test
{
    [TestFixture]

    public class FundsTransferPresenterTest
    {
        private MockFactory _mocks;
        private Mock<IFundsTransferView> _viewMock;
        private Mock<IAccountService> _serviceMock;
        private FundsTransferPresenter _presenter;

        [SetUp]
        public void SetUp()
        {
            _mocks = new MockFactory();
            _viewMock = _mocks.CreateMock<IFundsTransferView>();
            _serviceMock = _mocks.CreateMock<IAccountService>();
            _presenter = new FundsTransferPresenter(_viewMock.MockObject, _serviceMock.MockObject);
        }

        [Test]
        public void CanQueryViewUseAccountServiceToFundsTransfer()
        {
            _viewMock.Expects.One.Method(v => v.GetSourceAccount()).WillReturn("1234");
            _viewMock.Expects.One.GetProperty(v => v.TargetAccount).WillReturn("9876");
            _viewMock.Expects.One.GetProperty(v => v.TransferAmount).WillReturn(200.00m);
            _serviceMock.Expects.Exactly(1).Method(s => s.TransferFunds(null, null, 0m)).With("1234", "9876", 200.00m);
            _presenter.Transfer_Clicked();
            _mocks.VerifyAllExpectationsHaveBeenMet();
        }
    }
}

/*******************************   Fragment of System Under Test (SUT)   *******************************/

    public interface IFundsTransferView
    {
        string GetSourceAccount();
        string TargetAccount { get; }
        decimal TransferAmount { get; }
    }

    public interface IAccountService
    {
        void TransferFunds(string source, string target, decimal amount);
    }

    public class FundsTransferPresenter
    {
        private IFundsTransferView _view;
        private IAccountService _service;

        public FundsTransferPresenter(IFundsTransferView view, IAccountService service)
        {
            _service = service;
            _view = view;
        }

        public void Transfer_Clicked()
        {
            _service.TransferFunds(_view.GetSourceAccount(), _view.TargetAccount, _view.TransferAmount);
        }
    }

Source: Robert Zormeir

Tuesday 5 February 2013

Diagramming for Java 4.0 Released

Diagramming for Java 4.0 Released

MindFusion has released a new version of its Diagramming component for Java with various new features.

Node Effects

Diagramming for Java adds support for two visual effects - the GlassEffect and AeroEffect, which can be applied to nodes. Effects can be added, removed or modified at any time and this will immediately reflect on the diagram. You can apply more than one effect of the same type.

Styles & Themes

The Style is a set of properties, which can be applied to a given diagram item or to all items of a specific type. A Theme is a collection of styles. Each style in the theme is associated with a specific type of diagram items and affects all items of this type. Themes can be loaded and saved from / to XML files. Use the Theme Editor tool to create your own themes.

Diagram documents and tabbed views

The new DiagramDocument class represents a collection of pages (sheets). Each sheet is an instance of DiagramPage. DiagramPage is derived from the Diagram class and adds a Title property. All your current code that uses Diagram objects will work with DiagramPage objects. You can add, modify, rearrange and delete DiagramPage-s with the Pages collection.

The new TabbedScrollPane displays tabs for each DiagramDocument page. You can specify the active page by activating its associated tab. Use the buttons in the tab tray to add and remove pages to/from the document. Drag the tab of a page with the mouse to change its location.

Layer List Control

The new LayerListView control displays all layers of the Diagram together with a title and an overview area. You can edit the Visible and Locked properties of the layer and set the currently active layer. Use the plus (+) button to add new layers to the Diagram.

Layers

Now you can assign diagram Item-s into layers. Layers can be locked, hidden moved up or down in the Z-order or as a group. Call the setLayerIndex method of items to associate them with layers in the Diagram.Layers collection. Each Layer has Visible, Locked and ZIndex properties, which affect all items in the layer.

    
One-way Layout

The OneWayLayout class ensures that links enter into nodes from the same general direction and exit them from the opposite side.
Ruler improvements

The new MeasureUnit class lets you specify units of the ruler. The MeasureUnit class provides several built-in units as well as the opportunity to create custom units of measure.


Magnifier

The new magnifier tool allows users to interactively zoom in (or out) portions of the diagram by holding down a modifier key or pressing a mouse button. You can customize the magnifier's zoom factor and appearance.
Miscellaneous

The Shape property in ContainerNode and TreeViewNode can be set to Rectangle or RoundRect;
the value of DiagramItem.ZIndex property is no longer required to be unique and smaller than the number of items;
and more.

API Changes

A few changes were required to keep the API elegant and easy to use with the numerous new features added to Diagramming for Java. The changes are described in details in the "What's new" section in the documentation of the component.

Monday 4 February 2013

Reading Connection Strings from the Web.config File

Reading Connection Strings from the Web.config File 

The connectionStrings element is a ConnectionStringSettingsCollection collection of ConnectionStringSettings objects. Working with collection elements can be slightly more complicated than working with other configuration elements.

To update a configuration setting, use the Save or SaveAs method of the configuration object. For more information, see Using the Configuration Classes. For additional code examples, see the ConnectionStringsSection class and related classes.

This example uses the non-static method of obtaining configuration data, which allows you to pull configuration information from any application. If you are going to obtain configuration information from the application in which your code resides, use the static method, which processes faster. For more information, see the Working with Local and Remote Configuration Settings section in ASP.NET Configuration API Overview.

This example applies to a Web site named MyWebSiteRoot. To run the sample, you will have to either run it in a Web site by that name or replace the string supplied to the OpenWebConfiguration method with the name of your Web site.


C#


System.Configuration.Configuration rootWebConfig =
    System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("/MyWebSiteRoot");
System.Configuration.ConnectionStringSettings connString;
if (0 < rootWebConfig.ConnectionStrings.ConnectionStrings.Count)
{
    connString =
        rootWebConfig.ConnectionStrings.ConnectionStrings["NorthwindConnectionString"];
    if (null != connString)
        Console.WriteLine("Northwind connection string = \"{0}\"",
            connString.ConnectionString);
    else
        Console.WriteLine("No Northwind connection string");
}

VB
Dim rootWebConfig As System.Configuration.Configuration
    rootWebConfig = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("/MyWebSiteRoot")
Dim connString As System.Configuration.ConnectionStringSettings
If (0 < rootWebConfig.ConnectionStrings.ConnectionStrings.Count) Then
    connString = rootWebConfig.ConnectionStrings.ConnectionStrings("NorthwindConnectionString")
    If Not (Nothing = connString.ConnectionString) Then
        Console.WriteLine("Northwind connection string = {0}", connString.ConnectionString)
    Else
        Console.WriteLine("No Northwind connection string")
    End If
End If

Compiling the Code
This example requires:

    A connectionStrings element in the root Web.config file that contains a connection named NorthwindConnectionString. The element might look like the following:

<connectionStrings>
  <add
    name="NorthwindConnectionString"
    connectionString="Data Source=serverName;Initial
    Catalog=Northwind;Persist Security Info=True;User
    ID=userName;Password=password"
    providerName="System.Data.SqlClient"
  />
</connectionStrings>

The connectionStrings element is a direct child of the <configuration> element and a peer of the system.web element.
Security noteSecurity Note

When storing sensitive information such as user names and passwords in a configuration file, you should encrypt the sensitive values using protected configuration. For more information, see How to: Secure Connection Strings When Using Data Source Controls.
Robust Programming

If the specified connection string does not exist in the Web.config file, no object is returned. When reading connection strings, be sure to check that the code has returned an object.
Security

The configuration file should be protected on the server by using Windows security settings to limit who can read the file. The connectionString element can be encrypted in order to protect it.

Sunday 3 February 2013

Create Custom Configuration Sections Using IConfigurationSectionHandler

Create Custom Configuration Sections Using IConfigurationSectionHandler 

You can extend the standard set of ASP.NET configuration settings with XML configuration elements of your own. To do this, you must create your own configuration section handler.

The handler must be a .NET Framework class that implements either the System.Configuration.IConfigurationSectionHandler interface or the System.Configuration.ConfigurationSection class.

NOTE:
This topic uses the System.Configuration.IConfigurationSectionHandler interface, which has been deprecated in the .NET Framework version 2.0. For an example that uses the System.Configuration.ConfigurationSection class, see How to: Create Custom Configuration Sections Using ConfigurationSection. If you use the following code examples, please build them with the .NET Framework version 1.0 or 1.1.

The section handler interprets and processes the settings defined in XML configuration elements within a specific portion of a Web.config file and returns an appropriate configuration object based on the configuration settings. The configuration object that the handler class returns can be any data structure; it is not limited to any base configuration class or configuration format. ASP.NET uses the configuration object to read and write to your custom configuration element.
To create a custom configuration section handler

Create a public class that implements the System.Configuration.IConfigurationSectionHandler interface, as illustrated in the following code.
using System;
using System.Collections.Generic;
using System.Text;
using System.Configuration;
using System.Xml;

namespace MyConfigSectionHandler
{
  public class MyHandler : IConfigurationSectionHandler
  {
    #region IConfigurationSectionHandler Members

    object IConfigurationSectionHandler.Create(
        object parent, object configContext, XmlNode section)
    {
      throw new Exception("The method is not implemented.");
    }

    #endregion
  }
}


Add your own code to perform the configuration work that you desire.


For example, you can replace the throw new Exception("The method is not implemented."); line with code that obtains the attribute names and values from the Attributes property of the section parameter, and return a custom configuration object. The following example uses a Hashtable as the configuration object.

using System;
using System.Collections;
using System.Text;
using System.Configuration;
using System.Xml;

namespace MyConfigSectionHandler
{
  public class MyHandler : IConfigurationSectionHandler
  {
    #region IConfigurationSectionHandler Members

    object IConfigurationSectionHandler.Create(
      object parent, object configContext, XmlNode section)
    {
      // Creates the configuration object that this method will return.
      // This can be a custom configuration class.
      // In this example, we use a System.Collections.Hashtable.
      Hashtable myConfigObject = new Hashtable();

      // Gets any attributes for this section element.
      Hashtable myAttribs = new Hashtable();
      foreach (XmlAttribute attrib in section.Attributes)
      {
        if (XmlNodeType.Attribute == attrib.NodeType)
          myAttribs.Add(attrib.Name, attrib.Value);
      }

      // Puts the section name and attributes as the first config object item.
      myConfigObject.Add(section.Name, myAttribs);

      // Gets the child element names and attributes.
      foreach (XmlNode child in section.ChildNodes)
      {
        if (XmlNodeType.Element == child.NodeType)
        {
          Hashtable myChildAttribs = new Hashtable();

          foreach (XmlAttribute childAttrib in child.Attributes)
          {
            if (XmlNodeType.Attribute == childAttrib.NodeType)
              myChildAttribs.Add(childAttrib.Name, childAttrib.Value);
          }
          myConfigObject.Add(child.Name, myChildAttribs);
        }
      }

      return (myConfigObject);
    }
    #endregion
  }
}


To add a custom section handler to an ASP.NET configuration file

Add a sectionGroup and section element to your Web.config file inside the configSections element, as illustrated in the following code.

    Nesting a section element in a sectionGroup is optional, but is recommended to help organize configuration data.

    You can add the section handler declaration in a different configuration file than the one where you add your custom configuration elements providing that the configuration file where the section handler is declared is higher in the configuration file hierarchy. For more information, see ASP.NET Configuration File Hierarchy and Inheritance.

    The type attribute of the section element must match the manifest of the assembly or there will be a configuration error. The assembly file itself must be in the same ASP.NET application directory as the Web.config file that defines it.

    <configuration>

    <!-- Configuration section-handler declaration area. -->
      <configSections>
        <sectionGroup name="myCustomGroup">
          <section
            name="myCustomSection"
            type="MyConfigSectionHandler.MyHandler, MyCustomConfigurationHandler, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"
            allowLocation="true"
            allowDefinition="Everywhere"
          />
        </sectionGroup>
          <!-- Other <section> and <sectionGroup> elements. -->
      </configSections>

      <!-- Configuration section settings area. -->

    </configuration>

    Add your custom configuration elements in the configuration section settings area of your Web.config file.

    <configuration>

    <!-- Configuration section-handler declaration area. -->

      <!-- Configuration section settings area. -->
      <myCustomGroup>
        <myCustomSection myAttrib1="Clowns">
          <myChildSection
              myChildAttrib1="Zippy"
              myChildAttrib2="Michael Zawondy "/>
        </myCustomSection>
      </myCustomGroup>

      <!-- Other configuration settings, like <system.web> -->

    </configuration>

To programmatically access your custom configuration data

    Obtain an instance of your custom configuration object and use the System.Configuration.ConfigurationManager.GetSection(System.String) method or the System.Web.Configuration.WebConfigurationManager.GetSection(System.String) method to populate it.

    The following example of an ASPX page works with the previous examples to enumerate the attributes and child elements of the custom configuration section when a button is clicked.

    Because the custom section handler uses a Hashtable as the configuration object, the GetSection method returns a Hashtable.

    The following code goes in the .aspx page. The code for the button click event, which goes in the code-behind file, is contained in the next code example.

    The following code examples require the .NET Framework version 1.0 or 1.1.
    C#

    <%@ Page language="c#" Codebehind="WebForm1.aspx.cs" AutoEventWireup="false" Inherits="BugTest.WebForm1" %>
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >

    <html>
      <head>
        <title>WebForm1</title>
        <meta name="GENERATOR"
              Content="Microsoft Visual Studio .NET 2003">
        <meta name="CODE_LANGUAGE" Content="C#">
        <meta name=vs_defaultClientScript content="JavaScript">
        <meta name=vs_targetSchema
              content="http://schemas.microsoft.com/intellisense/ie5">
      </head>
      <body MS_POSITIONING="GridLayout">
        <form id="Form1" method="post" runat="server">
        <h1>Enumerate MyCustomSection</h1>
        <asp:Label ID="Label1" runat="server"
            Text="" />
        <br />
        <asp:Button ID="Button1" runat="server"
            Text="Get Custom Config Info"
            OnClick="Button1_Click" />
        </form>
      </body>
    </html>

    VB

    <%@ Page Language="vb" AutoEventWireup="false" Codebehind="WebForm1.aspx.vb" Inherits="WebApplication1.WebForm1"%>
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
    <HTML>
      <HEAD>
        <title>WebForm1</title>
        <meta name="GENERATOR" Content="Microsoft Visual Studio .NET 2003">
        <meta name="CODE_LANGUAGE" Content="VB">
        <meta name="vs_defaultClientScript" content="JavaScript">
        <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">
      </HEAD>
      <body MS_POSITIONING="GridLayout">
        <form id="Form1" method="post" runat="server">
          <h1>Enumerate MyCustomSection</h1>
          <asp:Label ID="Label1" runat="server" Text="" />
          <br>
          <asp:Button ID="Button1" runat="server" Text="Get Custom Config Info" OnClick="Button1_Click" />
        </form>
      </body>
    </HTML>

    The following code for the button click event goes in the code-behind file that belongs to the preceding .aspx page. The code-behind file uses the file name extension of .aspx.cs or .aspx.vb, depending on the language attribute of the @Page declaration.

    [C#]

    using System;
    using System.Collections;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Web;
    using System.Web.SessionState;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.UI.HtmlControls;
    using System.Configuration;
    using System.Text;

    namespace BugTest
    {
        /// <summary>
        /// Summary description for WebForm1.
        /// </summary>
        public class WebForm1 : System.Web.UI.Page
        {
            protected System.Web.UI.WebControls.Label Label1;
            protected System.Web.UI.WebControls.Button Button1;
       
            private void Page_Load(object sender, System.EventArgs e)
            {
                // Put user code to initialize the page here
            }

            #region Web Form Designer generated code
            override protected void OnInit(EventArgs e)
            {
                //
                // CODEGEN: This call is required by the ASP.NET Web Form Designer.
                //
                InitializeComponent();
                base.OnInit(e);
            }
           
            /// <summary>
            /// Required method for Designer support - do not modify
            /// the contents of this method with the code editor.
            /// </summary>
            private void InitializeComponent()
            {   
                this.Button1.Click += new System.EventHandler(this.Button1_Click);
                this.Load += new System.EventHandler(this.Page_Load);

            }
            #endregion

            protected void Button1_Click(object sender, System.EventArgs e)
            {
                Hashtable config =
    (Hashtable)System.Configuration.ConfigurationSettings.GetConfig("myCustomGroup/myCustomSection");
               
                StringBuilder sb = new StringBuilder();
                sb.AppendFormat("Config object item count = {0}<br/><br/>", config.Count);
                foreach (DictionaryEntry deKey in config)
                {
                    sb.AppendFormat("<h2>Attributes in the {0} Element:</h2>",
                        deKey.Key.ToString());
                    Hashtable attribs = (Hashtable)deKey.Value;
                    foreach (DictionaryEntry deAttrib in attribs)
                    {
                        sb.AppendFormat("{0} = {1}<br/>",
                            deAttrib.Key.ToString(), deAttrib.Value.ToString());
                    }
                }
                Label1.Text = sb.ToString();
                Label1.Visible = true;

            }
        }
    }

    VB

    Imports System.Text

    Public Class WebForm1
      Inherits System.Web.UI.Page

    #Region " Web Form Designer Generated Code "

      'This call is required by the Web Form Designer.
      <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()

      End Sub
      Protected WithEvents Label1 As System.Web.UI.WebControls.Label
      Protected WithEvents Button1 As System.Web.UI.WebControls.Button

      'NOTE: The following placeholder declaration is required by
      ' the Web Form Designer.
      'Do not delete or move it.
      Private designerPlaceholderDeclaration As System.Object

      Private Sub Page_Init(ByVal sender As System.Object, ByVal _
    e As System.EventArgs) Handles MyBase.Init
        'CODEGEN: This method call is required by the Web Form Designer
        'Do not modify it using the code editor.
        InitializeComponent()
      End Sub

    #End Region

      Private Sub Page_Load(ByVal sender As System.Object, ByVal _
    e As System.EventArgs) Handles MyBase.Load
        'Put user code to initialize the page here
      End Sub

      Protected Sub Button1_Click(ByVal sender As System.Object, ByVal _
    e As System.EventArgs) Handles Button1.Click
        Dim config As Hashtable = _
    System.Configuration.ConfigurationSettings.GetConfig( _
    "myCustomGroup/myCustomSection")

        Dim sb As New StringBuilder
        sb.AppendFormat("Config object item count = {0}<br/><br/>", _
    config.Count)

        For Each deKey As DictionaryEntry In config
          sb.AppendFormat("<h2>Attributes in the {0} Element:</h2>", _
    deKey.Key.ToString())
          Dim attribs As Hashtable = deKey.Value
          For Each deAttrib As DictionaryEntry In attribs
            sb.AppendFormat("{0} = {1}<br/>", deAttrib.Key.ToString(), _
    deAttrib.Value.ToString())
          Next
          Label1.Text = sb.ToString()
          Label1.Visible = True
        Next

      End Sub
    End Class

Saturday 2 February 2013

Access and Modify ASP.NET Configuration Files Remotely


The System.Configuration and System.Web.Configuration types allow your application to access the configuration files on a remote server. In particular, you can open and modify the Machine.config or a Web.config file in any Microsoft Internet Information Services (IIS) application or its child directories on a remote server. This topic:

    Demonstrates how to set the remote server to allow a client computer to access the server configuration files.

    Provides a console application, to run on the client computer, that can read or modify the server configuration files.

    Discusses the security considerations to take into account.

To access configuration files on a remote server, the client computer must be able to communicate with the server. To enable this communication, a remote configuration component must be installed on the server.

The client computer then accesses the server configuration files by calling the ASP.NET configuration API through the remote configuration component. For more information, see Editing ASP.NET Remote Configuration Files.

Note

If the requested configuration file does not exist, the .NET Framework, running on the server, returns a configuration file consisting entirely of inherited settings that apply to the specified path. If your application requests an update, a new file is created. When running the console application, you must enter a valid server name. This is because ASP.NET passes this name directly to the operating system. You must likewise enter a fully qualified user name with the domain name prefix.


To set up the remote server

    Install the remote configuration component on the server using the ASP.NET IIS Registration tool (Aspnet_regiis.exe) with the config+ command, as shown in the following code.

    Aspnet_regiis config+

    Programmatically or manually, make sure that the Web.config file of the IIS server's "Default Web Site" contains values similar to the following:

    <appSettings>
        <add key="keyName1", value = "this entry value"/>
        <add key="keyName2", value = "this entry value"/>
        <add key="keyName3", value = "this entry value"/>
    </appSettings>

To update the remote configuration files using a console application

    Run the console application provided in the code example below to update the Web.config file of the Default Web Site on the remote server. This example assumes that the user running the client application has administrative privileges on the remote server. You can use either of these two commands.

    >remoteconfiguration machineName
    >remoteconfiguration machineName domainName\userName password

Friday 1 February 2013

Create and Configure an HTTP Module

Create and Configure an HTTP Module

configure the httpModules element of a Web-application configuration by using the HttpModulesSection class and related types.

An HTTP module is a type that implements the IHttpModule interface and provides request processing by handing application events. For more information about HTTP modules, see Introduction to HTTP Modules.

The following table lists the accompanying topics, which include the code for an example HTTP module and an example configuration that programmatically adds and removes the HTTP module from an ASP.NET Web application. The HTTP module in these examples is a simple library application called RequestTimeIntervalModule.dll. Members of the RequestTimeIntervalModule class calculate the time interval between the beginning and the end of the Web request, obtain the principal's ID, and finally display the information on any Web page in the application.

Using the Example HTTP Module

The following preparatory steps are required to use the accompanying code examples.

Note:

You must run this example in an intranet environment where you can use Windows authentication to authenticate the users. By default, only administrators have read/write access to a Web.config file.

To create the HTTP module

    Compile the code for the HTTP module (Example HTTP Module) as a class library called RequestTimeIntervalModule. This produces an assembly DLL.

    Create a Web application named Test. You can create the application in IIS as a virtual directory named Test. If you need information about creating and configuring an IIS virtual directory, see How to: Create and Configure Virtual Directories in IIS.

    Create a Bin directory directly under the root directory of your Web application (which is also called the Web-application root).

    In the Bin directory, copy the RequestTimeIntervalModule.dll file.

Note:Alternatively, you can use the ASP.NET dynamic compilation feature to test your HTTP module code without pre-compiling an assembly DLL. ASP.NET dynamically compiles source code files that are placed in the App_Code directory directly under the root directory of your Web site. Therefore, classes in source files in the App_Code directory can be accessed from pages without being pre-compiled into assemblies. The App_Code directory is a new feature that is available in ASP.NET version 2.0. Storing your HTTP module code in the App_Code directory allows you to easily test the module without pre-compiling the code. For an example that uses this kind of implementation, see How to: Create Custom HTTP Modules. For information about compilation options, see ASP.NET Compilation Model.

Configuring the Example HTTP Module

This code example uses the HttpModulesSection class and related types to configure the application.
To configure the HTTP module

    Compile the code for configuring the HTTP module (Example Configuration Code for an HTTP Module) as a console application.

    From a command-line, call your console application. If there is no existing setting for the RequestTimeIntervalModule HTTP module, one is created. If there is no existing Web.config file in your ASP.NET application, one is created with the new setting. The setting might look like the following httpModules element, as a child element of the system.web element, in your Web.config file.

Testing the Example HTTP Module

HTTP modules enable you to examine the outbound response and modify it. The RequestTimeIntervalModule HTTP module uses the System.Web.HttpResponse.Output property to append some text to the response body.
To test the HTTP module

    In the root directory, create a blank ASP.NET page called Default.aspx.

    Open a Web browser and request the Default.aspx page from the application called Test, which you created earlier.

    The RequestTimeIntervalModule HTTP module appends the following text to any requested page in your ASP.NET application:

    Current user: <user name>

    Time span between begin-request and end-request events: <timespan>

    Your friendly HttpModule: RequestTimeIntervalModule

Source:http://msdn.microsoft.com/en-us/library/tfd6k449%28v=vs.85%29.aspx

Thursday 31 January 2013

JVM Server vs Client Mode

JVM Server vs Client Mode

JVM is launched in client mode by default in SUN/Orace JDK. JVM provides option to launch it in server or client mode. These two modes give different run time performance options.

At high level there are two steps from java source to running program. In first step we compile the java source to binary class file. In next step binary class is executed. In java class execution, combination of interpretation and compilation is done. Generally it is interpretation and to boost the performance JVM uses a just-in-time (JIT) compiler.

JIT compiles selective block of code to native instructions. Because running native instructions is always better and gives good performance. This is done at the cost of spending resource to compile code to native. There will be a performance benefit, if that block of code is used repeatedly as in subsequent runs instead of interpreting the binary code the native instructions will be executed.

When the JVM is launched in ‘server’ mode, it performs aggressive optimization than the ‘client’ mode. So server mode is better suited for production deployments and gives better performance. In case of tiny programs, where there is minimal scope for optimization server mode may not be best suited and in times it can even give worst performance than the client mode because of the additional cost of native code conversion.

The policy of having a JIT compiler and the performance optimization algorithm are completely the choice of the JVM implementors and it is not enforced in JVM specification. So when we study this behavior it is completely specific to the JVM we use and it cannot be generalized.

How to choose between client and server jvm mode?

To choose between server and client mode we can have client mode for small programs that are not executed for a longer period and server mode otherwise. The startup of the JVM might be slower in server mode and the runtime memory footprint also will be larger. Client mode starts JVM in quicker time and memory footprint is also lesser. This is because client mode does not try to optimize many code blocks as the server mode does. Therefore the shorter startup time and less memory usage.

So what is the special optimization done by server mode? One example is in lining of virtual method invocations wherever it is used. This is done by adaptive compilation. One more thing done by server mode is, it does not give back the memory acquired back to the OS till the execution is complete. But in case of client mode if a certain block of memory is left unused it may give back to the OS during the execution of the program. Initial options like InitialHeapSize and MaxHeapSize are taken as large numbers in server mode on launch in comparison with client mode.

JVM hotspot VM options provide rich set of opportunities to calibrate the runtime performance. So to launch is client mode we need not give any options as by default the JVM launches in client mode. To launch in server mode just use “- server” when we run java tool like,

java -server ClassName

This is based on SUN/Oracle JDK. If it is JRockit VM the default is server mode and client mode should be launched using option “-client”. Ah I forgot to mention a thing, as always the same java class can be used for running in both the modes. When we download JDK we get both the modes bundled. If we download JRE alone, then we get only the client mode with it.

Just in case if you don’t know what JVM you are using then the following java code should help.

String jvmName = System.getProperty("java.vm.name");  // jvmName = Java HotSpot(TM) Server VM

Source:javapapers

Wednesday 30 January 2013

Image Compression in ASP.NET using C#

You may want to compress image and save to a new file or compress them while loading any big images in your asp.net application.

This is an example for Image compression in ASP.NET using C#. System.Drawing.Imaging Namespace is used and class EncoderParameter, Encoder and EncoderParameters are used to compress the given image. Image compression will reduce the Bandwidth usage in the networks and can be sent quickly via mails.

Design

To get the image from user Place a file upload control and a button in the design and create onclick event called protected void Button3_Click() in code behind file,



<form id="form1" runat="server">
    <div>
    <asp:FileUpload ID="FileUpload1" runat="server" oolTip="Upload image" />
    <asp:Button ID="Button3" runat="server" nclick="Button3_Click" Text="Load"  ForeColor="#003366" />
    </div>
   
</form>



Code behind file for compress the uploaded image:


//Use the following Namespaces

using System.Drawing;
using System.IO;
using System;
using System.Drawing.Imaging;

//Mention the path to store the uploaded image

string Path = @"Your Path";



in the onclick event store the image and convert into bitmap type. then call the imgcompression method to compress the image


protected void Button3_Click(object sender, EventArgs e)
 {
    FileUpload1.SaveAs(ImagePath);
    string imgpath = Path.Combine( Path, FileUpload1.FileName);
    Bitmap img = new Bitmap(imgpath);
    imgcompression(img);
 }



Compress your image to various quality. Encoder Quality range zero is low quality and 100 is high quality.
Here you can get different qualities of a image using EncoderParameter, Encoder and EncoderParameters classes


static void imgcompression(Image img_in)
 {

    ImageCodecInfo jpeg = null;
    ImageCodecInfo[] imgtypes = ImageCodecInfo.GetImageEncoders();
    foreach (ImageCodecInfo jpegtype in imgtypes)
     {
        if (jpegtype.FormatID == ImageFormat.Jpeg.Guid)
         {
            EncoderParameters encParams = new EncoderParameters(1);

            for (long quality_rate= 10; quality_rate<= 100; quality_rate+=10)
             {
                EncoderParameter encParam = new EncoderParameter(Encoder.Quality, quality_rate);
                encParams.Param[0] = encParam;
                string strPath = Path.Combine(imgPath, "" + quality + ".jpeg");
                FileStream fs = new FileStream(strPath, FileMode.Create, FileAccess.Write);
                            img_in.Save(fs, jpgEncoder, encParams);
                fs.Flush();
                fs.Close();
             }
         }

     }
 }

Tuesday 29 January 2013

Marshalling Java Objects to JSON objects


A tutorial on how to create JSON object from Java objects

Gson API is a very useful API that enables you to marshal Java objects to JSON objets and unmarshall json objects to java objects.
In this tutorial we will see how easy we can marshall an object model to JSON objects.
As an example consider the case were we have a simple model that consists of tutorial categories and tutorials.
In the below snipet are the Tutorial and Category classes

package com.javaonly.json;

import java.util.Set;

public class Category {
     private int id;
     private String categoryName;
     private Set subCategories;
     private Category parentCategory;
      public int getId() {
     return id;
     }
      public void setId(int id) {
     this.id = id;
     }
      public String getCategoryName() {
     return categoryName;
     }
      public void setCategoryName(String categoryName) {
     this.categoryName = categoryName;
     }
       public Category getParentCategory() {
     return parentCategory;
     }
      public void setParentCategory(Category parentCategory) {
     this.parentCategory = parentCategory;
     }
     public String toString(){
     return getCategoryName();
     }
      public Set getSubCategories() {
     return subCategories;
     }
      public void setSubCategories(Set subCategories) {
     this.subCategories = subCategories;
     }
     }

package com.javaonly.json;

import java.util.Set;

public class Category {
     private int id;
     private String categoryName;
     private Set subCategories;
     private Category parentCategory;
      public int getId() {
     return id;
     }
      public void setId(int id) {
     this.id = id;
     }
      public String getCategoryName() {
     return categoryName;
     }
      public void setCategoryName(String categoryName) {
     this.categoryName = categoryName;
     }
       public Category getParentCategory() {
     return parentCategory;
     }
      public void setParentCategory(Category parentCategory) {
     this.parentCategory = parentCategory;
     }
     public String toString(){
     return getCategoryName();
     }
      public Set getSubCategories() {
     return subCategories;
     }
      public void setSubCategories(Set subCategories) {
     this.subCategories = subCategories;
     }
     }

Suppose now that we want to represent a java tutorial in json format.In other words we need to create the following JSON object:

{
"id":1,
"title":"Java Objects to JSON format",
"summary":"This is the summary",
"body":"This is the body",
"negativeVotes":0,
"possitiveVotes":0,
"category":{
              "id":1,
              "categoryName":"JAVA" 
            },
"dateAdded":"Nov 30, 2012 3:03:22 PM"
}

 Using toJSon() method  from Gson class:

package com.javaonly.json;



import java.util.Date;

import com.google.gson.Gson;

public class JsonTest {

    public static void main(String args[]){
        Category java=new Category();
        java.setId(1);
        java.setCategoryName("JAVA");
       
        Tutorial tutorial=new Tutorial();
        tutorial.setId(1);
        tutorial.setCategory(java);
        tutorial.setTitle("Java Objects to JSON format");
        tutorial.setSummary("This is the summary");
        tutorial.setBody("This is the body");
        tutorial.setDateAdded(new Date());
       
       
        Gson gson = new Gson();
        String json = gson.toJson(tutorial);
        System.out.println(json);
       
       
    }
}

 On the other hand the unmarshalling of a JSON object is quite simple too:

package com.javaonly.json;


import java.util.Date;

import com.google.gson.Gson;

public class JsonTest {

    public static void main(String args[]){
        Category java=new Category();
        java.setId(1);
        java.setCategoryName("JAVA");
       
        Tutorial tutorial=new Tutorial();
        tutorial.setId(1);
        tutorial.setCategory(java);
        tutorial.setTitle("Java Objects to JSON format");
        tutorial.setSummary("This is the summary");
        tutorial.setBody("This is the body");
        tutorial.setDateAdded(new Date());
       
       
        Gson gson = new Gson();
        String json = gson.toJson(tutorial);
        System.out.println(json);
       
        Tutorial jsonTutorial=gson.fromJson(json, Tutorial.class);
        System.out.println("TUTORIAL:"+jsonTutorial.getCategory().getCategoryName());
    }
}

 In the above example note that the category json object is unmarhalled in Category object and you can access it with getCategory() method

Monday 28 January 2013

Integrating XML News Feeds into ASP.NET Pages

Much of the talk about XML now days tends to be focused around using it for data exchange between e-business applications. While it"s true that XML is well-suited for this purpose due to its ability to describe data and maintain its structure while being transferred between distributed systems, there are many other ways it can be used to enhance applications.

This sample application demonstrates one of these ways by showing how XML can be integrated into a website to provide users with news information. The application relies on different classes found in the .NET platform that are used to retrieve an XML news document, parse it, and generate headlines that are displayed in the browser using JavaScript and DHTML. All of this functionality is included in a User Control to make adding news headlines to ASP.NET pages a snap.

Friday 25 January 2013

A DataBound Javascript News Ticker for ASP.NET

A DataBound Javascript News Ticker for ASP.NET

 It's funny how requirements come along like buses in the ASP.NET forums - you suddenly get the same thing asked for by two or more people in quick succession. Recently, a couple of people asked for help creating a Javascript ticker, like the one at the top of the BBC News site, which displays a selected number of headlines drawn from a database. I had adapted the code from the BBC site to create a similar widget that displayed the most recent threads in a message board on an old Classic ASP site some time ago. It's about time I dusted it off and updated it for use in an ASP.NET application.

To keep things relatively simple, I've created the ticker as a User Control, which is the ASP.NET successor to my original Server-Side Include file. The ascx file will hold the Javascript and the ascx.cs file will contain the data access code. First the Javascript:

<script language="JavaScript" type="text/javascript">

var CharacterTimeout = 50;

var StoryTimeout = 3000;

var SymbolOne = '_';

var SymbolTwo = '-';

var SymbolNone = '';

var LeadString = 'LATEST:&nbsp;&nbsp;&nbsp;';

var Headlines = new Array();

var Links = new Array();

var ItemCount = 4;


<asp:Literal ID="MyTicker" runat="server" />

 function startTicker() {

 StoryCounter = -1;

 LengthCounter = 0;

 TickerLink = document.getElementById("tickerlink");

 runTicker();

}

function runTicker() {

 var Timeout;

 if (LengthCounter == 0) {

  StoryCounter++;

  StoryCounter = StoryCounter % ItemCount;

  CurrentHeadline = Headlines[StoryCounter];

  TargetLink = Links[StoryCounter];

  TickerLink.href = TargetLink;

  Prefix = "<span class=\"ticker\">" + LeadString + "</span>";

 }

 TickerLink.innerHTML = Prefix + CurrentHeadline.substring(0, LengthCounter) + getSymbol();

 if (LengthCounter != CurrentHeadline.length) {

  LengthCounter++;

  Timeout = CharacterTimeout;

 }

 else {

  LengthCounter = 0;

  Timeout = StoryTimeout;

 }

 setTimeout("runTicker()", Timeout);

}


function getSymbol() {

 if (LengthCounter == CurrentHeadline.length) {

  return SymbolNone;

 }

 if ((LengthCounter % 2) == 1) {

  return SymbolOne;

 }

 else {

  return SymbolTwo;

 }

}

startTicker();

</script>

The Javascript starts with a set of variables being defined. CharacterTimeout and StoryTimeout respectively set the delay between the addition of characters to the headline, and the next story appearing. Three symbols are created, which give the appearance of a typewriter or old-fashioned teletype running as characters are appended to the headline. Finally, and array is set for the headlines, and one for the links, followed by the total number of headlines that will be managed by the ticker.

Next, an asp:Literal control is added. This will serve as a placeholder for the array of headlines and links that will be retrieved from the database. This is followed by the three functions that do the brunt of the work:

startTicker()
startTicker() intialises the ticker by setting some counters to their starting values, and then it locates the <a> tag that will display the links. The <a> tag has not been added yet, but should appear at the top of the ascx file:

<div>
  <a id="tickerlink" href="#" style="text-decoration: none;"></a>
</div>

Finally, it calls the next function:

runTicker()
LengthCounter holds the current position within the current headline. If the headline has finished, or not been started at all, the counter is set to 0. The StoryCounter, which was initialised at -1 is set to 0, or the next headline in the array. The link that matches the headline is also referenced. Then the initial text in the ticker is picked up and set inside a <span> that holds a CSS class attribute so that it can be styled. Then the <a> link text is set to hold the current headline together with its link and a symbol retrieved using the getSymbol() function. Some checks are made to calculate whether the current headline has been written, or is in the process of being written, then the runTicker() function is called with the value of TimeOut having been ascertained.

getSymbol()
This function is pretty simple. All it does is to alternate between symbols - either a hyphen or an underline - depending on whether the position reached within the string containing the headline is odd or even. If the end of the string hass been reached, the symbol is an empty string.

Last of all, the first function, startTicker() is called.

Now to the code-behind file for the user control:

StringBuilder sb = new StringBuilder();

string connect = ConfigurationManager.ConnectionStrings["myConnString"].ConnectionString;

using (SqlConnection conn = new SqlConnection(connect))

{

  string query = "SELECT TOP 4 ArticleID, Headline FROM Articles ORDER BY ArticleID DESC";

  SqlCommand cmd = new SqlCommand(query, conn);

  conn.Open();

  using (SqlDataReader rdr = cmd.ExecuteReader())

  {

    int i = 0;

    while (rdr.Read())

    {

      sb.Append("Headlines[" + i.ToString() + "] = '" + rdr[1].ToString() + "';");

      sb.Append("Links[" + i.ToString() + "] = '/Article.aspx?ArticleID=" + rdr[0].ToString() + "';");

      i++;

    }

  }

}

MyTicker.Text = sb.ToString();
This is very straightforward too. Remembering to reference System.Data.SqlClient, System.Text and System.Configuration, the code simply connects to a database and gets the most recent 4 headlines in the database together with their ID so that links can be written. While looping through a DataReader, a StringBuilder object is built up containing the text for the headlines and the links. This is set to generate an array for the headlines and one for the links to populate the ones that were instantiated in the Javascript earlier. Finally, the contents of the StringBuilder are passed to the Literal control in the ascx file. And that is it.

The Javascript above looks quite complex at first glance, but hopefully, you can now see that it actually very straightforward.

Thursday 24 January 2013

6 Tips to Improve Your Exception Handling

6 Tips to Improve Your Exception Handling

Getting exception handling right can save you hours (or even days) of troubleshooting.  Unexpected production issues can ruin your dinner and weekend plans.  They can even affect your reputation if not resolved quickly.  Having a clear policy on how to manage exceptions will save you time diagnosing, reproducing, and correcting issues.  Here are 6 tips to improve your exception handling.
1. Use a single, system-wide exception class

Instead of creating separate classes for each exception type, create just one.  And make it extend RuntimeException.  This will reduce your class count and remove the need to declare exceptions you aren’t going to handle anyway.

I know what you’re thinking: How will I tell exceptions apart if they’re all the same type?  And how will I track type-specific properties?  Read on!
2. Use enums for error codes

Most of us were trained to put the cause of an exception into its message.  This is fine when reviewing log files (ugh), but it does have drawbacks:

   1. Messages can’t be translated (unless you’re Google).
   2. Messages can’t be easily mapped to user-friendly text.
   3. Messages can’t be inspected programmatically.

Putting info in the message also leaves the wording up to each developer, which can lead to different phrases for the same failure.

6 tips to improve your exception handling

A better approach is to use enums to indicate the exception’s type.  Create one enum for each category of errors (payments, authentication, etc.).  Make the enums implement an ErrorCode interface and reference it as a field in the exception.

When throwing exceptions, simply pass in the appropriate enum.


throw new SystemException(PaymentCode.CREDIT_CARD_EXPIRED);

Now when you need to test for a specific case, just compare the exception’s code with the enum.

} catch (SystemException e) {
  if (e.getErrorCode() == PaymentCode.CREDIT_CARD_EXPIRED) {
  ...
  }
}

User-friendly, internationalized text can now be retrieved by using the error code as the resource bundle’s lookup key.


public class SystemExceptionExample3 {

    public static void main(String[] args) {
        System.out.println(getUserText(ValidationCode.VALUE_TOO_SHORT));
    }

    public static String getUserText(ErrorCode errorCode) {
        if (errorCode == null) {
            return null;
        }
        String key = errorCode.getClass().getSimpleName() + "__" + errorCode;
        ResourceBundle bundle = ResourceBundle.getBundle("com.northconcepts.exception.example.exceptions");
        return bundle.getString(key);
    }

}

3. Add error numbers to enums

In some cases a numerical error code can be associated with each exception. HTTP responses for example. For those cases, add a getNumber method to the ErrorCode interface and implement it in each enum.


public enum PaymentCode implements ErrorCode {
  SERVICE_TIMEOUT(101),
  CREDIT_CARD_EXPIRED(102),
  AMOUNT_TOO_HIGH(103),
  INSUFFICIENT_FUNDS(104);

  private final int number;

  private PaymentCode(int number) {
    this.number = number;
  }

  @Override
  public int getNumber() {
    return number;
  }

}

Numbering can be globally unique across all enums or each enum can be responsible for numbering itself. You can even use the implicit ordinal() method or load numbers from a file or database.
4. Add dynamic fields to your exceptions

Good exception handling means also recording relevant data, not just the stack trace. Doing this will save you big time when trying to diagnose and reproduce errors.  And customers won’t have to tell you what they were doing when your app stopped working (you’ll already know and hopefully have fixed it).

The easiest way to do this is to add a java.util.Map field to the exception.  The new field’s job will be to hold all your exception related data by name.  You’ll also need to add a generic setter method following the fluent interface pattern.

Throwing exceptions, with relevant data, will now look something like the following.

throw new SystemException(ValidationCode.VALUE_TOO_SHORT)
  .set("field", field)
  .set("value", value)
  .set("min-length", MIN_LENGTH);

5. Prevent unnecessary nesting

Long, redundant stack traces help no one. Even worse, they waste your time and resources.  When rethrowing exceptions, call a static wrap method instead of the exception’s constructor . The wrap method will be responsible for deciding when to nest exceptions and when to just return the original instance.


public static SystemException wrap(Throwable exception, ErrorCode errorCode) {
  if (exception instanceof SystemException) {
    SystemException se = (SystemException)exception;
    if (errorCode != null && errorCode != se.getErrorCode()) {
      return new SystemException(exception.getMessage(), exception, errorCode);
    }
    return se;
  } else {
    return new SystemException(exception.getMessage(), exception, errorCode);
  }
}

public static SystemException wrap(Throwable exception) {
  return wrap(exception, null);
}

Your new code for rethrowing exceptions will look like the following.

   

} catch (IOException e) {
  throw SystemException.wrap(e).set("fileName", fileName);
}

6. Use a central logger with a web dashboard

Consider this tip a bonus. Depending on your situation, getting access to production logs could be quite a hassle. A hassle that may involve multiple go-betweens (since many developers don’t have access to production environments).

Things get worse if you’re in a multi-server environment. Finding the right server — or determining that the problem only affects one server — can be quite a headache.

My recommendations are:

   1. Aggregate your logs in a single place, preferably a database.
   2. Make that database accessible from a web browser.

There are many ways to do this and may products to choose from: log collectors, remote loggers, JMX agents, system monitoring software, etc. You can even build it yourself. The main thing is that you do it soon. Once you have it, you’ll be able to:

    * Troubleshoot issues in a matter of seconds.
    * Have a URL for each exception that you can bookmark or email around.
    * Enable your support staff to determine root causes without involving you.
    * Prevent testers from creating multiple tickets for the same bug.  Plus they’ll have an exception URL to put in their ticket.
    * Save money for your business.
    * Keep your weekend and reputation intact.

Source:Dele Taylor

Wednesday 23 January 2013

ASP.NET Web Application Security

ASP.NET Web Application Security

Most Web sites need to selectively restrict access to some portions of the site. You can think of a Web site as somewhat analogous to an art gallery. The gallery is open for the public to come in and browse, but there are certain parts of the facility, such as the business offices, that are accessible only to people with certain credentials, such as employees. When a Web site stores its customers' credit card information in a database, for example, access to the database must be restricted. ASP.NET security features help you address this and many other security issues.

ASP.NET, in conjunction with Microsoft Internet Information Services (IIS), can authenticate user credentials such as names and passwords using any of the following authentication methods:

    * Windows: Basic, digest, or Integrated Windows Authentication (NTLM or Kerberos).
    * Microsoft Passport authentication
    * Forms authentication
    * Client Certificate authentication

ASP.NET controls access to site information by comparing authenticated credentials, or representations of them, to NTFS file system permissions or to an XML file that lists authorized users, authorized roles (groups), or authorized HTTP verbs.

This section and the following sections describe the specifics of ASP.NET security. For more information about the types of security attacks Web sites experience and how you can help protect your site from attack, see Security Considerations for ASP.NET Web Applications

Tuesday 22 January 2013

10 Reasons to Develop in ASP


 Active Server Pages are a server-side scripting technology primary developed to work under IIS (Internet Information Server) on Windows NT Server (3rd party products exist enabling the use of ASP on other server platforms). ASP enables the server to deliver dynamic, database driven content to the client with minimal effort.

The goal of this article is not to move developers from other wonderful technologies to ASP, but to explain the advantages of Active Server Pages to Web designers, programmers and anyone interested in Web development. ASP is not my first server-side scripting technology. I was developing with Netscape Server-Side JavaScript, Borland IntraBuilder and Oracle Web Application Server before I moved to ASP. Now I'm an ASP developer, and I will try to explain why I think ASP is currently the best choice for general Web developer.

Ease of Use

Active Server Pages are plain HTML pages with ASP code embedded into them enclosed in <% and %> tags. You just place ASP files into a directory on the server with scripting or execute permissions and your ASPs are ready to run. Whenever you need to change something you just edit the .asp files and that's it, your changes are applied.

Language Independence

ASP is a scripting engine enabling you to develop in virtually any language of your choice. The two languages available by default are VBScript and JScript (Microsoft's version of JavaScript); however, modules for Perl, Python and other languages already exist and there are virtually no limits for support for other languages to be implemented. This enables the novice ASP developer to utilize his or her previous programming experience. If you have ever programmed in Visual Basic or VBA (the version of Visual Basic used in the MSOffice suite), you will have no problems starting with VBScript. If you're familiar with JavaScript, then JScript is your choice. Unix gurus will find that Perl can be used readily.

Short Learning Curve

As you have seen, you may use your current expertise in some programming language or technology to jump into ASP in short time. Even if you know only HTML, it will not be difficult for you to learn how to insert ASP commands into your HTML files. Why, you ask? Just keep reading....

Tons of Information

There are currently more than 150 sites listed in Open Directory's ASP category. This is more than for any other server-side development engine or language. Lots of online magazines will deliver new articles on ASP to your mailbox on a weekly or even daily basis. There's a lot of resources out there for ASP, folks.

Huge Community

There are plenty of professional ASP developers ready to answer your questions in numerous ASP newsgroups and forums. For instance, on the day I write this article, there are more than 50 new threads in the microsoft.public.inetserver.asp.general newsgroup alone.

Low Cost of Ownership

This mainly applies to site owner, not directly to the developer. Nowadays it's easier to find an NT administrator and ASP developer than a UNIX guru. You may think that for you as a developer, this isn't a compelling reason to use ASP. However, low cost and abundance of support is just one more reason you can give to your employer/customer as to why they should do business with you. You can explain that they won't get left high and dry if one day you decide to part company, so while you're with them they will feel safe and satisfied.

Extensibility

There are virtually no limits to what can be done with ASP thanks to unlimited extensibility provided via COM components. This approach, in my opinion, is a key success factor of ASP. For example, there's no way to send email using standard ASP functions but there are lots of components (both free and commercial) enabling you to do this, as well as chosing the methods and features you want implemented. Recent introduction of Java Server Pages - an ASP style scripting language developed to work in conjunction with server-side Java, shows that the approach is recognized as powerful by one of the biggest Microsoft competitors, Sun Microsystems.

Hosting

Hosting companies widely support ASP. A search on HostIndex returned 889 matches for hosting companies supporting ASP with hosting prices starting below $10. This is quite enough to find the host that meets all your needs for a reasonable price and you will be able to switch hosting companies easily if your current doesn't satisfy you.

Tools

Microsoft has two tools supporting ASP: their most popular WYSIWYG editor - FrontPage (though I would not personally recommend it for ASP editing) and Visual InterDev. Other vendors have also implemented ASP support into their products, including the popular HTML coding package HomeSite from Allaire. There's also scheduled support for ASP in upcoming versions of other widely-used code based editors, such as HotDog Pro from Sausage Software.

You Can Get a Good Job

A search for ASP on high tech job search engine dice.com returned more than 10000 matches with average salary around $70K. I think it will be hard for you to chose the best from such a quantity, but very simple to find good one.

There are of course more reasons to develop in ASP, but I hope these ten were enough to convince you that developing in ASP can make your life happier and get you to the next level of your career.

For additional information on ASP, take a look at:

    The ABC's of Active Server Pages:
    msdn.microsoft.com/workshop/server/asp/ASPover.asp

    ASP Overview:
    www.wdvl.com/Software/Tools/ASP.html

    General ASP resource sites:
    www.aspwatch.com/
    www.asptoday.com/

Source:Alan Mendelevich

Monday 21 January 2013

Final version of jQuery with IE 6, 7 and 8 support released

Final version of jQuery with IE 6, 7 and 8 support released

The final version of jQuery with support for Internet Explorer 6, 7 and 8 has been released as the development team move towards a smaller codebase for version 2.0.

jQuery 1.9 will be the last version of the popular JavaScript framework to support these browsers, referred to collectively in jQuery blog posts as ‘oldIE’.

The change was announced in June in an attempt to reduce the size of jQuery’s codebase, which has gradually increased in size over time and is now considered by some to be too large.

Removing oldIE support in the first beta of jQuery 2.0 has seen a 10% reduction in the size of its footprint, and Dave Methvin, president of the jQuery foundation, claimed that the work was “nowhere near done” in a blog post. Strangely, neither this release nor a blog post entitled “The State of jQuery 2013” make any reference to modularisation introduced in jQuery 1.8.

jQuery has long been praised for its support for older (and current) browsers with patchy implementation of vanilla JavaScript. However, this has become increasingly unimportant as oldIE’s market share continues to dwindle.

Though their numbers are undoubtedly falling, it’s difficult to say how much of the market will now be left unsupported by jQuery 2.0. NetMarketShare estimates that IE6,7 and 8 together retain a 32.88% market share, while StatCounter reports a meagre 12.29% share.

It’s far from a sudden transition, however: jQuery’s developers have pledged to support version 1.9 “as long as oldIE is a significant factor on the web”. In addition, jQuery 1.9 and 2.0 utilise an identical API, so the latter can be exchanged for the former on oldIE using conditional comments.

Though jQuery 2.1 may introduce new features incompatible with 1.9, it’s unlikely to come out before 2014 - by which point oldIE will have (hopefully) disappeared from the market. Before then, the official jQuery migrate plugin can be used to detect deprecated APIs, features or functionality still referenced within your code.

Source:Elliot Bentley

Saturday 19 January 2013

How to use Google+ APIs from ASP.NET


Samples and source code:

Are you trying to integrate Google+ with your .NET applications? Google+ provides some APIs, but the output is in JSON format. Download the .NET client library for Google+ APIs and see our examples to find out how to use them.



The data retrieved using the Google+ APIs are not strongly typed as I would expect in .NET. Instead, Google+ APIs return data in JSON format, which is a structured form of data, but not strongly typed like .NET types.

 tried couple of Google+ APIs. After couple of trial and error,  was able to call some Google+ APIs, using the WebRequest class in .NET.

Here is the code I used to call Google+ API:

    string requestString = "https://www.googleapis.com/plus/v1/people/" + _profileId + "?key=" + _apiKey;
    WebRequest objWebRequest = WebRequest.Create(requestString);
    WebResponse objWebResponse = objWebRequest.GetResponse();

    Stream objWebStream = objWebResponse.GetResponseStream();

    using (StreamReader objStreamReader = new StreamReader(objWebStream))
    {
        string result = objStreamReader.ReadToEnd();

        return result;
    }

In the above code, _profileId represents a valid Google+ profile. It does not need to be any valid profile id. This API returns only public information from any profile and so no authentication is required to call this. However, you need to pass an API Key before you can call the Google+ APIs. That is what I used in the variable _apiKey. You can get a Google+ API Key from here.

The above code returns some text data in JSON format, which is structured data.

We need to convert the data in to valid .NET types. The JavaScriptSerializer class comes in handy here. We can use this class to convert the JSON data structure to corresponding C# or VB.NET class.

Example:


JavaScriptSerializer js = new JavaScriptSerializer();
string requestString = "https://www.googleapis.com/plus/v1/people/"
                  + _profileId + "?key=" + _apiKey;
string result = GetWebData(requestString);
GPlusPerson activity = js.Deserialize(result);

GPlusActivity is a custom class created that matches its properties with the keys in the JSON structured returned by the Google+ API. Each property in the class must match with the key names in the data structure returned by the API. The JavaScriptSerializer DeSerialize call will convert the data structure in to corresponding .NET object.

example, the above API call returns the following JSON data:


{
"kind": "plus#person",
"id": "102428175534077457150",
"displayName": "Tony John",
"tagline": "Microsoft MVP, Founder of dotnetspider.com",
"gender": "male",
"aboutMe": "",
"url": "https://plus.google.com/102428175534077457150",
"image": {  "url": "https://lh3.googleusercontent.com/-wDpbQaFJFKg/
        AAAAAAAAAAI/AAAAAAAAAAA/ZQ8VOHPB1Is/photo.jpg?sz=50" },
"urls": [  {   "value": "http://www.thoughtsfromgeeks.com/member/manjaly.aspx"  }, 
       {   "value": "http://www.indiastudychannel.com/member/manjaly.aspx"  }, 
       {   "value": "http://www.dotnetspider.com/member/manjaly.aspx"  } ],
"organizations": [ {   "name": "LoneStar Informatics LLP",  
                       "title": "Owner",   "type": "work"  } ],
"placesLived": [  {  "value": "Bangalore, India"  } ]
}


Now, to match the JSON structure,  have defined the .NET class like this:

public class GPlusPerson
{
    public string kind { get; set; }
    public string id { get; set; }
    public string displayName { get; set; }
    public string tagline { get; set; }
    public string birthday { get; set; }
    public string gender { get; set; }
    public string aboutMe { get; set; }
    public string url { get; set; }
    public GImage image { get; set; }
    public Url[] urls { get; set; }
    public Organization[] organizations { get; set; }
    public PlaceLived[] placesLived { get; set; }
}

You can see that each of the key in the JSON structure has a corresponding property in the .NET class. the DeSerialize method of the JavaScriptSerializer class will map the JSON key-value pair to the corresponding .NET property.

You may notice that some of the items in JSON structure is an array of data by itself. Examples: Image, Organizations, PlacesLived. I have defined each of them as separate types (classes).

You can download the full set of classes to map each of the JSON structure for all the Google+ APIs released in October 2011 (version 1). I have included some samples and basic documentation on how to call each of the Google+ APIs.