Running Full Trust applications under Windows Azure.
July 12, 2009 by MK
Filed under ASP.NET, Hosting, web development
What is Windows Azure?
Microsoft’s Azure Services Platform is a cloud platform (cloud computing platform as a service) offering that “provides a wide range of Internet services that can be consumed from both on-premises environments or the Internet (though the platform itself will not be made available for on-premises deployments.
To read more about Azure please visit Microsoft’s Official Website on Azure Services Platform.
What is Full Trust and why is it required?
Full trust (CAS - Code Access Security Level) allows ASP.NET applications to execute native code, to read from the Registry and Windows Event Log, and to read and write to files outside of the application’s virtual directory. In short, with full trust one web application could delete the entire contents of another web application.
To read more on Full Trust Hosting please visit What is ASP.NET Full trust hosting?
Looking for good Full Trust Windows / ASP.NET Hosting Plans - Try Webhost4life OR Alentus (We have been using them for years now)
Windows Azure and Full Trust.
Windows Azure now offers the option of running the code in your Web and Worker roles under full trust. As a developer this opens up a lot of exciting and compelling options -
- Inter-process Communication via Named Pipes:
If you application spawns processes, you can communicate among them via named pipes.
- Invoking non-.NET Code:
Many developers have existing investments in native code or may choose to use native code for some specialized tasks. .NET full trust makes it possible to use native code via spawning processes or Platform Invoke (P/Invoke).
- Using .NET Libraries that Require Full Trust:
Certain .NET libraries, including libraries in the .NET Services SDK, require full trust and can now be used in Windows Azure.
To enable full trust, simply add the enableNativeCodeExecution attribute to your role in the Service Definition file and set the attribute value to true:
<?xml version=”1.0″ encoding=”utf-8″?>
<ServiceDefinition name=”MyService” xmlns=”http://schemas.microsoft.com/ServiceHosting/2008/10/ServiceDefinition”>
<WebRole name=”WebRole” enableNativeCodeExecution=”true”>
<InputEndpoints>
<InputEndpoint name=”HttpIn” protocol=”http” port=”80″ />
</InputEndpoints>
</WebRole>
</ServiceDefinition>
Windows Azure applications run with restricted “User” privileges in the cloud. Accordingly, certain operations such as modifying the registry and writing to the system directory are not possible at this time (even though they may succeed in your local development environment). To read more on more on Custom Trust visit Why Full Trust hosting is not recommended when using a shared ASP.NET or shared Windows hosting plan?
How to create high quality (resolution) pie chart using ASP.NET and C#
March 20, 2009 by MK
Filed under ASP.NET, C# / ASP.NET, web development
Using ASP.NET’s Drawing namespace we can easily create high quality charts and graphs without using any 3rd party components.
To demonstrate and for the purpose of this article we will be working with Bitmap and Graphics class. You can think of Bitmap as the drawing board and Graphics as the toolbox to draw anything out of your imagination. Both these classes are available in ASP.NET under System.Image and System.Image.Drawing namespace and are used for creating and manipulating images on the fly.
Don’t forget to include these namespaces -
using System.Image
using System.Image.Drawing
To create the drawing board, we just need to instantiate an object of Bitmap class like following -
Bitmap objBitmap = new Bitmap(width, height);
You can change the width and height of the bitmap by passing in width and height as parameters.
Now we will create an Arraylist of colors that we will use to define different pieces of the pie chart. I am using the following for the purpose of this article but you can use a for loop to create random colors if you want.
System.Collections.ArrayList colors = new System.Collections.ArrayList();
colors.Add(new SolidBrush(Color.FromArgb(255, 235, 149)));
colors.Add(new SolidBrush(Color.FromArgb(232, 110, 52)));
colors.Add(new SolidBrush(Color.FromArgb(240, 179, 16)));
colors.Add(new SolidBrush(Color.FromArgb(186, 208, 236)));
Now that we have a canvas, we need to create an instance of the Graphics class, create the paintbrush, and specify a canvas to use. We can accomplish this using the static Graphics method FromImage, which takes an Image instance as a single parameter and returns a resulting Graphics instance. We can pass in the instance of the Bitmap class, since it is derived from the Image class.
Graphics objGraphics = Graphics.FromImage(objBitmap);
Now comes the most important part, this part of code will define the look of the pie chart. Here are a set of properties that we need to set to obtain a better resolution to get the resolution just like any other third party components.
objGraphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
objGraphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
objGraphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
objGraphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.ClearTypeGridFit;
You can follow this link for more information on Graphics class and the properties used above - http://msdn.microsoft.com/en-us/library/system.drawing.graphics(VS.80).aspx
Now we will run our for loop to create the slices of the pie chart and slices will add up to create the full pie chart.
for (iLoop = 0; iLoop < ds.Tables[0].Rows.Count - 1; iLoop++)
{
//create the slice with values coming from the database and total is the aggregate of total amount of data or total slices of pie
objGraphics.FillPie((SolidBrush)colors[iLoop], pieRect, currentDegree,
Convert.ToSingle(ds.Tables[0].Rows[iLoop][dataColumnName]) / total * 360);
//here datacolumnname is the value of a single slice of pie coming from the database
// increment the currentDegree
currentDegree +=
Convert.ToSingle(ds.Tables[0].Rows[iLoop][dataColumnName]) / total * 360;
}
NOTE: You can refer to these articles for Advanced Shading Effects using ASP.NET and C#.
http://www.codeproject.com/KB/cs/ColorShading.aspx
http://www.codeproject.com/KB/GDI-plus/drawing3dgdi.aspx
Now the only other thing that we need to do is to save the image as the highest quality. Also, you can copy the following code to your aspx page that will return the image as a page
response stream. e.g. if you named this page as return_image.aspx then you can use this image anywhere using this line of HTML code -
<img src=”return_image.aspx” alt=”" border=”0″ />
and your image will be rendered here.
Following is the code for generating highest quality pie chart image and return as a response stream to the browser.
using (System.Drawing.Image img = LoadImage()) //LoadImage() will return the image that we
have created in the steps above.
{
ImageCodecInfo myImageCodecInfo;
Encoder myEncoder;
EncoderParameter myEncoderParameter;
EncoderParameters myEncoderParameters;
myImageCodecInfo = GetEncoderInfo(”image/jpeg”);
myEncoder = Encoder.Quality;
myEncoderParameters = new EncoderParameters(1);
myEncoderParameter = new EncoderParameter(myEncoder, 100L); //You can use 100L to increase or decrease the quality of the image.
myEncoderParameters.Param[0] = myEncoderParameter;
Response.ContentType = “image/gif”;
img.Save(Response.OutputStream, myImageCodecInfo, myEncoderParameters);
}
private static ImageCodecInfo GetEncoderInfo(String mimeType)
{
int j;
ImageCodecInfo[] encoders;
encoders = ImageCodecInfo.GetImageEncoders();
for (j = 0; j < encoders.Length; ++j)
{
if (encoders[j].MimeType == mimeType)
return encoders[j];
}
return null;
}
What is ASPNetSqlProvider? and How to provide your custom Role provider?
|
While developing a ASP.NET web application you might have come across ASPNetSqlProvider a number of times. This provider stores the membership information. In other words if you are building a user login based application, and you are using the built in ASP.NET Configuration Manager, then you are using ASPNetSqlProvider. |
![]() |
The AspNetSqlProvider is what stores the membership (users), roles, provider information. This defaults to an SQL Express database in your applications App_Data directory.
ASP.NET 2.0 includes a number of built-in “building block” application services. They include:
- A membership API for managing usernames/passwords and secure credential management.
- A roles API that supports mapping users into logical groups.
- A profile API for storing arbitrary properties about both authenticated and anonymous users visiting a web site (for example: their zipcode, gender, theme preference, etc)
- A personalization API for storing control customization preferences.
- A health monitoring API that can track and collect information about the running state and any errors that occur within a web application .
- A site navigation API for defining hierarchy within an application and constructing navigation UI (menus, treeviews, bread-crumbs) that can be context specific based on where the current incoming user is in the site.
ASPNetSqlProvider is part of the Roles API. Out of the box, most of the ASP.NET 2.0 application services are configured to use the built-in SQL Express provider. This provider will automatically create and provision a new database for you the first time you use one of these application services, and provides a pretty easy way to get started.
If you want to use a SQL Server 2000 or 2005 database instance instead of SQL Express then There is a free utility that you can use.
Following are the steps to use a custom SQL Server 2000 or 2005 database instance -
- Open a command-line window on your system and run the aspnet_regsql.exe utility that is installed with ASP.NET 2.0 in under your C:\WINDOWS\Microsoft.NET\Framework\v2.0.xyz directory.
- Just follow the steps on the next screens to extract the schema to your SQL Database.
Once the above mentioned is done you can use the following settings in your web.config to override the default AspNetSqlProvider settings in machine.config
<roleManager enabled=”true” defaultProvider=”AspNetSqlRoleProvider”>
<providers>
<remove name=”AspNetSqlRoleProvider”/>
<add connectionStringName=”myconn”
applicationName=”YourAppName” name=”AspNetSqlRoleProvider”
type=”System.Web.Security.SqlRoleProvider” />
</providers>
</roleManager>
[NOTE: Failure to override default AspNetSqlProvider might get you following error:]
Could not establish a connection to the database. If you have not yet created the SQL Server database, exit the Web Site Administration tool, use the aspnet_regsql command-line utility to create and configure the database, and then return to this tool to set the provider.
<roleManager>
Line 148: <providers>
Line 149: <add name=”AspNetSqlRoleProvider” connectionStringName=”LocalSqlServer” applicationName=”/” type=”System.Web.Security.SqlRoleProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a”/>
Line 150: <add name=”AspNetWindowsTokenRoleProvider” applicationName=”/” type=”System.Web.Security.WindowsTokenRoleProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a”/>
Line 151: </providers>
If you look at your computer’s Machine.Config file which can be found at following path -
(C:\WINDOWS\Microsoft.Net\Framework\<version>\CONFIG\machine.config)
you’ll see that the default configuration for the membership providers references a connection string labeled “LocalSqlServer”. If you do not override this configuration in your web.config file, your ASP.NET app will try to use these settings to access membership resources.
To fix this, you need to do one of two things:
- Update your machine.config to make “LocalSqlServer” point to the correct database where you installed the membership objects
- Add settings to your web.config to override your machine.config. Those settings may look something like this:
<membership>
<providers>
<clear/>
<add name=”AspNetSqlMembershipProvider” type=”System.Web.Security.SqlMembershipProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a” connectionStringName=”DbConnString” enablePasswordRetrieval=”false” enablePasswordReset=”true” requiresQuestionAndAnswer=”false” applicationName=”/” requiresUniqueEmail=”true” passwordFormat=”Hashed” maxInvalidPasswordAttempts=”15″ minRequiredPasswordLength=”4″ minRequiredNonalphanumericCharacters=”0″ passwordAttemptWindow=”10″ passwordStrengthRegularExpression=”"/>
</providers>
</membership>
Where “<clear/>” removes any settings made by your machine.config and “DbConnString” is the name of a connection string in your web.config.
How to use iTextSharp .NET PDF library to insert text and image in an existing PDF form template
October 17, 2008 by MK
Filed under ASP.NET, C# / ASP.NET
This is my second post regarding iTextSharp PDF creation and manipulation. I have recently being involved in a web application where we have created a number of PDF’s with data coming from different feeds. In addition to my earlier post Using Open Source iTextSharp .NET PDF library to generate PDF on the fly - here is more info on using the iTextSharp library to generate PDF’s dynamically.
Here is the code that I have used to manipulate an existing PDF template and to insert text and image in the PDF template using iTextSharp. Code is quite self explanatory with some comments. In case you have questions please leave me a comment or leave a QUESTION IN MY FORUM UNDER ITEXTSHARP and I will reply back with answers. |
You will first need the PDF file template for this method. You can easily create the template and form fields with Adobe Acrobat. The next step is quite simple. Read PDF file from disk, create instance of PDFStamper class, fill out the PDF form fields. Finally flatten the generated PDF file and save it to disk (or stream to client if necessary).
For those who are not familiar with iTextSharp. iTextSharp is a C# port of a Java library written to support the creation and manipulation of PDF documents. The project is available for download through SourceForge.net. With the iTextSharp DLL, it is possible to not only populate fields in an existing PDF document, but also to dynamically create PDFs.
You can use Adobe Acrobat professional to create a PDF form template. Follow these easy steps to create one -
Open your “template” pdf file to which you want to add text.
Click on the Form toolbar and add the form text fields to your pdf and give each of the fields names according to what text will be put in the field.
Then make the appropriate tweaks to the formatting and alignment with the ‘Appearance’ and ‘Options’ tabs of the ‘Text Field Properties’ window.
Now you should have a pdf with form text fields in it for each of the areas on the pdf in which you want text and images displayed.
Please make sure you add REFERENCE to iTextSharp DLL before you test the following code.
/////////////////FYI: Framework used - .NET 3.5///////////////////
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.IO;
using System.Xml;
using System.Xml.Linq;
using iTextSharp.text;
using iTextSharp.text.pdf;
using System.Text;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
CreatePDFDocument();
}
/// <summary>
/// Creates the PDF document with a given content at a given location.
/// </summary>
/// <param name=”strFilePath”>The file path to write the new PDF to.</param>
/// <param name=”strContent”>Content in HTML to write to the PDF.</param>
public void CreatePDFDocument()
{
string pdfTemplate = @”F:\pdf_redesign\testFinal.pdf”;
string imagePath = String.Empty;
imagePath = @”F:\pdf_redesign\community.jpg”;
PdfReader pdfReader = null;
// Create the form filler
FileStream pdfOutputFile = new FileStream(pdfTemplate, FileMode.Create);
pdfReader = new PdfReader(@”F:\Websites\pdf_redesign\testTemplate.pdf”);
PdfStamper pdfStamper = null;
pdfStamper = new PdfStamper(pdfReader, pdfOutputFile);
// Get the form fields
AcroFields testForm = pdfStamper.AcroFields;
// Fill the form
testForm.SetField(”textBox1″, “This is PDF generation test from coolwebdeveloper.com using iTextSharp PDF library”);
testForm.SetField(”textBox2″, “This is PDF generation test from coolwebdeveloper.com using iTextSharp PDF library”);
iTextSharp.text.Image instanceImg = iTextSharp.text.Image.GetInstance(imagePath);
PdfContentByte overContent = pdfStamper.GetOverContent(1);
//Specifying the name of the field wehere this image will be placed
float[] imageArea = testForm.GetFieldPositions(”testImage1″);
iTextSharp.text.Rectangle imageRect = new Rectangle(imageArea[1], imageArea[2], imageArea[3], imageArea[4]);
instanceImg.ScaleToFit(imageRect.Width, imageRect.Height);
instanceImg.SetAbsolutePosition(imageArea[3] - instanceImg.ScaledWidth + (imageRect.Width - instanceImg.ScaledWidth) / 2, imageArea[2] + (imageRect.Height - instanceImg.ScaledHeight) / 2);
overContent.AddImage(instanceImg);
//’Flatten’ (make the text go directly onto the pdf) and close the form
pdfStamper.FormFlattening = true;
pdfStamper.Close();
pdfReader.Close();
}
}
///////////////////////////////////////////////
Using Open Source iTextSharp .NET PDF library to generate PDF on the fly
Quite recently I worked on a project to generate a number of PDF’s from a single page template with data coming from an XML file. I searched for a number of options to convert an existing HTML page to PDF using .NET Open Source libraries. But I was not able to render the page correctly, my page was pure XHTML and a lot of libraries were not rendering the TAGS right. And as a result the PDF generating was all messed up with content and images everywhere.
That is when I decided to generate PDF on the fly and not converting, i.e. writing content directly to the PDF instead of converting PDF from an existing HTML page. I will be writing more about the code to fill a PDF with data using FORM elements as placeholders in the PDF in the coming days. Right now I am pasting a quick script, this is what I used initially as a test to generate and create the PDF from scratch. |
Please first ADD REFERENCE to iTextSharp DLL to your project before running the following code.
You can get the DLL by CLICKING HERE.
And here is the Home Page of ItextSharp project on SourceForge.Net - CLICK HERE.
//////////////FYI: I am using .NET 3.5///////////////////
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.IO;
using System.Xml;
using System.Xml.Linq;
using iTextSharp.text;
using iTextSharp.text.pdf;
public partial class creator : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
CreatePDFDocument();
}
/// <summary>
/// Creates the PDF document with a given content at a given location.
/// </summary>
/// <param name=”strFilePath”>The file path to write the new PDF to.</param>
/// <param name=”strContent”>Content in HTML to write to the PDF.</param>
public static void CreatePDFDocument()
{
MemoryStream MStream = new MemoryStream();
Document document = new Document(PageSize.A4, 80, 50, 30, 65);
try
{
PdfWriter writer = PdfWriter.GetInstance(document, MStream);
document.Open();
document.Add(new iTextSharp.text.Paragraph(”This is test and must work”));
document.Close();
}
catch (Exception e)
{
throw e;
}
HttpContext.Current.Response.Buffer = true;
HttpContext.Current.Response.ClearContent();
HttpContext.Current.Response.ClearHeaders();
HttpContext.Current.Response.ContentType = “application/pdf”;
HttpContext.Current.Response.AddHeader(”Content-Disposition”, attachment;filename=myPDFNew.pdf”);
HttpContext.Current.Response.BinaryWrite(MStream.GetBuffer());
HttpContext.Current.Response.End();
}
}
////////////////////////////////















