Tuesday, August 28, 2012

Passing values from Parent to Child and vice versa using popup modal dialog

This code is very useful to transfer data from parent page to child page using popup modal dialog. Also this code return values from child to parent.

Parent HTML:-


<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <script type="text/javascript">
        function UpdateFields(newFore, newSur) {
            var forename = document.getElementById("forename");
            var surname = document.getElementById("surname");
            forename.value = newFore;
            surname.value = newSur;
        }

        function ShowModal() {
            var forename = document.getElementById("forename");
            var surname = document.getElementById("surname");

            var sharedObject = {};
            sharedObject.forename = forename.value;
            sharedObject.surname = surname.value;

            if (window.showModalDialog) {
                var retValue = showModalDialog("childpage.htm", sharedObject, "dialogWidth:200px; dialogHeight:200px; dialogLeft:300px;");
                if (retValue) {
                    UpdateFields(retValue.forename, retValue.surname);
                }
            }
            else {
                // similar functionality in Opera, but its not modal!
                var modal = window.open("childpage.htm", null, "width=200,height=200,left=300,modal=yes,alwaysRaised=yes", null);
                modal.dialogArguments = sharedObject;
            }
        }
    </script>
</head>
<body>
    Forename: <input type="text" id="forename" value="Alan"/><br />
    Surname: <input type="text" id="surname" value="Smith"/>
    <br /><br />
    <button onclick="ShowModal()">Edit fields with a modal dialog!</button>
</body>
</html>



Child HTML:-

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>Modal dialog sample</title>
    <script type="text/javascript">
        function Init() {
            var sharedObject = window.dialogArguments;

            var forename = document.getElementById("forename");
            var surname = document.getElementById("surname");
            forename.value = sharedObject.forename;
            surname.value = sharedObject.surname;
        }

        function OnOK() {
            var forename = document.getElementById("forename");
            var surname = document.getElementById("surname");

            if (window.showModalDialog) {
                var sharedObject = {};
                sharedObject.forename = forename.value;
                sharedObject.surname = surname.value;

                window.returnValue = sharedObject;
            }
            else {
                // if not modal, we cannot use the returnValue property, we need to update the opener window
                window.opener.UpdateFields(forename.value, surname.value);
            }
            window.close();
        }

        function OnCancel() {
            window.close();
        }
    </script>
<body onload="Init ();">
    Forename: <input type="text" id="forename"/><br/>
    Surname: <input type="text" id="surname"/>
    <br/><br/>
    <button onclick="OnOK()">OK</button> <button onclick="OnCancel()">Cancel</button>
</body>
</html>

Friday, August 24, 2012

Publishing Web application to IIS using Visual studio


Basic points to remember when publishing

Publishing
==========
Right click project
Click Publish
now do the following steps

publish method - web deploy
service url = localhost
site/application = Default Web Site

click publish and thats all

Note: To do this you should be administrator, you can open VS as Run as Administrator by right clicking VS


Configuring IIS
===============

Click Windowkey+R to open run
type inetmgr to open iis
now left side connections open upto  domain->Sites->Default Web Site
now you can see your project
if project icon showing as folder then "convert to application" by right click
right click your project Manage application->browse (or simply right side actions browse)
now your URL will open in browser
now you type your page name ex:- http://localhost:XXXX/applicationname/default.aspx
if you found any error then check in web config & application pool

Application pool settings
=========================
click your project in Default Web Site
Click Basic settings at right side actions
Check application pool is your .net framework same or click select & choose your framwork (ex:-.net framework v4.0.30319)

Web Config Settings
===================
you can check in two ways
before publish check web config and publish
or right click your project in Default web site and click Explore
now you can edit your web config (if not editable uncheck the readonly field from properties)

I will update the sample images as well soon. If you want to add points more you can comment me..
Balajiprasad

Monday, August 20, 2012

Understanding JSON


What does it stand for?

JavaScript Object Notation.
[A ridiculous name. It should be called Lightweight Ecmascript Object Notation, or 'LEON' for short. ;-)]

And what does that mean?

JSON is a syntax for passing around objects that contain name/value pairs, arrays and other objects.
Here's a tiny scrap of JSON:
{"skillz": {
 "web":[
  {"name": "html", 
   "years": "5"
  },
  {"name": "css", 
   "years": "3"
  }],
 "database":[
  {"name": "sql", 
   "years": "7"
  }]
}}
You got that? So you'd recognise some JSON if you saw it now? Basically:

Squiggles, Squares, Colons and Commas

  1. Squiggly brackets act as 'containers'
  2. Square brackets holds arrays
  3. Names and values are separated by a colon.
  4. Array elements are separated by commas

Think 'XML with Anorexia'

(Or if you're as old as me, think "'.INI' files, with hierarchy.")
(Or if you're a smug lisp weenie, think "S-expressions", and just be smug.)

JSON is like XML because:

  1. They are both 'self-describing' meaning that values are named, and thus 'human readable'
  2. Both are hierarchical. (i.e. You can have values within values.)
  3. Both can be parsed and used by lots of programming languages
  4. Both can be passed around using AJAX (i.e. httpWebRequest)

JSON is UNlike XML because:

  1. XML uses angle brackets, with a tag name at the start and end of an element: JSON uses squiggly brackets with the name only at the beginning of the element.
  2. JSON is less verbose so it's definitely quicker for humans to write, and probably quicker for us to read.
  3. JSON can be parsed trivially using the eval() procedure in JavaScript
  4. JSON includes arrays {where each element doesn't have a name of its own}
  5. In XML you can use any name you want for an element, in JSON you can't use reserved words from javascript

But Why? What's good about it?

When you're writing ajax stuff, if you use JSON, then you avoid hand-writing xml. This is quicker.
Again, when you're writing ajax stuff, which looks easier? the XML approach or the JSON approach:

The XML approach:

  1. bring back an XML document
  2. loop through it, extracting values from it
  3. do something with those values, etc,

versus

The JSON approach:

  1. bring back a JSON string.
  2. 'eval' the JSON

So this is Object-Oriented huh?

Nah, not strictly.
JSON is about as object oriented as VB6. It provides a nice encapsulation technique, that you can use for separating values and functions out, but it doesn't provide anything inheritence, polymorphism, interfaces, or OO goodness like that.
It is certainly a step in the right direction though, making javascript easier to maintain, share and reuse.
Thomas Frank wrote a nifty little javascript library called classyJSON for adding inheritance and scoping capabilities to JSON code.

And it's just for the client-side right?

Yes and no. On the server-side you can easily serialize/deserialize your objects to/from JSON. For .net programmers you can use libraries like Json.net to do this automatically for you (using reflection i assume), or you can generate your own custom code to perform it even faster on a case by case basis.

Here is an example of JSON data:
{
     "firstName": "John",
     "lastName": "Smith",
     "address": {
         "streetAddress": "21 2nd Street",
         "city": "New York",
         "state": "NY",
         "postalCode": 10021
     },
     "phoneNumbers": [
         "212 555-1234",
         "646 555-4567"
     ]
 }

JSON in JavaScript

When working with JSON and JavaScript, you may be tempted to use the eval function to evaluate the result returned in the callback, but this is not suggested due to security reasons (malicious data can be sent from the server to the client and then evaled in the client script with harmful effects).

Therefore, one must always try to use Crockford's script that checks for a valid JSON before evaluating it. Link to the script explanation is found here and here is a direct link to the js file.
Example on how to use the JSON Parser (with the json from the above code snippet):
//The callback function that will be executed once data is received from the server
var callback = function (result) {
    var johnny = JSON.parse(result);
    //Now, the variable 'johnny' is an object that contains all of the properties 
    //from the above code snippet (the json example)
    alert(johnny.firstName + ' ' + johnny.lastName); //Will alert 'John Smith'
};
The JSON Parser also offers another very useful method, stringify. This method accepts a JavaScript object as a parameter, and outputs back a string with JSON format. This is useful for when you want to send data back to the server:
var anObject = {name: "Andreas", surname : "Grech", age : 20};
var jsonFormat = JSON.stringify(anObject);
//The above method will output this: {"name":"Andreas","surname":"Grech","age":20}
The above two methods (parse and stringify) also take a second parameter, which is a function that will be called for every key and value at every level of the final result, and each value will be replaced by result of your inputted function. (More on this here)
Btw, for all of you out there who think JSON is just for JavaScript, check out this post that explains and confirms otherwise.

Thursday, August 16, 2012

Get public key token of a .Net assembly


Updating the application configuration file with the latest version and the correct public key token is important for a .Net application to execute successfully. One can look up the public key token of a .Net assembly in one of the following ways.
1. Using Reflector:
Open the assembly using .Net Reflector [1]. Click on the assembly name and Reflector will show the details of the assembly in the pane to the bottom of the application like in the example below:

2. Using Sn.exe
Launch the .Net command prompt and execute the following command. Keep in mind that the arguments are case sensitive. Check out the following example for the usage:
1Sn.exe - Tp <assemblyname>

Watch out for the following error in case of a incorrect command line argument: Failed to convert key to token — The public key for assembly ‘(null)’ was invalid.

Adding System.Web dll reference to other class libraries


Follow the steps:
  1. Project properties
  2. Click on the Tab Application
  3. In the "Target Framework" drop down, be sure to select ".NET Framework 4" and not the one with the suffix "Client Profile"
for more information:
The reason you can't find the System.Web is the first sentence:
The .NET Framework 4 Client Profile is a subset of the .NET Framework 4
So, some of the functionality doesn't exists in the client profile, like System.Web.

Tuesday, August 14, 2012

A basic introduction to the Unity Application Block


Introduction

With its latest release, the Enterprise Library from Microsoft introduces a new component named Unity. This application block provides an easy path to implement the IoC pattern, and consequently the Dependency Injection pattern.
All the references for the Enterprise Library documentation can be found at the end of the article.

Background

Inversion of Control and Dependency Injection are the key points to understand how Unity works and the benefits of including it in our projects. If you want a deep dive on these patterns: http://martinfowler.com/articles/injection.html.
The scope of this article is writing code that is loosely coupled. Let's examine the following DummyLogger class:
public class DummyLogger
{
    private IWriter _selectedWriter;

    public DummyLogger()
    {
        //The container class is in charge for the initialization of the interface. 
        //the result is a strong dependency between the two objects
        _selectedWriter = new ConsoleWriter();
    }

    public void WriteOutput(string msg)
    {
        _selectedWriter.Write(msg);
    }
}
The first thing that comes to mind to break the relationship between the two objects is to delegate the creation of the class member to someone else:
public class DummyLogger
{
    private IWriter _selectedWriter;

    public void SetWriter(IWriter writer)
    {
        _selectedWriter = writer;
    }

    public void WriteOutput(string msg)
    {
        _selectedWriter.Write(msg);
    }
}
Nothing new until now. This can be interpreted as a trivial implementation of the IoC pattern. The contained object is no more controlled by its container class.
But what if we don't care about the real implementation of the IWriter interface ? Here's where Unity and Dependency Injection comes. The concrete implementation of the class member will be "injected" by Unity depending on its configuration. The first thing we need to do is expose the class/interface with its get/set methods and mark it with the [Dependency] attribute to make it visible to the application block.
public class DummyLogger
{

    private IWriter _selectedWriter;

    public void SetWriter(IWriter writer)
    {
        _selectedWriter = writer;
    }

    public void WriteOutput(string msg)
    {
        _selectedWriter.Write(msg);
    }
}
Behind the scenes, each class/interface decorated with the [Dependency] attribute will be created according to the Unity container's configuration. This can be done programmatically or via the .config file.
<type type="George2giga.TestUnity.Library.IWriter,George2giga.TestUnity.Library" 
   mapTo="George2giga.TestUnity.Library.ConsoleWriter,George2giga.TestUnity.Library" />

Using the code

Given below is a basic implementation of Unity. Here's the class diagram of our sample application:
IWriter, the interface is shared between the logging providers:
public interface IWriter
{
    void Write(string msg);
}
Of the three logging providers, depending on the configuration, one of them will be "injected" to create the IWriterinstance:
public class ConsoleWriter : IWriter
{
    #region IWriter Members

    public void Write(string msg)
    {
        Console.WriteLine(msg);
        Console.ReadLine();
    }

    #endregion
}

public class FileWriter : IWriter
{
    #region IWriter Members

    public void Write(string msg)
    {
        using (StreamWriter streamWriter = 
               new StreamWriter("c:\\TestUnity.txt",true))
        {
            streamWriter.WriteLine(msg);
        }
    }
    #endregion
}

public class EventViewerWriter : IWriter
{
    #region IWriter Members

    public void Write(string msg)
    {
        EventLog.WriteEntry("TestUnity", msg, 
                            EventLogEntryType.Information);
    }

    #endregion
}
The logging class contains the dependency property:
public class DummyLogger
{
    private IWriter selectedWriter;

    [Dependency]
    public IWriter SelectedWriter
    {
        get { return selectedWriter; }
        set { selectedWriter = value; }
    }

    public void WriteOutput(string msg)
    {
        selectedWriter.Write(msg);
    }
}
The entry point of the application is responsible for the initialization of the Unity container:
class Program
{
    static void Main(string[] args)
    {
        IUnityContainer container = new UnityContainer();
        UnityConfigurationSection section = 
          (UnityConfigurationSection)ConfigurationManager.GetSection("unity");
        section.Containers.Default.Configure(container);
        DummyLogger dummyLogger = container.Resolve<DummyLogger>();
        dummyLogger.SelectedWriter.Write("Hello");}
}
Here is the App.config:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <configSections>
      <section name="unity" 
         type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, 
               Microsoft.Practices.Unity.Configuration" />
    </configSections>
    <unity>
      <containers>
        <container>
          <types>
            <type 
               type="George2giga.TestUnity.Library.IWriter,George2giga.TestUnity.Library" 
               mapTo="George2giga.TestUnity.Library.ConsoleWriter,
                      George2giga.TestUnity.Library" />
          </types>
        </container>
      </containers>
    </unity>
</configuration>