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.

Friday 18 January 2013

Implement Impersonation in ASP.NET

Introduction

One of our websites uses Impersonation and a specific user account with special permissions to access certain system resources. The first step in enabling impersonation is setting up the correct attributes in the web.config file:

<system.web>
<identity impersonate="true" password="xxxxxx" userName="xxxxxxx" />   

By using the attribute impersonate="true", you are telling IIS that this website will be impersonating the configured user account.
Configure the website to use a specific user account

The next step is you need to go to IIS Manager and configure the user account you want to impersonate by this website.
Steps

Open IIS Manager.
Expand computer name.
Expand websites.
Click on the specific website for which you want to use impersonation.
On the right panel, under the heading "IIS", double click "Authentication".
Right click on "ASP.NET Impersonation" and select "Edit".
Choose "Specific User".
Click the SET button to provide the specific user name and password.
Press OK at the popup dialog to complete this step on enabling impersonation for website in IIS 7.0.

How to choose process identity for Application Pool in IIS 7.0

To set the correct user identity for the application pool, follow the steps below:

Open IIS Manager.
Click on "Application Pools" under the computer name.
On the right panel, right click on the application pool name (your website’s relevant application pool).
Select "Advanced properties".
Select "Identity" under "Process Model".
Click on the button to set the user account.
Select "Custom account".
Click on the button to specify the user account and password.
Press "OK".

Recycle the app pool by right clicking on the application pool name and selecting "Recycle" on the right click context menu to ensure all configuration changes have taken place.

You are all set to use your application with the impersonated user account.
Source:The Code Project Open License (CPOL)

Thursday 17 January 2013

Scraping JavaScript based web pages with Chickenfoot


The data from most webpages can be scraped by simply downloading the HTML and then parsing out the desired content. However some webpages load their content dynamically with JavaScript after the page loads so that the desired data is not found in the original HTML. This is usually done for legitimate reasons such as loading the page faster, but in some cases is designed solely to inhibit scrapers.
This can make scraping a little tougher, but not impossible.

The easiest case is where the content is stored in JavaScript structures which are then inserted into the DOM at page load. This means the content is still embedded in the HTML but needs to instead be scraped from the JavaScript code rather than the HTML tags.

A more tricky case is where websites encode their content in the HTML and then use JavaScript to decode it on page load. It is possible to convert such functions into Python and then run them over the downloaded HTML, but often an easier and quicker alternative is to execute the original JavaScript. One such tool to do this is the Firefox Chickenfoot extension. Chickenfoot consists of a Firefox panel where you can execute arbitrary JavaScript code within a webpage and across multiple webpages. It also comes with a number of high level functions to make interaction and navigation easier.

To get a feel for Chickenfoot here is an example to crawl a website:
Collapse | Copy Code

// crawl given website url recursively to given depth 
function crawl(website, max_depth, links) { 
  if(!links) { 
    links = {}; 
    go(website); 
    links[website] = 1; 
  } 
 
  // TODO: insert code to act on current webpage here
  if(max_depth > 0) { 
    // iterate links 
    for(var link=find("link"); link.hasMatch; link=link.next) {   
      url = link.element.href; 
      if(!links[url]) { 
        if(url.indexOf(website) == 0) { 
          // same domain 
          go(url); 
          links[url] = 1; 
          crawl(website, max_depth - 1, links); 
        } 
      } 
    } 
  } 
  back(); wait(); 
}

This is part of a script I built on my Linux machine for a client on Windows and it worked fine for both of us. To find out more about Chickenfoot check out their video.

Chickenfoot is a useful weapon in my web scraping arsenal, particularly for quick jobs with a low to medium amount of data. For larger websites there is a more suitable alternative.

Source:The Code Project Open License (CPOL)

Wednesday 16 January 2013

Create Page Hit Counter in Asp.Net

   
Create Page Hit Counter in Asp.Net

Create table Query for Hit Counter

CREATE TABLE [dbo].[hits](
    [i_autoid] [int] IDENTITY(1,1) NOT NULL,
    [hits] [float] NULL,
    [cratedate] [datetime] NULL CONSTRAINT [DF_hits_cratedate]  DEFAULT (getdate())
)

C# Code For Hit Counter

public partial class _Default : System.Web.UI.Page
    {

        dataclass dc = new dataclass();

        protected void Page_Load(object sender, EventArgs e)
        {
            // select max hits from table
            string query = "select max(hits) as hits from hits";
            DataSet ds = new DataSet();
            ds = dc.connection(query);
            float hit = float.Parse(ds.Tables[0].Rows[0]["hits"].ToString());
            //increment hit counter with 1
            float hitsnew =    hit+1;
            // update hit counter table
            string query1 = "UPDATE  hits SET  hits = '"+hitsnew+"'";
            dc.execquery(query1);
        }
    }

We are using just simple steps.on pageload we select data from table and update counter after increment, when pageload this will increment the counter and you can show it in label ttextbox or any where..
DC is the object of Class where we perform sql related task like create connection etc.
executequery method execute query to sql server.you can use your way to execute queries.

Saturday 12 January 2013

D3 crash course

D3 crash course

Introduction

Data-Driven Documents (D3) is a javascript library that offers an interesting approach to visualization for the web. D3 enables direct inspection and manipulation of the standard document object model (DOM). With D3 we can selectively bind input data to document elements and define dynamic transforms that both generate and modify the content of the DOM.

D3’s primary authors Michael Bostock, Vadim Ogievetsky and Jeffrey Heer have created a library that uses representational transparency to improve expressiveness and provide natural integration with developer tools. It’s quite different from other visualization libraries since it focuses on direct inspection and manipulation of the document object model.

The functionality of D3 can broadly be separated into four categories:

    Loading data
    Binding data to elements
    Transforming elements by inspecting the bound data, and updating the bound properties of the elements
    Transitioning elements in response to user interaction

The transformation of elements based on bound data is the most important category and D3 provides the structure for performing these transformations, while we define how we want those transformations carried out – leaving us in full control of the final output.

D3 is not a traditional visualization framework. Instead of introducing a new graphical grammar, D3’s authors choose to solve a different, smaller problem: the manipulation of documents based on data.

Basically D3 can be thought of as a visualization “kernel” rather than a framework, somewhat resembling other document transformers such as jQuery, CSS and XSLT. These libraries share a common concept of a selection: A set of elements is selected matching the given criteria before applying a set of operations that transforms the selected elements. JavaScript-based selections provide flexibility on top of CSS, since styles can be altered dynamically in response to user interaction and changes to the data.

The designers of D3 choose to adopt the W3C Selectors API for selection; a mini-language consisting of predicates that filter elements by tag (“tag”), class (“.class”), unique identifier (“#id”), attribute (“[name=value]”), containment (“parent child”), adjacency (“before ~ after”), and other facets. Since predicates can be intersected (“.a.b”) and unioned (“.a, .b”) we have a rich and concise method for selection.

D3’s operates on set of elements queried from the current document. Data joins bind data to elements, enabling functional operations that depend on data, and produce enter and exit sub-selections that enables creation and destruction of elements in correspondence with data. Operations are, by default, applied instantaneously, while animated transitions interpolate attributes and styles smoothly over time. The library facilitates event handlers that respond to user input and enable interaction. D3 also provides a number of helper modules that simplify common visualization tasks, such as layout and scales.

For More Information Log on To http://www.codeproject.com/Articles/523444/D3-crash-course

Friday 11 January 2013

Creating a Pinterest Like Layout in ASP.NET


Pinterest is currently the world’s fastest growing social networking site and famous for the best functioning visual design. Do you love the look and feel of Pinterest? This post explains how to implement the same masonry dynamic layout with infinite scroll in ASP.NET.

Here are the steps to implement it:

1. Download and add jQuery Masonry plugin. It is a dynamic grid layout plugin which arranges elements vertically, positioning each element in the next open spot in the grid and minimizes vertical gaps between elements of varying height.

2. We are going to display product with description in each tile. Here is the structure of Product and ProductRepository class.
   
public class Product {
    public string Url { get; set; }
    public string Description { get; set; }
}

public static class ProductRepository
{
    static List<Product> objList;
    public static IEnumerable<Product> GetData(int pageIndex, int pageSize)
    {
       int startAt = (pageIndex-1) * pageSize;
        objList =new List<Product>();
        Product obj;
        Random r = new Random();
        int n = r.Next(1, 7);  
        for (int i = startAt; i < startAt + pageSize; i++)
        {
            n = r.Next(1, 7);
            obj = new Product();
            obj.Url = String.Format("http://dummyimage.com/150x{1}/{0}{0}{0}/fff.png&text={2}", n, n * 50,i+1);
            obj.Description = "Description of product " + (i+1).ToString();
            objList.Add(obj);
        }
        return objList;
    }
}

In ProductRepository, GetData method takes pageIndex and pageSize parameters and generates dummy data and images of random heights.
HTML Structure:

3. In the aspx page, the head tag structure is as follows:

<head id="Head1" runat="server">
    <title>Pinterest Like Layout</title>
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <!--[if lt IE 9]><script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script><![endif]-->
    <style type="text/css">
        body
        {
            background-color:#EEEEEE;
        }
        #imgLoad
        {
            position:fixed;
            bottom:0; 
            left:40%;
            display:none;
        }
        .box
        {
            margin: 5px;
            padding: 10px;
            background-color:#FFFFFF;
            box-shadow: 0 1px 3px rgba(34, 25, 25, 0.4);
        }
    </style>
    <script src="Scripts/jquery-1.7.1.min.js" type="text/javascript"></script>
    <script src="Scripts/jquery.masonry.min.js" type="text/javascript"></script>
</head>

4. To display products, we use Repeater control:
   
<div id="container" class="transitions-enabled infinite-scroll clearfix">
       <asp:Repeater ID="Repeater1" runat="server">
           <ItemTemplate>
               <div class="box">
                   <img src="<%# Eval("Url") %>" />
                   <p><%# Eval("Description") %></p>
               </div>
           </ItemTemplate>
       </asp:Repeater>
   </div>
   <div id="imgLoad">
       <img src="http://i.imgur.com/6RMhx.gif" />
   </div>
Dynamic Grid Layout:

5. To bind repeater on Page_Load:

Repeater1.DataSource = ProductRepository.GetData(1, 25);
Repeater1.DataBind();

Now, the product is displayed in normal order. If there is variance in each tile height then there is unnecessary blank space between rows. For dynamic grid layout, the following javascript code is used:
   
var $container = $('#container');

$container.imagesLoaded(function () {
    $container.masonry({
        itemSelector: '.box',
        columnWidth: 100,
        isAnimated: true
    });
});

You can see the products are reordered to minimize vertical spacing.
Infinite Scrolling:

6. To implement infinite scrolling, lets create a webmethod on aspx side:
   
[WebMethod]
   public static IEnumerable<Product> GetData(int pageNo, int pageSize)
   {
      
       return ProductRepository.GetData(pageNo, pageSize);
   }

We call this method using jQuery ajax on scrolling, add products dynamically and reorder products
   
var pageNo = 1,pageSize = 25;
 $(window).scroll(function () {
               if ($(window).scrollTop() == $(document).height() - $(window).height() && !($('#imgLoad').is(':visible'))) {
                   loadMore();
               }
           });

           function loadMore() {
               $('#imgLoad').show();
               $.ajax({
                   type: "POST",
                   url: "Default.aspx/GetData",
                   data: JSON.stringify({ pageNo: pageNo + 1, pageSize: pageSize }),
                   dataType: "json",
                   contentType: "application/json",
                   complete: function (response) {                     
                       $('#imgLoad').hide();
                   },
                   success: function (response) {
                       if (response.d.length > 0) {
                           var ctrls = [];
                           for (var i = 0; i < response.d.length; i++) {
                               ctrls.push('<div class="box"> <img src="' + response.d[i].Url + '" /><p>' + response.d[i].Description + '</p></div>');
                           }
                           var $newElems = $(ctrls.join(''));
                           $container.append($newElems);
                           $newElems.css({ opacity: 0 });
                           $newElems.imagesLoaded(function () {
                               // show elems now they're ready
                               $newElems.css({ opacity: 1 });
                               $container.masonry('appended', $newElems, true);
                           });
                           pageNo++;
                       }
                   }
               });

Thursday 10 January 2013

Learn Basic Java in 10 Minutes


What is Java?

You can find tons of definition about Java on web; Answer is simple “Programming Language to develop any kind of application with Object Oriented approach and it can run anywhere”.

Sample application
For example, you need to develop an application to track your daily expenses on your PC. The application can be developed by Java by the following manner.

Minute 1 Session
First download and install Java Development Kit (JDK) from official Oracle site. The JDK is the software environment where you can compile and run your Java programs.  Download here.

Minute 2 Session
Know the commands to compile and run a Java program.  Before that you need to set the path to point your Java compiler on your development location. Assume that you have installed JDK on your C:\Program Files\Java\jdk1.7.0 drive. You need to run the following line of code in your command prompt before accessing Java compiler.
SET PATH = C:\Program Files\Java\jdk1.7.0\bin;
Open start menu and type cmd on your Windows machine to open command window.  Now open your folder where your Java programs are saved.

For example: D:/MyJava.
Cd  D:/MyJava
D:MyJava > SET PATH = C:\Program Files\Java\jdk1.7.0\bin;

Note that “jdk1.7.0\bin” folder contains Java compiler (javac) and Java interpreter (java) applications.
Now you are ready to run a sample Java program on your machine. Unlike like regular hello world application, we are going to run a practical program to track daily expenses.

Minute 3 Session
Just learn about simple Java program and know the basic steps to compile and run a program.
A Java class is a blueprint of an object. An object in an instance of a class.

Step1: Identify Java classes
Step2: Develop Java classes
Step3: Develop main class
Step4: Compile all classes
Step5: Run main class

Main class is a Java class which has interpreter calling method named main like below:

public void main(String args[]){ // main method to run a Java program
// Code to call other objects/classes
}

Minute 4 Session
In our case, we need to develop an application for daily expense tracking. The following classes may satisfy these requirements.
ExpenseTracker
ExpenseTrackerMain

Minute 5 Session
Develop ExpenseTracker Java class.

public class ExpenseTracker {

public void addExpense(String expenditure, double amount){
System.out.print(“Expenditure ”+ expenditure+”  “+amount+” added on ”+new java.util.Date());
}

}

Save this file as ExpenseTracker.java in your working folder.

Minute 6 Session
Develop ExpenseTrackerMain class to run this application.

public class ExpenseTrackerMain {

public static void main(String as[]){
ExpenseTracker tracker = new ExpenseTracker();
String expen = JOptionPane.showInputDialog(null, “Expenditure”);
String amount = JOptionPane.showInputDialog(null, “Amount”);
Double doubleAmount = Double.parseDouble(amount);
tracker.addExpense(expen, doubleAmount);
}

}

Minute 7 Session
Compile your application.  Just open your working directory where you saved these .java files and follow the below steps.
Open command prompt and go to your working directory.

Type SET PATH = C:\Program Files\Java\jdk1.7.0\bin; // recall Minute 2 session
Type javac *.java
This command will compile both ExpenseTracker and ExpenseTrackerMain Java files. This action will generate .class files inside your working directory.

Minute 8 Session
Run your application.
Open command prompt and go to your working directory.
Just type java ExpenseTrackerMain in your command window.

Minute 9 Session
Your first Java program is done.
What is next?
Just add some methods in ExpenseTracker Java file, call those methods in ExpenseTrackerMain class, compile and run again.

Minute 10 Session
Similar to Expense Tracker application develop Task Tracker application by using the following code snippet.

public void addTask(String task, Status status){
System.out.print(“Task ”+ task +”   added on ”+new java.util.Date()+”.  Status of this task is :”+status);
}

One of the best ways to develop your Java knowledge is by Oracle’s Java Certification program. There are numerous vendors available to teach Java in the world but there are few vendors are having good knowledge and latest updates.

Wednesday 9 January 2013

5 Reasons to be excited about Java in 2013



With 2012 done and dusted, it’s time to look forward to the coming 12 months for the development world. Over the past few days, we’ve asked some respected developers for their predictions - now it’s time for our own.

Here’s five quick reasons why you ought to be excited about what 2013 holds...

1. Java 8

An obvious place to start but for most Java developers, it’s the release of 2013. Assuming there’s no further delays, we can expect Java 8 to arrive in September, bringing with it long awaited lambda functions.

It’s fairly likely in the immediate aftermath of Java 8’s welcome, we will see blogposts of equal measure either moaning at the complexity of the new features or saying the release isn’t big enough to warrant interest.

Either way, some much needed deferred features finally make an appearance and the rest of us will just knuckle down. The improved Date and Time API within Java 8 also deserves a mention here.

2. JVM languages go from strength to strength

2012 was really the year when JVM languages took centre stage. Front of the pack was multi-paradigm Scala, notching up impressive enterprise clients thanks to investment into Typesafe. Extending the possibilities with Akka and Play 2.0!, it looks like the foundations are in place to push further in 2013. The real challenge is selling Scala to those who don’t need something heavy duty.

The dynamic Groovy wasn’t far behind last year, adding static compilation into the mix with Groovy 2.0.  A third major version is expected not long after Java 8 to allow Groovy developers to get the most of the new features. The supporting cast, including Gradle and Grails, could be a big draw for those looking for a Java alternative that isn’t too far removed.

We’ve not mentioned the likes of Clojure, JRuby and Kotlin; the latter undergoing plenty of work as it nears a final version. Ultimately, success comes down to the fostering of an active community, which many JVM languages have cottoned onto, and the spinoff projects within that community.

If 2012 was the rise, 2013 is the consolidation within enterprise circles, which is fuelled by the developers using the language.

3. The increasing importance of JavaScript in Java

Details were thin on the ground for two new initiatives in OpenJDK for most of 2012, but by the year’s end, we had learnt a bit more about each project’s goals and their importance to Java innovation.

The new JavaScript engine set to be included within Java 8 will embed JavaScript into Java applications. Project Nashorn cements the notion of JavaScript’s reemergence and ever more relevance to Java developers.

Initially shrouded in secrecy, Nashorn was open sourced in November and appeared in the OpenJDK repository four days before Christmas. Another big plus point for Nashorn is the crucial inclusion of wildly popular node.js within the deal, ushering in a polyglot future. With plenty more details set to come, we’ll be monitoring this one with eagle eyes.

4. Getting more bang for your buck - harnessing the GPU

Another project within OpenJDK that has great potential is Sumatra, aiming to harness greater Java performance by utilising the GPU. Initial investigations are centred on the Hotspot JVM to lay the groundwork, before ‘leveraging’ Java 8 library and languages features such as lambdas to test the techniques with cutting edge Java.

The project, led by GPU specialist AMD, expects to find some roadblocks on the way with the Java API and its constructs, so we won’t be seeing ideas implemented in Java 8, but Sumatra could lead to some great advances and new techniques down the line for developers.

5. Java drifts even further into the cloud

With dozens of IaaS and PaaS options flooding the market, from both indies like Jelastic and industry giants like Oracle and AWS, developers are now spoilt for choice. Java has, it seems, successfully made the leap into the brave new world of “the cloud”.

The biggest current problem, as highlighted by Martijn Verburg on the Java Advent Calendar blog, is a lack of standardisation and optimisation. With Java’s own cloud features delayed to Java EE 8, it’s now up to the providers to provide standards such as CAMP or, failing that, the community to come up with universal frameworks like jclouds. Meanwhile, others are refusing to wait patiently for Oracle to provide features like multitenancy and efficient garbage collection, such as Waratek (which we profiled in September).

With cloud platforms rapidly becoming the norm, we’re likely to see the launch of even more third-party solutions for supporting Java in the cloud: by the time Java EE 8 rolls around (possibly 2014), we may not even need it. (Elliot Bentley)

Tuesday 8 January 2013

Telerik ASP.NET AJAX Q1 2013 with Persistence Framework and iOS6 Support

Telerik ASP.NET AJAX control suite Q1 2013 will provide support for persistence framework with which users will be able to preserve their settings between sessions by saving the state of any RadControl on the page in a file, database or any other storage mode. The release will also include significant performance enhancements by leveraging HTML5, CSS3 with support for iOS6 and Windows 8 touch user interface.

Telerik is also planning to add SASS support which enables developers to build custom skins very easily. Moreover, all the controls included with the upcoming release will be Section 508 and level AA compliant. Telerik is also working towards the creation of controls which will be compatible with W3C Web Content Accessibility Guidelines 1.0/2.0.

The Q1 2013 release will ship with a new control which incorporates TreeView functionality in a ComboBox. Moreover, it will also include a new DropDownList and an advanced editor control with the look and feel of website search boxes.

Telerik ASP.NET AJAX control suite Q1 2013 will include several new features for existing controls - PivotGrid, HTML Chart, Image Editor, Async Upload, Editor, Grid, AutoCompleteBox, TreeList, Slider, ComboBox, Barcode and is expected to release in February 2013.

Monday 7 January 2013

ASP.NET Page Life Cycle Overview


When an ASP.NET page runs, the page goes through a life cycle in which it performs a series of processing steps. These include initialization, instantiating controls, restoring and maintaining state, running event handler code, and rendering. It is important for you to understand the page life cycle so that you can write code at the appropriate life-cycle stage for the effect you intend.

If you develop custom controls, you must be familiar with the page life cycle in order to correctly initialize controls, populate control properties with view-state data, and run control behavior code. The life cycle of a control is based on the page life cycle, and the page raises many of the events that you need to handle in a custom control.


General Page Life-Cycle Stages

In general terms, the page goes through the stages outlined in the following table. In addition to the page life-cycle stages, there are application stages that occur before and after a request but are not specific to a page. For more information, see Introduction to the ASP.NET Application Life Cycle and ASP.NET Application Life Cycle Overview for IIS 7.0.

Some parts of the life cycle occur only when a page is processed as a postback. For postbacks, the page life cycle is the same during a partial-page postback (as when you use an UpdatePanel control) as it is during a full-page postback.

Stage
   

Description

Page request
   

The page request occurs before the page life cycle begins. When the page is requested by a user, ASP.NET determines whether the page needs to be parsed and compiled (therefore beginning the life of a page), or whether a cached version of the page can be sent in response without running the page.

Start
   

In the start stage, page properties such as Request and Response are set. At this stage, the page also determines whether the request is a postback or a new request and sets the IsPostBack property. The page also sets the UICulture property.

Initialization
   

During page initialization, controls on the page are available and each control's UniqueID property is set. A master page and themes are also applied to the page if applicable. If the current request is a postback, the postback data has not yet been loaded and control property values have not been restored to the values from view state.

Load
   

During load, if the current request is a postback, control properties are loaded with information recovered from view state and control state.

Postback event handling
   

If the request is a postback, control event handlers are called. After that, the Validate method of all validator controls is called, which sets the IsValid property of individual validator controls and of the page. (There is an exception to this sequence: the handler for the event that caused validation is called after validation.)

Rendering
   

Before rendering, view state is saved for the page and all controls. During the rendering stage, the page calls the Render method for each control, providing a text writer that writes its output to the OutputStream object of the page's Response property.

Unload
   

The Unload event is raised after the page has been fully rendered, sent to the client, and is ready to be discarded. At this point, page properties such as Response and Request are unloaded and cleanup is performed.

Saturday 5 January 2013

11 predictions for enterprise software in 2013

All cloudy in the ERP forecast: The options for, and customers' comfort with, cloud-based ERP could grow significantly this year.

Market watchers will be eyeing whether Workday has the same success winning megadeals with its newer financials module as it did with HCM (human capital management). Microsoft's Dynamics ERP product lines should get additional cloud deployment options, as should customers of Infor and Epicor. Expect more attention to be paid to the likes of Plex and Kenandy, which specialize in cloud-based ERP for manufacturers. Meanwhile, Oracle and SAP will hope to fend off the competition overall with their own cloud modules.

With no shortage of choices now and upcoming for cloud ERP, the real question seems to be whether customers will vote en masse with their wallets.

Salesforce.com will move further into ERP: Even as it reformed its image from a cloud CRM software vendor into a full-blown platform player and moved into new application categories, Salesforce.com has yet to make an aggressive push into ERP software on its own, preferring instead to work with partners such as Workday and Infor.

Salesforce.com has taken one small step in the direction of ERP with the introduction of Work.com, a human resources application for managing employee performance. But Work.com can easily be added to the edges of a customer's software landscape, versus supplanting a rival product.

While it's not clear Salesforce.com will either develop a robust ERP suite on its own or acquire a vendor who already has one, in 2013 expect to see the company make some type of move, even if it's just a strengthening of partner relations. ERP simply takes up too much of the IT budget pie, and Salesforce.com will want a bigger slice.

Oracle and others will invest heavily in mobility and mobile middleware: Mobile application deployment options and design became the name of the game in enterprise software this year. SAP has made much of its mobile middleware and device management software, which it acquired through the $5.8 billion acquisition of Sybase in 2010.

Oracle is hardly lacking in mobile development tools, but it seems likely that it will scoop up a specialized company or three, perhaps next year, in order to strengthen its position. Don't be surprised if the likes of Hewlett-Packard and IBM do the same.

Oracle will get out of some part of the hardware business: It's no secret that Oracle has struggled with Sun's hardware business following the 2010 acquisition of Sun. Oracle executives have sent a consistent message, however, that the vendor is focused on higher-margin systems like the Exadata database machine and has little interest in competing with Hewlett-Packard or IBM in the commodity server market.

But Exadata's real profitability lies in the large amount of Oracle database and other software it runs, which delivers Oracle steady streams of lucrative maintenance revenue. This speaks to the real issue: Oracle has always been a software company at heart, so expect some type of retreat from hardware in 2013.

SAP boosts HANA with big data buy and nomenclature shift: Expect SAP to purchase an up-and-coming "big data" product or vendor, and perhaps several, including at least one that specializes in integration with the Hadoop framework for large-scale data processing, said Jon Reed, an independent analyst who closely tracks the company. Such a move would surely be taken with an eye on building out the capabilities of SAP's HANA in-memory database.

SAP will also seek to disassociate the NetWeaver brand name from its cloud products, Reed said. "For 2012, HANA will be the new term du jour."

Hadoop's momentum will continue: Expect plenty of additional adoption for Hadoop, according to analyst Curt Monash of Monash Research. "Everybody has the 'big bit bucket' use case, largely because of machine-generated data," Monash said via email. "Even today's technology is plenty good enough for that purpose, and hence justifies initial Hadoop adoption." Development of further Hadoop technology will be rapid as well, Monash said.

MySQL gets some more competition: Usually when the topic of alternative databases comes up, the incumbent is often Oracle or IBM DB2. But in 2013, MySQL could be playing the latter role. "NoSQL and NewSQL products often are developed as MySQL alternatives," Monash said. "Oracle has actually done a good job on MySQL technology, but now its business practices are scaring companies away from MySQL commitments, and newer short-request SQL DBMS are ready for use. Also, look for PostgreSQL to regain visibility as part of the mix."

Software all around: "[2013] will be the year everyone wants to be a software company," said analyst Ray Wang, CEO of Constellation Research. "Large hardware vendors and systems integrators will take advantage of [the consumerization of IT trend] and the cloud to consider delivering software-based solutions and IP to their market and competitors."

HP will make another big software buy: As most people have heard by now, Hewlett-Packard's $10.3 billion acquisition of infrastructure software vendor Autonomy hasn't gone terribly well, particularly in the public relations department.

Although HP shareholders may shudder at the thought of the company shelling out yet more billions, CEO Meg Whitman may push for another big acquisition as part of her turnaround plan.

Along with the search and data management software from Autonomy, HP also has a powerful database in the form of Vertica. Missing components in its lineup seem to be middleware and business applications, so if a deal does occur, watch those spaces.

Economic turmoil on tap: There's likely to be an economic recession in the U.S. in 2013, resulting in a significant pullback in IT spending, particularly on new purchases and investments, according to analyst Frank Scavo, president of the IT research firm Computer Economics.

This will "impact the traditional enterprise software vendors in a greater way than they realize," Scavo said. "Upgrade projects for traditional on-premises enterprise systems will be cancelled or delayed. The third-party maintenance business will prosper as customers look for ways to cut support costs. This will put pressure on traditional vendors to cut maintenance rates, which they have been resisting. This in turn will pressure their operating margins."

While cloud-based vendors will suffer less, they'll still see some deals take longer to close, Scavo said.

Don't believe anything you've just read: "Very few people see really new trends before they start," Scavo said. "I agree with Bill Gates, who said, 'We always overestimate the change that will occur in the next two years and underestimate the change that will occur in the next 10.'"

Source:java world

Friday 4 January 2013

Making a switchable Desktop and Mobile site with ASP.NET MVC 4 and jQuery Mobile

There's something about making an experience great on a pocket supercomputer phone that is so much more satisfying than a desktop. Actually got this blog looking nice on mobile devices back in 2006 when nobody was mobile except doctors and, well, all of us techies here on the blogs.

About the importance of a good mobile site before in posts like Create a great mobile experience for your website today. Please. However, some folks had asked me if I'd do a post on how to do a combination Desktop and Mobile site using ASP.NET MVC similar to the examples I used in my talks in Russia on mobile earlier this year. (There's video of those ASP.NET mobile presentations available)

When you start Visual Studio 2012 and go File | New ASP.NET MVC 4 app, there's an Internet Application template and a Mobile template. One gets you a standard desktop site - although with responsive design elements so it works on small screens - and the other gets you a jQuery Mobile application meant primarily for phones and tablets. Let's make one that switches between both.

We will do a small site in ASP.NET MVC for the Desktop, do some quick DB access, add jQuery Mobile and a View Switcher switch back and forth. I'll be using the Electric Mobile Studio from Electric Plum to simulate an iPhone. You can get a 7 day trial or you can get the Lite version of the Electric Plum Mobile Simulator with WebMatrix 2.
Quick CRUD Example

First, a model for DVDs.
public class DVD
{
    public int ID { get; set; }
    public string Title { get; set; }
    public int Year { get; set; }
    public Rating rating { get; set; }
}

public enum Rating
{
    G, PG, PG13, R
}

Next, I scaffold out the Index, Create, Edit, Delete, etc. Unfortunately scaffolding doesn't do Enums (I'm sad) for my Movie Ratings so I add EditorFor() calls to my Create and Edits, and update my Index.
<div class="editor-label">
    @Html.LabelFor(model => model.rating)
</div>
<div class="editor-field">
    @Html.EditorFor(model => model.rating)
    @Html.ValidationMessageFor(model => model.rating)
</div>

Shared/EditorTemplates/Rating.cshtmlI could have used DropDownList I suppose, but I have always found that helper confusing. Instead, I'll create a Rating.cshtml that makes a dropdown. I could change this at some future point to be fancier and not even use a DropDown.

Aside: How do you guys usually handle Enums? I've seen it done a few ways. I'd like this to be more generic, but here's what I did for the Rating editor Template. Note the nullable ? as it has to work for both Create and Delete
@model MyApp.Models.Rating?
@using MyApp.Models

<select id="@ViewData.TemplateInfo.GetFullHtmlFieldId("")" name="@ViewData.TemplateInfo.GetFullHtmlFieldName("")">
    @foreach (int rating in Enum.GetValues(typeof(Rating))) {
        var name = Enum.GetName(typeof(Rating), rating);
        <option value="@name" selected="@(Model.HasValue ? (int)Model == rating : false)">@name</option>
    }
</select>

OK, so there's a basic Desktop CRUD app.


For more Information Browse http://www.hanselman.com/blog/MakingASwitchableDesktopAndMobileSiteWithASPNETMVC4AndJQueryMobile.aspx

Thursday 3 January 2013

ASP .Net Development Vs Java Development


Java being the predecessor of all other programming languages is open source and on top of that is platform independent. Being platform independent has made it the preferred choice of amateurs and professionals alike. Being open source, Java API’s can easily be accessed by developers unlike .NET which is proprietary software and whose API’s are not accessible. Java, being open source, users do not have to grapple with hefty license fees each year, something which is mandatory in case of proprietary software.


Java being a very old technological platform is being taught in universities for a number of years. Therefore, there is an abundance of talent when it comes to developing applications in Java. There is however a significant shortage of developers who are acquainted with the .Net platform in the developed world. You would need to offshore your application development work to a low cost location like India where you would find a significantly higher number of developers acquainted with .NET technologies.


Some developers are of the opinion that ASP. NET is just an improved version of JAVA and has been developed by overcoming the short- comings of Java. Supporters of .NET technologies claim that Java is a language while .Net is language independent. Opting for .Net does not bind you to a single language as .Net supports multiple languages. It even supports Java as J# is very close to Java.


Another major advantage of using .Net is the ease with which it allows the exchange of data between various software applications. This occurs because the dot net platform allows different programs to exchange data via a common set of exchange formats, to read and write the same file formats and to use the same protocols. Such features make ASP.NET the preferred programming language for developing database driven websites and applications. .Net proves to be useful when applications stored on remote systems have to communicate with each other through standard internet protocols like XML, SOAP.



In my opinion, you should always develop applications on such a platform which does not get obsolete in the next five or even ten years. In simple words, you should avoid the upgrade treadmill offered by proprietary software’s who ask you to upgrade every few years.