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();
}
}
}
}
Mag Web Technologies is a Software Development Company offers on & offshore Software Development Services. Mag Web Enterprise IT services deliver excellence to new age IT businesses. Explore new possibilities of enterprise automation.
Wednesday, 30 January 2013
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.
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: ';
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.
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: ';
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
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
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
Subscribe to:
Posts (Atom)