Total Pageviews

Tuesday, May 21, 2013

How to give permissions to a folder pro-grammatically using C# in Windows

Below are the code which gives full control to a folder programmatically


 var dInfo = new DirectoryInfo(@"C:\\MyFolder");
            DirectorySecurity dSecurity = dInfo.GetAccessControl();
            dSecurity.AddAccessRule(new FileSystemAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), FileSystemRights.FullControl, InheritanceFlags.ObjectInherit | InheritanceFlags.ContainerInherit, PropagationFlags.NoPropagateInherit, AccessControlType.Allow));
            dInfo.SetAccessControl(dSecurity);


Enjoy reading

Wednesday, May 1, 2013

Call Restful Service using HttpWebRequest and Post data

Introduction
        This article helps  you call Restful service using HttpWebRequest and Post Data to a particular service.

Our Restful Service
Contract

[ServiceContract]
    public interface IOrionChatService
    {


 [WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare,ResponseFormat = WebMessageFormat.Json, UriTemplate = "/PushNotification")]
        [OperationContract]
        void MyServiceMethod(PostedInformation postedInformations);
}

Service Implementation
  public void MyServiceMethod(PostedInformation postedInformations)
{
//do implemention code here
}


DataContract

  [DataContract]
    public class PostedInformation 
    {
        [DataMember]
        public List<string> To { get; set; }
        [DataMember]
        public string SenderEmail { get; set; }
        [DataMember]
        public string Subject { get; set; }
        [DataMember]
        public string SenderFullName { get; set; }

    }


Calling our created Restful service from a Console application using HttpWebRequest

//Create a  new object of the class that we want to post

  PostedInformation postedInformations = new PostedInformation ()
            {
               SenderEmail = "aaa@bbb.com",
               SenderFullName = "test",
                To = new List<string>() { "ccc@eee.com" }
            };
//Serialize the postedInformations to jSon using Newtonsoft.json. You can download dll from here //http://json.codeplex.com/



 var dataToSend = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(postedInformations ));
//Passyour service url to the create method
            var req = 
HttpWebRequest.Create("http://localhost/MyServer/YourServiceName.svc/MyServiceMethod");
            req.ContentType = "application/json";
            req.ContentLength = dataToSend.Length;
            req.Method = "POST";
            req.GetRequestStream().Write(dataToSend, 0, dataToSend.Length);
            var response = req.GetResponse();

Enjoy......


Friday, March 22, 2013

Post data to the action result in jqGrid and ASP.NET MVC

Here when a dropdown change the filter value (what we are selected ) will pass to the action result

Script

 $(".selectRequestType").change(function () {
                 $('#jqgRequests').setGridParam({ postData: { FilterValue: $(this).val() } }).trigger('reloadGrid', [{ page: 1 }]);
            });

Action Result

 [AcceptVerbs(HttpVerbs.Post)]
            public JsonResult LoadRequest(JqGridRequest request, PostDataViewModel postData)
            {
           }

 public class PostDataViewModel
    {
       public string FilterValue { get; set; }
    }


Saturday, March 16, 2013

Html.Partial,Html.RenderPartial,Html.Action and Html.RenderAction in ASP.NET MVC

Html.Partial and Html.RenderPartial
        The Html.Partial helpers renders a partial view in to string.Typically, a partial view contains reusable markup you want to render from inside multiple different views. Partial has four overloads


public void Partial(string partialViewName);
public void Partial(string partialViewName, object model);
public void Partial(string partialViewName, ViewDataDictionary viewData);
public void Partial(string partialViewName, object model,
ViewDataDictionary viewData);
Example : 
@Html.Partial("MyPartial")    

The RenderPartial  is similar to Partial, but RenderPartial writes directly to the response
output stream instead of returning a string. For this reason, you must place RenderPartial inside
a code block instead of a code expression
Example : 
@{Html.RenderPartial("MyRenderPartial");}
So, which should you use, Partial or RenderPartial
            In general, you should prefer Partial to RenderPartial because Partial is more convenient (you don’t have to wrap the call in a code block with curly braces). However, RenderPartial may result in better performance because it writes directly to the response stream.
Html.Action and Html.RenderAction
         Html.Action and Html.RenderAction are similar to Partial and RenderPartial.Action  executes a separate controller action and display the results.the only difference between Action and RenderAction is that RenderAction writes directly to the response.

Example :
      Imagine you are using the following controller

public class ActionDemoController : Controller {
public ActionResult Index() {
return View();
}
[ChildActionOnly]
public ActionResult DisplayMenu() {
var menu = GetMenuFromSomewhere();
return PartialView(menu);
}
}

The Menu action builds a menu model and returns a partial view with just the menu:
@model Menu
<ul>
@foreach (var item in Model.MenuItem) {
<li>@item.Text</li>
}
</ul>
In your Index.cshtml view, you can now call into the Menu action to display the menu:
<html>
<head><title>Index with Menu</title></head>

<body>
@Html.Action("DisplayMenu")
<h1>Welcome to the Index View</h1>
</body>
</html>


       Notice that the Menu action is marked with a ChildActionOnlyAttribute. The attribute prevents the runtime from invoking the action directly via a URL. Instead, only a call to Action or RenderAction can invoke a child action. The ChildActionOnlyAttribute isn’t required, but is generally recommended for child actions.

Passing values to Action
       Sometimes you want to pass parameters in to the action.

Example:

[ChildActionOnly]
public ActionResult Menu(MenuParameters param) {
return PartialView(
param
);
}


@Html.Action("Menu", new {
options = new 

MenuParameters 
{ Width=400, Height=500 } })










Load Partial View as Partial View Result using Ajax in ASP.NET MVC

            In ASP.NET MVC we can return a Partial View in the form of PartialViewResult using the PartialView method.
           The following example shows Partial update scenarios using Ajax.Using jQuery to load the contents of a PartailView in to the current view using an Ajax call. In this example i have load a simple grid using Ajax.
           Controller and Action Result

 public class PartialController : Controller
    {
        //
        // GET: /Partial/

        public ActionResult GetPartialResult()
        {
            var list = new List<Album>
                           {
                               new Album {Title = "Album1"},
                                new Album {Title = "Album2"},
                                 new Album {Title = "Album3"},
                                  new Album {Title = "Album4"}
                           };
            return PartialView(list);
        }

    }

 public class Album
    {
        public string Title { get; set; }
    }


Right click the ActionResult and Create a PartialView like below

@model IEnumerable<Mvc4Demos.Controllers.Album>

<p>
    @Html.ActionLink("Create New", "Create")
</p>
<table>
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.Title)
        </th>
        <th></th>
    </tr>

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.Title)
        </td>
    </tr>
}

</table>

Here from another view when a button click load the PartialViewResult by using Ajax and Append in to a Result div


<script type="text/javascript">
    $(document).ready(function () {
        $('#btn').click(function () {
            $('#result').load('/Partial/GetPartialResult');
        });
    });

</script>


<input type="button" id="btn" value="PartialExample"/>
<div id="result"></div>


Sunday, March 3, 2013

jQuery Type Testing Function

Type testing function

  • Determine the type of an object
  • Useful for optional parameters &amp; validation
Example
             In this example  isNumeric() and isFunction() are used as Type testing function
   
   <head>
    <title></title>
    <script src="script/jquery-1.7.1.js" type="text/javascript"></script>

</head>
<body>
    <script type="text/javascript">
        function callAnotherFunction(arg1,arg2,arg3) {
            var times = $.isNumeric(arg1) ? arg1 : 3;
            var delay = $.isNumeric(arg2) ? arg2 : 1000;
            var functiontocall = $.isFunction(arg1) ? arg1 : $.isFunction(arg2) ? arg2 : arg3;
            var i = 0;
            (function loopIt() {

                i++;
                functiontocall();
                if(i<times) {
                    setTimeout(loopIt, delay);
                }
            })();
        }        
   

        function functionToCall() {
            $('#output').append("<br/>fuction called");
        }

        $(document).ready(function () {
            callAnotherFunction(3, 500, functionToCall);
        });
               
    </script>
    <div id="output"></div>
</body>
</html>

   
   
Output
fuction called
fuction called
fuction called

Monday, December 10, 2012

Single Responsibility Principle



            In this context a responsibility is considered to be one reason to change. This principle states that if we have 2 reasons to change for a class, we have to split the functionality in two classes. Each class will handle only one responsibility and on future if we need to make one change we are going to make it in the class which handle it. When we need to make a change in a class having more responsibilities the change might affect the other functionality of the classes. The Single Responsibility Principle is a simple and intuitive principle, but in practice it is sometimes hard to get it right.
Intent
A class should have only one reason to change.
Example
            Let's assume we need an object to keep an email message. We are going to use the IEmail interface from the below sample. At the first sight everything looks just fine. At a closer look we can see that our IEmail interface and Email class have 2 responsibilities (reasons to change). One would be the use of the class in some email protocols such as pop3 or imap. If other protocols must be supported the objects should be serialized in another manner and code should be added to support new protocols. Another one would be for the Content field. Even if content is a string maybe we want in the future to support HTML or other formats.
If we keep only one class, each change for a responsibility might affect the other one:
Ø  Adding a new protocol will create the need to add code for parsing and serializing the content for each type of field.
Ø  Adding a new content type (like html) make us to add code for each protocol implemented.
// single responsibility principle - bad example
interface IEmail {
            public void setSender(String sender);
            public void setReceiver(String receiver);
            public void setContent(String content);
}
class Email implements IEmail {
            public void setSender(String sender) {// set sender; }
            public void setReceiver(String receiver) {// set receiver; }
              public void setContent(String content) {// set content; }
}
We can create a new interface and class called IContent and Content to split the responsibilities. Having only one responsibility for each class give us a more flexible design:
Ø  adding a new protocol causes changes only in the Email class.
Ø  adding a new type of content supported causes changes only in Content class.
// single responsibility principle - good example
interface IEmail {
            public void setSender(String sender);
            public void setReceiver(String receiver);
            public void setContent(IContent content);
}
interface Content {
            public String getAsString(); // used for serialization
}
class Email implements IEmail {
            public void setSender(String sender) {// set sender; }
            public void setReceiver(String receiver) {// set receiver; }
            public void setContent(IContent content) {// set content; }
}
Conclusion
            The Single Responsibility Principle represents a good way of identifying classes during the design phase of an application and it reminds you to think of all the ways a class can evolve. A good separation of responsibilities is done only when the full picture of how the application should work is well understand.

Open Close Principle


          The Open Close Principle states that the design and writing of the code should be done in a way that new functionality should be added with minimum changes in the existing code. The design should be done in a way to allow the adding of new functionality as new classes, keeping as much as possible existing code unchanged.
Intent
Software entities like classes, modules and functions should be open for extension but closed for modifications.

Open to Extension

New behavior is added in the future

Closed to Modification

Changed to source or binary code are not required
Example
Below is an example which violates the Open Close Principle. It implements a graphic editor which handles the drawing of different shapes. It's obviously that it does not follow the Open Close Principle since the GraphicEditor class has to be modified for every new shape class that has to be added. There are several disadvantages:
•        for each new shape added the unit testing of the GraphicEditor should be redone.
•        when a new type of shape is added the time for adding it will be high since the developer who add it should understand the logic of the GraphicEditor.
•        adding a new shape might affect the existing functionality in an undesired way, even if the new shape works perfectly
// Open-Close Principle - Bad example
 class GraphicEditor {
            public void drawShape(Shape s) {
                        if (s.m_type==1)
                                    drawRectangle(s);
                        else if (s.m_type==2)
                                    drawCircle(s);
            }
            public void drawCircle(Circle r) {....}
            public void drawRectangle(Rectangle r) {....}
 }

 class Shape {
            int m_type;
 }
 class Rectangle extends Shape {
            Rectangle() {
                        super.m_type=1;
            }
 }
 class Circle extends Shape {
            Circle() {
                        super.m_type=2;
            }
 }
// Open-Close Principle - Good example
 class GraphicEditor {
            public void drawShape(Shape s) {
                        s.draw();
            }
 }

 class Shape {
            abstract void draw();
 }

 class Rectangle extends Shape  {
            public void draw() {
                        // draw the rectangle
            }
 }
Conclusion
            Like every principle OCP is only a principle. Making a flexible design involves additional time and effort spent for it and it introduce new level of abstraction increasing the complexity of the code. So this principle should be applied in those area which are most likely to be changed.

Tuesday, December 4, 2012

How Requests Are Processed by the Thread Pool In IIS

On the web server, the .NET Framework maintains a pool of threads that are used to service ASP.NET requests. When a request arrives, a thread from the pool is dispatched to process that request. If the request is processed synchronously, the thread that processes the request is busy while the request is being processed, and that thread cannot service another request.



This might not be a problem, because the thread pool can be made large enough to accommodate many busy threads. However, the number of threads in the thread pool is limited (the default maximum for .NET 4.5 is 5,000). In large applications with high concurrency of  long-running requests, all available threads might be busy. This condition is known as thread starvation. When this condition is reached, the web server queues requests. If the request queue becomes full, the web server rejects requests with an HTTP 503 status (Server Too Busy). The CLR thread pool has limitations on new thread injections. If concurrency is bursty (that is, your web site can suddenly get a large number of requests) and  all available request threads are busy because of backend calls with  high latency, the limited thread injection rate can make your application respond very poorly.  Additionally, each new thread added to the thread pool has overhead (such as 1 MB of stack memory). A web application  using synchronous methods to service high latency calls where the thread pool grows to the .NET 4.5 default maximum  of 5, 000 threads would consume approximately 5 GB more memory than an application able the service the same requests using asynchronous methods and only 50 threads. When you’re doing asynchronous work, you’re not always using a thread. For example, when you make an asynchronous web service request, ASP.NET will not be using any threads between the async method call and the await.  Using the thread pool to service requests with high latency can lead to a large memory footprint and poor utilization of the server hardware.

Monday, December 3, 2012

Globalization(Do and Don't) In .NET


       String Comparison
Do
 string str1 = "Apple"; string str2 = "Æble"; int result1 = String.Compare(str1, str2, CultureInfo.InvariantCulture,                                                  CompareOptions.IgnoreCase);

Don't
  string str1 = "Apple";
  string str2 = "Æble";
  int result1 = String.Compare(str1, str2);

 Do

   const string input = "interesting";
   bool result =input.Equals("INTERESTING",            StringComparison.InvariantCultureIgnoreCase);

 Don't

    const string input = "interesting";
    bool comparison = input.ToUpper() == "INTERESTING";
               
 Do            
    string newString =     s.ToUpper(CultureInfo.InvariantCulture);

 Don't      

    string newString = s.ToUpper();
    
                String Sorting
 Do
     StringComparer invCmp = StringComparer.InvariantCulture;
     var str=new List<string> {"a", "b", "c"};
     str.Sort(invCmp);

 Don't 

     var str=new List<string> {"a", "b", "c"};
     str.Sort();


Number Formatting
 Do
     int i = 100;
     string res = i.ToString(CultureInfo.InvariantCulture);
     string res2 = Convert.ToString(CultureInfo.InvariantCulture);

 Don't

      int i = 100;
      string res = i.ToString();
      string res2 = Convert.ToString();

  Do

       double number = 123.456;
       string convertToString =    Convert.ToString(number,  CultureInfo.InvariantCulture);
       string numberToString = number.ToString(CultureInfo.InvariantCulture);
       string stringFormat = String.Format(CultureInfo.InvariantCulture, "{0}",          number);
 Don't              
        double number = 123.456;
        string convertToString = Convert.ToString(number);
        string numberToString = number.ToString();
        string stringFormat = String.Format("{0}", number);
                                               
Calendar Differences
Date Formatting

  Do
        string s1 = "10/31/2012";
       DateTime date = DateTime.Parse("10 / 31 /  2012",  CultureInfo . InvariantCulture);     
       
 Don't
        string s1 = "10/31/2012";
        DateTime date = DateTime.Parse("10 / 31 / 2012");

 Do

        string datenew = Convert.ToDateTime("10/31/2012", CultureInfo.InvariantCulture).ToString();           

Don't
        string datenew = Convert.ToDateTime("10/31/2012").ToString();                 
 Do
        DateTime datenew = Convert.ToDateTime("10/31/2012", CultureInfo.InvariantCulture);     
       
 Don't
         DateTime datenew = Convert.ToDateTime("10/31/2012");


Time Formatting

             The easiest and most efficient way of doing time formatting in the .NET world is to take advantage of theDateTime structure that provides methods such as DateTime.ToString and DateTime.Parse. These methods allow you to perform culture-sensitive operations on a DateTime object.
 Do
      string conv = DateTime.Now.ToShortTimeString();
      DateTime newDate = DateTime.Parse(conv, CultureInfo.InvariantCulture);
Don't
      string conv = DateTime.Now.ToShortTimeString();
      DateTime newDate = DateTime.Parse(conv);


Currency Formatting

     Do
      string conv2 = "12,34,56,789.00";
      decimal newd = Convert.ToDecimal(conv2,CultureInfo.InvariantCulture);
    Don't
       string conv2 = "12,34,56,789.00";
       decimal newd = Convert.ToDecimal(conv2);

Read text file using Powershell


Run the following command in powershell. You get the contents from the text file in to the variable $b
$b = get-content -path C:\ValidatorReport\status.txt

Sunday, February 6, 2011

Windows Programming in C++ (Part2)

                                 Painting the window 
                Previous Documentation we study about WindowProcedure.In this Documentation explain about Painting the window.
You have created your window.Now you want to show something inside in it this is called Painting the window.
                  Sometimes your program will initiate painting to update the appearance of the window. At
other times, the operating system will notify you that you must repaint a portion of the window. When this
occurs, the operating system sends the window a WM_PAINT message. The portion of the window that must
be painted is called the update region.
                The first time a window is shown, the entire client area of the window must be painted. Therefore, you will always receive at least one WM_PAINT message when you show a window.
                             Illustration showing the update region of a window
                     You are only responsible for painting the client area. The surrounding frame, including the title bar, is automatically painted by the operating system. After you finish painting the client area, you clear the update region, which tells the operating system that it does not need to send another WM_PAINT message until something changes.
                  Now suppose the user moves another window so that it obscures a portion of your window.When the obscured portion becomes visible again, that portion is added to the update region, and your window receives another WM_PAINT message.
              Illustration showing how the update region changes when two windows overlap
                      The update region also changes if the user stretches the window. In the following diagram, the user stretches the window to the right. The newly exposed area on the right side of the window is added to the update region:
              Illustration showing how the update region changes when a window is resized
                     In our first example program, the painting routine is very simple. It just fills the entire client area with a solid color. Still, this example is enough to demonstrate some of the important concepts.
--------------------------------------------------------------------------------------------------
switch (uMsg)
{
case WM_PAINT:
{
PAINTSTRUCT ps;
HDC hdc = BeginPaint(hwnd, &ps);
// All painting occurs here, between BeginPaint and EndPaint.
FillRect(hdc, &ps.rcPaint, (HBRUSH) (COLOR_WINDOW+1));
EndPaint(hwnd, &ps);
}
return 0;
}
---------------------------------------------------------------------------------------------------- 

                 Start the painting operation by calling the BeginPaint function. This function fills in the PAINTSTRUCT structure with information on the repaint request. The current update region is given in the rcPaint member of PAINTSTRUCT. This update region is defined relative to the client area:
                            Illustration showing the origin of the client area
                   In your painting code, you have two basic options:
• Paint the entire client area, regardless of the size of the update region. Anything that falls outside of the update region is clipped. That is, the operating system ignores it.
• Optimize by painting just the portion of the window inside the update region.
                  If you always paint the entire client area, the code will be simpler. If you have complicated painting logic, however, it can be more efficient to skip the areas outside of the update region.
                     The following line of code fills the update region with a single color, using the system-defined window background color (COLOR_WINDOW). The actual color indicated by COLOR_WINDOW depends on the user's current color scheme.
                               FillRect(hdc, &ps.rcPaint, (HBRUSH) (COLOR_WINDOW+1));
                       The details of FillRect are not important for this example, but the second parameter gives th coordinates of the rectangle to fill. In this case, we pass in the entire update region (the rcPaint member of PAINTSTRUCT). On the first WM_PAINT message, the entire client area needs to be painted, so rcPaint will contain the entire client area. On subsequent WM_PAINT messages, rcPaint might contain a smaller rectangle.
                       The FillRect function is part of the Graphics Device Interface (GDI), which has powered Windows graphics for a very long time. In Windows 7, Microsoft introduced a new graphics engine, named Direct2D, which supports high-performance graphics operations, such as hardware acceleration. Direct2D is also available for Windows Vista through the Platform Update for Windows Vista and for Windows Server 2008 through the Platform Update for Windows Server 2008. (GDI is still fully supported.) After you are done painting, call the EndPaint function. This function clears the update region,
which signals to Windows that the window has completed painting itself.


  


Tuesday, February 1, 2011

Windows Programming in C++(Part3)


                  
          Previous Documentation we study how we can create a window,paint the window and Close the window.In this documentation explain about detail.
Window Messages
A GUI application must respond to events from the user and from the operating system.
  •  Event from the User include all of the ways that someone can interact with your program      Eg:MouseClick,KeyStrokes,TouchScreen,Gestures etc..
  •  Event from the OS include anything "outside" of the program that can affect how the program behaves.Eg : user might plug in a new hardware device, or Windows might enter a lower-power state (sleep or hibernate).
           These events can occur at any time while the program is running, in almost any order. How do you structure a program whose flow of execution cannot be predicted in advance?
          To solve this problem, Windows uses a message-passing model. The operating system communicates with your application window by passing messages to it. A message is simply a numeric code that designates a particular event. For example, if the user presses the left mouse button, the window receives
a message with the following message code.
--------------------------------------------------------------------------------------------------
#define WM_LBUTTONDOWN 0x0201
--------------------------------------------------------------------------------------------------
           Some messages have data associated with them. For example, the WM_LBUTTONDOWN
message includes the x-coordinate and y-coordinate of the mouse cursor. 
          To pass a message to a window, the operating system calls the window procedure registered for that window. (And now you know what the window procedure is for.)
The Message Loop
          An application will receive thousands of messages while it runs. (Consider that every keystrokeand mouse-button click generates a message.) Furthermore, an application can have several windows, each with its own window procedure. How does the program receive all of these messages and deliver them to the right window procedure? The application needs a loop to get the messages and distpatch them to the correct
windows.
         For each thread that creates a window, the operating system creates a queue for windowmessages. This queue holds messages for all of the windows that are created on that thread. The queue itself is hidden from your progam. You can't manipulate the queue directly, but you can pull a message from the queue
by calling the GetMessage function.
--------------------------------------------------------------------------------------------------
MSG msg;
GetMessage(&msg, NULL, 0, 0);
--------------------------------------------------------------------------------------------------
         This function removes the first message from the head of the queue. If the queue is empty, the function blocks until another message is queued. The fact that GetMessage blocks will not make your program unresponsive. If there are no messages, there is nothing for the program to do. If you need to perform background processing, you can create additional threads that continue to run while GetMessage waits for another message.
Parameter Definition of GetMessage function
         The first parameter of GetMessage is the address of a MSG structure. If the function succeeds,it fills in the MSG structure with information about the message, including the target window and the message code. The other three parameters give you the ability to filter which messages you get from the queue. In almost all cases, you will set these parameters to zero.
         Although the MSG structure contains information about the message, you will almost never examine this structure directly. Instead, you will pass it directly to two other functions.
----------------------------------------------------------------------------------------------------
TranslateMessage(&msg);
DispatchMessage(&msg);
----------------------------------------------------------------------------------------------------
          The TranslateMessage function is related to keyboard input; it translates keystrokes (key down, key up) into characters. You don't really need to know how this function works; just remember to call it right before DispatchMessage..
          The DispatchMessage function tells the operating system to call the window procedure of the window that is the target of the message. In other words, the operating system looks up the window handle in its table of windows, finds the function pointer associated with the window, and invokes the function.For example, suppose the user presses the left mouse button. This causes a chain of events:
1. The operating system places a WM_LBUTTONDOWN message on the message queue.
2. Your program calls the GetMessage function.
3. GetMessage pulls the WM_LBUTTONDOWN message from the queue and fills in the MSG structure.
4. Your program calls the TranslateMessage and DispatchMessage functions.
5. Inside DispatchMessage, the operating system calls your window procedure.
6. Your window procedure can either respond to the message or ignore it.
           When the window procedure returns, it returns back to DispatchMessage, which returns to the message loop for the next message. As long as your program is running, messages will continue to arrive on the queue. Therefore, you need a loop that continually pulls messages from the queue and dispatches them. You can think of the loop as doing the following:
--------------------------------------------------------------------------------------------------
// WARNING: Don't actually write your loop this way.
while (1)
{
GetMessage(&msg, NULL, 0, 0);
TranslateMessage(&msg);
DispatchMessage(&msg);
}
--------------------------------------------------------------------------------------------------
            As written, of course, this loop would never end. That's where the return value for the GetMessage function comes in. Normally, GetMessage returns a non-zero value. Whenever you want to quit the application and break out of the message loop, simply call the PostQuitMessage function.
--------------------------------------------------------------------------------------------------
PostQuitMessage(0);
--------------------------------------------------------------------------------------------------
The PostQuitMessage function puts a WM_QUIT message on the message queue. WM_QUIT is
a special message: It causes GetMessage to return zero, signaling the end of the message loop. Here is the
revised message loop.
--------------------------------------------------------------------------------------------------
// Correct.
MSG msg = { };
while (GetMessage(&msg, NULL, 0, 0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
---------------------------------------------------------------------------------------------------
              As long as GetMessage returns a non-zero value, the expression in the while loop evaluates to true. After you call PostQuitMessage, the expression becomes false and the program breaks out of the loop. (One interesting consequence of this behavior is that your window procedure never receives a WM_QUIT message, so do not need a case statement for this message in your window procedure.)
             The next obvious question is: When should you call PostQuitMessage? We'll return to this question in the topic Closing the Window, but first we need to write our window procedure. Posted Messages versus Sent Messages
            The previous section talked about messages going onto a queue. In some situations, the operating system will call a window procedure directly, bypassing the queue.
The terminology for this distinction can be confusing:
  • Posting a message means the message goes on the message queue, and is dispatched through the  message loop (GetMessage and DispatchMessage).
  •  Sending a message means the message skips the queue, and the operating system calls the window    procedure directly.
              For now, the distinction is not very important. The window procedure handles all messages, but some messages bypass the queue and go directly to your window procedure. However, it can make a difference
               if your application communicates between windows. You can find a more thorough discussion of this issue in the topic About Messages and Message Queues.

Windows Programming Using C++(Part1)


                                    
Introduction
<><><><><><><><><><><><><><><><><><><><><><><><><><> 
            This documentation provides information about developing WindowApplication using C++.Here iam used to develop window programming using VisualStudio2008.
Steps
Following are the steps for creating WindowsProgramming
>> Open Visualstudio2008
>> File >>New >>Project
>>ProjectTypes
>>VisualC++
>>Select WIN32 project

GetStarted
In this section we will write a minimal Windows Program. Create a New WIN32 Project and Given your application name and Click Ok.We can see that from the Solution Explorer there are 3 Folders named Header Files,Resource Files and Source Files.From the Header Files folder Select your ApplicationName.h (Your Application name).The we can get ApplicationName.cpp.Copy and Paste the Below code into this.
Note that:The Previous codes in that page are delete and then paste the below code 
--------------------------------------------------------------------------------------------- 
#include "stdafx.h"
int _tmain(int argc, _TCHAR* argv[])
{
return 0;
}
#ifndef UNICODE
#define UNICODE
#endif
#include<windows.h>
LRESULT CALLBACK WindowProc(HWND hwnd,UINT uMsg,WPARAM wParam,LPARAM lParam);
int WINAPI wWinMain(HINSTANCE hInstance,HINSTANCE,PWSTR pCmdLine,int nCmdShow)
{
const wchar_t CLASS_NAME[]=L"Simple Window Class";
WNDCLASS wc={};
wc.lpfnWndProc=WindowProc;
wc.hInstance=hInstance;
wc.lpszClassName=CLASS_NAME;
RegisterClass(&wc);
HWND hwnd=CreateWindowEx(
0,
CLASS_NAME,
L"This is My First Window Programming",
WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT,CW_USEDEFAULT,CW_USEDEFAULT,CW_USEDEFAULT,
NULL,
NULL,
hInstance,
NULL);
if(hwnd==NULL)
{
return 0;
}
ShowWindow(hwnd,nCmdShow);
MSG msg={};
while(GetMessage(&msg,NULL,0,0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return 0;
}
LRESULT CALLBACK WindowProc(HWND hwnd,UINT uMsg,WPARAM wParam,LPARAM lParam)
{
switch(uMsg)
{c
ase WM_DESTROY:
PostQuitMessage(0);
return 0;
case WM_PAINT:
{
PAINTSTRUCT ps;
HDC hdc=BeginPaint(hwnd,&ps);
FillRect(hdc,&ps.rcPaint,(HBRUSH)(COLOR_WINDOW+1));
EndPaint(hwnd,&ps);
}
return 0;
}
return DefWindowProc(hwnd,uMsg,wParam,lParam);
}
-------------------------------------------------------------------------------------------- 
After this Build the project and Run(Press F5).A window has been Displayed.
Code Explanation
     Window Classes
A window class defines a set of behaviors that several windows might have in common.Every window must be associated with a window class, even if your program only ever creates one instance of that class. It is important to understand that a window class is not a "class" in the C++ sense. Rather, it is a data structure used internally by the operating system. Window classes are registered with the system at run time. To register a new window class, start by filling in a WNDCLASS structure.
------------------------------------------------------------------------------------------
// Register the window class.
const wchar_t CLASS_NAME[] = L"Sample Window Class";
WNDCLASS wc = { };
wc.lpfnWndProc = WindowProc;
wc.hInstance = hInstance;
wc.lpszClassName = CLASS_NAME;
------------------------------------------------------------------------------------------
You must set the following structure members:
>>lpfnWndProc is a pointer to an application-defined function called the window procedure or "window proc." The window procedure defines most of the behavior of the window. We'll examine the window procedure in detail later. For now, just treat this as a forward reference.
>>hInstance is the handle to the application instance. Get this value from the hInstance parameter of wWinMain.
>>lpszClassName is a string that identifies the window class. Next, pass the address of the WNDCLASS structure to the RegisterClass function. This function registers the window class with the operating system.
--------------------------------------------------------------------------------------
RegisterClass(&wc);
--------------------------------------------------------------------------------------
Creating the Window
To create a new instance of a window, call the CreateWindowEx function:
--------------------------------------------------------------------------------------
HWND hwnd = CreateWindowEx(
0, // Optional window styles.
CLASS_NAME, // Window class
L"Learn to Program Windows", // Window text
WS_OVERLAPPEDWINDOW, // Window style
// Size and position
CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,
NULL, // Parent window
NULL, // Menu
hInstance, // Instance handle
NULL // Additional application data
);
if (hwnd == NULL)
{
return 0;
}
------------------------------------------------------------------------------------
> The first parameter lets you specify some optional behaviors for the window (for example, transparent windows). Set this parameter to zero for the default behaviors.
> CLASS_NAME is the name of the window class. This defines the type of window you are creating.
> The window text is used in different ways by different types of windows. If the window has a title bar, the text is displayed in the title bar.
> The window style is a set of flags that define some of the look and feel of a window. The constant WS_OVERLAPPEDWINDOW is actually several flags combined with a bitwise OR. Together these flags give the window a title bar, a border, a system menu, and Minimize and Maximize
buttons. This set of flags is the most common style for a top-level application window.
> For position and size, the constant CW_USEDEFAULT means to use default values. The next parameter sets a parent window or owner window for the new window. Set the parent if you are creating a child window. For a top-level window, set this to NULL.
> For an application window, the next parameter defines the menu for the window. This example does not use a menu, so the value is NULL.
> hInstance is the instance handle, described previously. (See WinMain: The Application Entry Point.)
> The last parameter is a pointer to arbitrary data of type void*. You can use this value to pass a data structure to your window procedure. We'll show one possible way to use this parameter in the
section Managing Application State.
              CreateWindowEx returns a handle to the new window, or zero if the function fails. To show the
window—that is, make the window visible —pass the window handle to the ShowWindow function
--------------------------------------------------------------------------------------------
ShowWindow(hwnd, nCmdShow);
--------------------------------------------------------------------------------------------
            The hwnd parameter is the window handle returned by CreateWindowEx. The nCmdShow parameter can be used to minimize or maximize a window. The operating system passes this value to the program through the wWinMain function.