SUBSCRIBE - [ Tech News ] [ Make Money Blogging Tips ] [ Online Marketing Tips ] [ Web Dev News ]
Powered by MaxBlogPress  

Apps running from Network Share run under Full Trust in .NET 3.5 SP1

July 16, 2009 by MK  
Filed under C# / ASP.NET, web development

image .NET 3.5 contains a change to the default grant set, applications launched from Local Intranet Zone will now run under Full Trust. This make the user experience and trust levels as if the app is launched from the local computer itself.

How this works?

When an .exe is launched directly off a network share, rather than giving it the Zone evidence of [Local Intranet], framework instead give the Zone evidence of [My Computer].  This causes the .exe to match the default [My Computer] code group rather than the [Local Intranet] group, and by default CAS policy grants Full Trust to that code group.  

In addition to the entry point .exe of the application, framework also extend [My Computer] evidence to any assembly loaded from the same directory as the .exe.  So, if you place any managed DLL’s immediately next to your .exe, those will also all be given Full Trust by default in .NET 3.5 SP1.

Will this work for DLL’s in sub directories?

And the answer is NO.

It will only work for assemblies loaded from the same directory as the entry point application. Apps that need to load assemblies from different sub directories or other network shares may not see all of their assemblies get fully trusted by default.  For these type of applications, [Click Once] deployment is the recommended way to grant Full Trust.

Articles explaining Full Trust -

As per msdn web site -

Assemblies which will now receive Zone evidence of [My Computer] and therefore be fully trusted by default are:

  • Any managed .exe which is launched directly from a network share
  • Any assembly in that .exe’s process which is loaded from the same directory as the .exe itself was.

Assemblies which will not see this change include:

  • Assemblies loaded from a subdirectory of the share where the .exe was launched from
  • Assemblies loaded from shares other than the one where the main .exe was launched
  • Any assembly loaded on a machine with the LegacyMyComputer registry value set to 1
  • Any assembly loaded into a CLR host, including assemblies loaded into Internet Explorer as controls.
  • Any assembly loaded from shares by an application that was launched from the "real" MyComputer zone.

What to expect in .NET 4 ?

In .NET 4.0 beta 1, Microsoft has significantly expanded this exemption, and all assemblies loaded by unhosted applications are fully trusted by default.

Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Google
  • LinkedIn
  • Reddit
  • StumbleUpon
  • Technorati
  • TwitThis
  • Yahoo! Buzz

How to retain high resolution of a dynamically created image using ASP.NET and C#

March 27, 2009 by MK  
Filed under C# / ASP.NET, web development

pie_chart Today we will discuss about maintaining high resolution of dynamically created image using ASP.NET and C#. If you want to learn how to create an image - You can view this related article for creating an image dynamically using ASP.NET and C# (This article teaches about creating pie chart but can easily be altered to create any image).

This is a two step process -

First step is to define properties while declaring the Graphics class to be used for creating the image. Following properties can be used for attaining that -

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

Second step is saving the image. For creating a high quality image we need to play around with the ImageCodecInfo class that we have created. Here we will loop through the MimeType property of encoders array and will select the matching MimeType.

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;

    }

Now we will define the response stream and the type of image we want to create.

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);

        }

As you see its quite easy to create high quality images using the Graphics class in ASP.NET. Almost everything done by using third party components can be created using built in classes with ASP.NET. Happy Coding!!.

Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Google
  • LinkedIn
  • Reddit
  • StumbleUpon
  • Technorati
  • TwitThis
  • Yahoo! Buzz

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

pie_chart 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;

}

Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Google
  • LinkedIn
  • Reddit
  • StumbleUpon
  • Technorati
  • TwitThis
  • Yahoo! Buzz

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.

Recommended reading - iText in Action: Creating and Manipulating PDF introduces iText and lowers the learning curve to its advanced features. Its numerous, valuable examples unlock many of the secrets hidden in Adobe’s PDF Reference. The examples are in Java but they can be easily adapted to .NET using one of iText’s .NET ports: iTextSharp (C#) or iText.NET (J#).

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();
 
 
    }
}

///////////////////////////////////////////////

Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Google
  • LinkedIn
  • Reddit
  • StumbleUpon
  • Technorati
  • TwitThis
  • Yahoo! Buzz