How to use HTML5 Canvas 2D API

by Admin 12. June 2011 06:49
canvas 2d api demo

In this post I will be putting together some introductory notes on one of cool features of HTML5, CANVAS. Canvas opens up whole new dimension in some interesting presentations in web application without use of third party add on like Flash, Silverlight or some server side controls to generate images (e.g. charts).

This post will some basic use of 2D api to draw some basic shapes in Canvas element on your web page.

Canvas Element

You have to start by adding a canvas element on the page where you want to render graphics. Following snippet shows element on my demo page.

<canvas id="drawingCanvas" width="400px" height="300px"></canvas>

Check Browser Support For 2D API

Since HTML5 specification is not supported by all browsers, you want to make sure that your browser has support for it. To support drawing api (e.g. 2D), canvas has to implement getContext fuction. So we will check for it.

var canvasElem = $('#' + elemId);
if (null != canvasElem) {
// There is support for canvas api
}

Check For 2D Drawing API Support

Next step is to check what kind of drawing you can perform on your canvas element. In HTML5 specification terms, you have to check what kind of context is supported. You have to call getContext method with a string parameter for type of rendering you want to perform. For example to draw 2D graphics, you will set that parameter value as '2d'. You should check return value from that function to make sure that context is actually supported. HTML5 specification states that if a given context is not supported then getContext function will return null.

var canvasElem = $('#' + elemId);
if (null != canvasElem) {
  if (canvasElem[0].getContext) {
     var drawCtx = canvasElem[0].getContext('2d');
       if (null != drawCtx) {
        // We can use 2d api
       }
     }
}

Draw Some Basic Shapes

Here are some example on drawing some basic shapes.

How to draw filled rectangle

You will use fillRect function to draw a filled rectangle. This function takes 4 parameters as shown in function signature below.

fillRect(x, y, width, height)

Next question you have in mind is how do you specify color to use for filling. This is done by using fillStyle function. Basic use of this function is to set color value to this property. Following code snippet shows how to draw four filled rectangles with 2 colors as shown in the screenshot.

// Draw 4 rectanlges
drawCtx.fillStyle = "#4e3";
drawCtx.fillRect(0, 0, 100, 75);
drawCtx.fillRect(100, 75, 100, 75);
drawCtx.fillStyle = "#e13";
drawCtx.fillRect(100, 0, 100, 75);
drawCtx.fillRect(0, 75, 100, 75);

How to draw lines

Use will use lineTo function to draw a line. As function name suggests that parameters for this function specify end point for the line. Now you are wondering how to specify start point for the line. Rendering API has concept of path. You use moveTo function to move start point of path to that specified point. And then lineTo function will draw line from moveTo point to lineTo point. Untill you use beingPath function, subsequent calls to lineTo function calls will use last point as start point. Following code snippet shows drawing two lines across diagonals.

// Draw lines across diagonals
drawCtx.beginPath();
drawCtx.moveTo(0, 0);
drawCtx.lineTo(200, 150);
drawCtx.stroke();
// now set stroke color to blue.
drawCtx.beginPath();
drawCtx.strokeStyle = "#00f";
drawCtx.moveTo(0, 150);
drawCtx.lineTo(200, 0);
drawCtx.stroke();

How to draw circle

Similar to drawing a line, you will use arcTo function to draw an arc. A circle is special case of an arc where start angle is 0 and end angle is 360 degree. Following code snippet shows drawing of a circle in middle of rectangle as shown in screenshot.

// Draw a circle.
drawCtx.beginPath();
drawCtx.lineWidth = 3;
drawCtx.strokeStyle = "#ff0";
drawCtx.arc(100, 75, 50, 0, Math.PI * 2, true);
drawCtx.stroke();

These are just some basic examples of 2D api. In subsequent posts I will show some interesting usage of various 2D api functions to perform some cool rendering on pages.

Sample Code

Here is code that was used to generate basic shapes shown in screenshot.

function drawBasicCanvasShapes(elemId) {
  var canvasElem = $('#' + elemId);
  if (null != canvasElem) {
    var width = canvasElem.width();
    var height = canvasElem.height();
    if (canvasElem[0].getContext) {
      var drawCtx = canvasElem[0].getContext('2d');
      if (null != drawCtx) {
        drawCtx.fillStyle = "#4e3";
        drawCtx.fillRect(0, 0, 100, 75);
        drawCtx.fillRect(100, 75, 100, 75);
        drawCtx.fillStyle = "#e13";
        drawCtx.fillRect(100, 0, 100, 75);
        drawCtx.fillRect(0, 75, 100, 75);

        drawCtx.beginPath();
        drawCtx.moveTo(0, 0);
        drawCtx.lineTo(200, 150);
        drawCtx.stroke();
        // now set stroke color to blue.
        drawCtx.beginPath();
        drawCtx.strokeStyle = "#00f";
        drawCtx.moveTo(0, 150);
        drawCtx.lineTo(200, 0);
        drawCtx.stroke();

        // Draw a circle.
        drawCtx.beginPath();
        drawCtx.lineWidth = 3;
        drawCtx.strokeStyle = "#ff0";
        drawCtx.arc(100, 75, 50, 0, Math.PI * 2, true);
        drawCtx.stroke();
      }
   }
 }
}

Views: 2500

Tags:

HTML

How to open firewall port in Windows 7

by Admin 5. June 2011 17:21

In this post I will describe how to open a fire wall port in Windows 7. I will describe in context of opening up port for SQL Server as an example.

  • Goto Start > Control Panel.

  • Click on System and Security option in right pane.

  • Now you will see options in right pane and one of them is Windows Firewall. Click on that option.

  • Now you have details about Windows Firewall status etc. on your machine.

  • Click on Advanced Settings link in left hand pane.

  • Now you have a very elaborate user interface with very detailed status of fire wall on your machine. In left hand pane you will see option for Inbound Rules. This is what you need to click because we are about to open a port for incoming connections for your machine.

  • You will see all the firewall port rules for incoming connections. On right side, click on New Rule link to start adding new rule for opening port in firewall.

  • Now you will have wizard to help you add port opening rule. Since we are going to open port, select radio button for Port.

  • Follow the wizard to add port. At one step you will get option to select what type of network will have access to this port. If you do not want the port to be open in public network then uncheck that option. It will be important if you use your machine on public WiFi networks.

Once you have followed these steps, you will have your port open in firewall.

Views: 1923

Tags:

Windows 7

Computer Tips - How to restart windows through Remote Desktop

by Admin 11. April 2011 08:00

When you are connected to a windows machine via Remote Desktop (RDP), restarting the remote machine option is not present in Windows Start menu. Only options you see are Disconnect and Log off. If you need to restart that machine you can not press CTL + ALT + DEL. If you do it will bring up shut down option dialog box for local machine. So to restart Windows machine via Remote Desktop, you need to use CTL + ALT + END keys.

Views: 1762

Tags:

Windows

How to remove menu items from ASP.Net menu control

by Admin 22. March 2011 03:15

In this post I will show code snippet for removing a menu item from ASP.Net Menu control. This kind of situation may arise when you want to authorize certain menu items based on some run time condition or user's role. One option is that you can add entries to Menu control at run time based on authorization rules. And then you have option of removing menu items if you have created your whole menu structure declartively.

Here is code snippet that shows how you can remove menu items from collection.

void AuthorizeMenuNavigation()
{
   List<MenuItem> itemsToRemove = new List<MenuItem>();
   foreach (MenuItem menuitem in NavigationMenu.Items)
   {
      if (menuitem.Value == "Manage")
      {
        itemsToRemove.Add(menuitem);
      }
   }

   foreach (var item in itemsToRemove)
   {
      NavigationMenu.Items.Remove(item);
   }
}

Views: 1935

Tags: ,

ASP.Net | ASP.Net

How to programtically block or unblock ip address in IIS using .Net API

by Admin 7. February 2011 07:02

In my earlier post How to get list of applications in IIS programatically using .Net, I discussed how to automate IIS management using managed API. One of the common task or action that lot of applications perform is block or unblock IP addresses of users that may be violating some rules or trying to attack your site. Here is code sample that will answer following questions.

  • How to block an IP addreess in IIS using .Net?
  • How to unblock an IP address in IIS using .Net?
static void BlockIpAddress(string site, string ip)
{
   var serverManager = new ServerManager();
   var hostConfig = serverManager.GetApplicationHostConfiguration();
   // Get ipSecurity section in configuration.
   var ipSecuritySection = hostConfig.GetSection("system.webServer/security/ipSecurity", site);
   var configElements = ipSecuritySection.GetCollection();
   // Check if this ip address is already blocked.
   var ipExists = false;
   foreach (var elem in configElements)
   {
     if (elem.ElementTagName == "add")
     {
        var ipaddr = elem.Attributes["ipAddress"];
        if (null == ipaddr)
        {
           continue;
        }
        if (ipaddr.Value == ip)
        {
          // Check value of "allowed" attribute.
          if ((bool)elem.Attributes["allowed"].Value == true)
          {
           // Simple change this attribute to false and we are done.
           elem.Attributes["allowed"].Value = false;
           break;
          }
        }
      }
    }
    if (!ipExists)
    {
       // Create new element and add it to collection.
       var newElement = configElements.CreateElement("add");
       newElement.Attributes["ipAddress"].Value = ip;
       newElement.Attributes["allowed"].Value = false;
       configElements.Add(newElement);
    }

    serverManager.CommitChanges();
 }

Views: 2520

Tags:

IIS

How to fix 404 - File or directory not found error for ASP.Net 4.0 application pool

by Admin 1. February 2011 06:15

This morning I was upgrading an existing ASP.Net application on Windows 2008 R2 server. Previously it was using an application pool that was using ASP.Net 2.0 framework. Since I had compiled the application with .Net 4.0 framework, I need to switch in IIS 7.5 for application to use application pool for ASP.Net 4.0. As soon as I switched to using ASP.Net 4.0 framework in application pool, I got the following error.

404 - File or directory not found.
The resource you are looking for might have been removed, 
had its name changed, or is temporarily unavailable.

That did not make sense for a moment because I was just using the web application and how can I get 404 error just by switching ASP.Net version in application pool. After digging around in Microsoft Knowledge base and IIS7 documentation, I found that the issue is related to ISAPI filter for ASP.Net 4.0 not being enabled in IIS. Here is what you need to do see what is enabled and what is not enabled for ISAPI and CGI in your server.

From IIS Manager, click on top node of your server in left pane. You will see feature view as shown in the image below.

iis7 isap cgi feature view

You can see that only ISAPI filters enabled for my server are for ASP.Net 2.0. The ones for ASP.Net 4.0 are not available. Just enabled those for ASP.Net 4.0 and you should be all set to roll.

Views: 2280

Tags: ,

ASP.Net | IIS

How to specify color of Excel Cell and Row using .Net

by Admin 10. January 2011 07:26

In my previous posts I have discussed some of the following building blocks of using Excel object model using .Net.

How to set color of a specified cell or row in Excel

Now that we have seen how to access the rows and cells programatically, lets see how we can format the cells in Excel sheet. One of the most common tasks we all perform is to set a color or change the font. Following code snippets show this can be done.

Microsoft.Office.Interop.Excel.Range dataRow = allRows[i];
Microsoft.Office.Interop.Excel.Range dateCell = dataRow.Cells[1];
Microsoft.Office.Interop.Excel.Range priceCell = dataRow.Cells[2];
priceCell.NumberFormat = "$0.00";
priceCell.Font.Bold = false;
priceCell.Interior.Color = System.Drawing.Color.BlanchedAlmond;

This code uses Color property on Interior object of a cell range. The documentation does not explain much on what this Color object is. After digging through some old VBA documentation, I found that you have to create Color .Net object to assign to this property. But there is some issue that you need to be aware of. Although you can set any color for the cell(s) but older versions of Excel do not support all colors. Older versions are limited to only 56 colors that you could specify using ColorIndex property. So if you specify any color that does not fall in that range, you will end up with following Microsoft Excel - Compatibility dialog box warning you about it. But if your users are not going to use older versions of Excel then you are all set to use any color you want.

Views: 2049

Tags: ,

.Net | Office

How to check Excel Workbook saved state in automation application

by Admin 30. December 2010 06:18

While working on creating a console application to manipulate an Excel file using COM interop, I ran into an issue where console application would not close even after I called Quit on the Application object. There was no exception or any error throw but the console application was still waiting for close.

The problem was that I had made a change in the worksheet but I did not save the workbook after it. Excel application sees that a workbook is in Dirty state so it wants to make sure that user of the application, which in my case is a console application, saves the unsaved changes before closing the workbook. There are few options you have here.

How to check if there are unsaved changes in Excel Workbook?

Workbook object exposes a property Saved that can be used to check if there are any unsaved changes. If value of this property is True that means you have unsaved changes.

if (myWorkbook.Saved)
{
 Console.Writeline("There are no unsaved changes to this workbook");
}

How to close Workbook without saving changes?

There may be cases where you have made some changes to some cells. That means Workbook is dirty now. But you really do not want to save the changes. If you do not take care of this, then your application will not close because Excel application instance is waiting for Workbook to be saved. You will use the same Saved property to deal with this. You can set this property to True to indicate that Workbook should be treated as saved and not prompted for saving.

if (!myWorkbook.Saved && !needToSave)
{
 myWorkbook.Saved = true;
}

This is all to how you can deal with saving or not saving of a dirty Excel Workbook.

Views: 1794

Tags: , ,

.Net | .Net | Office | Office

How to fix HTTP Error 401.3 - Unauthorized

by Admin 19. October 2010 03:21

Other day I was installing a DotnetNuke site on Windows 2008 R2 server. I followed all the usual steps of creating a new web site in IIS7.5 on Windows 2008. When I tried to access the site, I ended up with the following error.

HTTP Error 401.3 - Unauthorized

You do not have permission to view this directory or page because of the access control list (ACL) configuration or encryption settings for this resource on the Web server.

In the past I had run into this problem and I knew that it has something to do with application pool and accounts associated with that pool. The error message clearly tells that it has something to do with file permissions on the folder where the web site was physically present. Here are some of the common causes of this sort of error when you configure a new web site on Windows 2008 IIS7.5.

Check Application Pool

Most important is that you need to check what Application Pool is being used for your site and make sure that that account being used by that pool has appropriate access rights on the folders and files. In Windows 2008 R2 there are some important changes related to accounts that are used for IIS application pools. Most of us who come to Windows 2008 R2 environment, get stumped by the fact that it may not be Network Service account that is used for your web site process.

First thing first, we need to figure out what application pool we are using and how we can change it. Here are my earlier posts where I described these steps.

Security Account Used By Application Pool

This piece of information is crucial to solving the error with access control list. When you bring up advanced settings dialog box for the application pool, you will find the following value that tells you the account used by your application pool.

Select the button next to that name and it will bring up following diaolog box where you can change the account settings for your pool identity. You can select system defined accounts from the dropdown or you can select a custom account that you have created for your site.

Application Pool Identity configuration

Diagnosing The Error

So far I have discussed cause and remedies of the error that you got. Now let's see how you can diagnose the issue to really find out what account was trying to access the site files that ended up in access denied error.

I always keep my super tool Process Monitor tool handy on all my development as well as production servers. You can download it from SysInternals site. Fir it up and acces the site. After you get the error, capture the trace and then look for ACCESS DENIED error. I will not go into details about how to effectively use this tool with filters and all to get to the correct information quickly. There you will be able to see windows account that was trying to access the files. Now you can go to site fclder and configure appropriate access rights for the account and you are good to go!

Views: 3605

Tags:

IIS | Windows 7 | Windows 2008

How to customize display of ASP.Net Calendar

by Admin 20. September 2010 06:00

Out of the box ASP.Net Calendar control renders very boring calendar with dates. This works great if only purpose for using control in your application is to pick some dates for some other action. But if you are looking into making your calendar control to display some more advanced text or display some descriptive and informative text on dates to show different events that may be taking place on that day, then you have to do some customization of the control. In the image below, you can see that I am using the calendar control to display some important events and actions on certain dates. And I have color coded those events along with an icon being displayed on the left as well.

asp.net calendar>

Custom ASP.Net Calendar Display

The trick is to understand that ASP.Net calendar gets rendered as a HTML table. So what you need is access to each cell of the table. And access is provided to you by DayRender event of Calendar control. You can handle that event and then set the text as you want. Following code snippet shows how to do it.

protected void OnCalendarDayRender(object sender, DayRenderEventArgs e)
{
  if (e.Day.Date.Day % 2 == 0)
  {
     e.Cell.CssClass = "importantdatecell";
     var cellText = new System.Text.StringBuilder(300);
     cellText.AppendFormat("<a href='#'><span class='importantdate'>{0}</span></a>",
      e.Day.Date.Day);
     cellText.AppendFormat("<span class='{0}'>{1}</span>", 
       "meetingdateevent", "Meeting Today");
     if (e.Day.Date.Day % 4 == 0)
     {
       cellText.AppendFormat("<span class='{0}'>{1}</span>", 
        "lockdateevent", "Droid Rocks!");
     }
     e.Cell.Text = cellText.ToString();
   }
   else
   {
      e.Cell.CssClass = "regulardatecell";
   }
 }

The only problem you are going to run with this approach is that you will have to manage PostBack implementation on click by your self. You can see from the code snippet that I have addedd the data link as Href tag. This is where you will have to add client side click handle to call __doPostBack function. Or you can handle it anyways you would like to.

This should give you a good starting point on customizing display of ASP.Net Calendar control.

Views: 3404

Tags:

ASP.Net

Powered by BlogEngine.NET 1.5.1.7
Theme by Naveen Kohli