Saturday 29 December 2012

Dataset to Excel


Dataset to Excel


Use the following Code to export Dataset to Excel:


Excel.ApplicationClass excel = new ApplicationClass();

excel.Application.Workbooks.Add(true); 
DataTable table = DATASETNAME.Tables[0];
int ColumnIndex=0; 
foreach(Datacolumn col in table.Columns)
{   
   ColumnIndex++;
   excel.Cells[1,ColumnIndex]=col.ColumnName;
} 
int rowIndex=0; 
foreach(DataRow row in table.Row) 
{         
    rowIndex++;       
    ColumnIndex=0;         
    foreach(DataColumn col in table.Columns)         
    {  
        ColumnIndex++;                
        excel.Cells[rowIndex+1,ColumnIndex]=row.Cells[col.ColumnName].Text;         
    }
} 
excel.Visible = true; 
Worksheet worksheet = (Worksheet)excel.ActiveSheet; 
worksheet.Activate();
)

Determine the Version of .Net Framework in the Client System Using Javascript


Determine the Version of .Net Framework in the Client System Using Javascript


Use this javascript code snippet, which gives the version of dontnet framework installed on clients machine, its good when creating installers for the application:


<script language="JavaScript" type="text/javascript">

var a = navigator.userAgent.match(/\.NET CLR [0-9.]+/g);

if (a == null)

document.write( ".NET Framework(s) is not installed" )

else

{

document.write

( "The following versions of .NET Frameworks are installed:<br/>" )

  for (i = 0; i < a.length; ++i)

  {

     document.write( a[i] )

     document.write( "<br/>" )

  }    

}

</script>

Convert PPT to PDF using C#


Convert PPT to PDF using C#

Use this Function to convert PPT  to PDF using C#:


 public static int ConvertPowerPointToPDF()

        {

 string InputFilePath = @"C:\Users\\Desktop\tst1.pps";

            string OutputFilePath = @"C:\Users\\Desktop\tst1.pdf";

            int Errors = 0;

            Microsoft.Office.Interop.PowerPoint._Application PPApplication = null;

            Presentation PPDoc = null;

            try

            {

                // Start an instance of PowerPoint

                PPApplication = new Application();

                //PPApplication.Visible = True

                // Open the source document.

                PPDoc = PPApplication.Presentations.Open(InputFilePath);

                PPDoc.SaveAs(OutputFilePath, PpSaveAsFileType.ppSaveAsPDF);

                //PPDoc.ExportAsFixedFormat(OutputFilePath, PpFixedFormatType.ppFixedFormatTypePDF, PpFixedFormatIntent.ppFixedFormatIntentScreen, Microsoft.Office.Core.MsoTriState.msoCTrue, PpPrintHandoutOrder.ppPrintHandoutHorizontalFirst, PpPrintOutputType.ppPrintOutputBuildSlides, Microsoft.Office.Core.MsoTriState.msoFalse, , , , False, False, False, False, False)

            }

            catch (Exception ex)

            {

                //Interaction.MsgBox(ex.Message);

                //Errors = 1;

            }

            finally

            {

                // Close and release the Document object.

                if ((PPDoc != null))

                {

                    PPDoc.Close();

                    PPDoc = null;

                }

                // Quit PowerPoint and release the ApplicationClass object.

                if ((PPApplication != null))

                {

                    PPApplication.Quit();

                    PPApplication = null;

                }

                GC.Collect();

                GC.WaitForPendingFinalizers();

                GC.Collect();

                GC.WaitForPendingFinalizers();

            }

            return Errors;

        }


For Displaying the PDF in the Page:

Design Part:

<div>
<object type="application/pdf" data="<%= FileName %>" width="1024" height="768">
</div>


Code-Behind:


protected void Page_Load(object sender, EventArgs e)
{
    FileName ="tst1.pdf";
} 

Monday 24 December 2012

Convert Perl Script to C#


Convert Perl Script to C#


Make Use of the following function to convert your Perl Script to C#:


public void PerlTransFile(string filename)

{

string outDelim = ",";

char fs = '|';

Hashtable neigh = new Hashtable();

using (StreamReader sr = new StreamReader("TestFile.txt"))

{

string line;

while ((line = sr.ReadLine()) != null)

{

string[] temp = line.Split(fs);

neigh[string.Format("{1}{0}{2}{0}{3}", fs.ToString(), temp[1], temp[2], temp[3])] =

string.Format("{1}{0}{2}{0}{3}{0}{4}{0}{5}{6}",

fs.ToString(), temp[34], temp[14], temp[15], temp[32], temp[33], temp[24]);

}

foreach(string key in neigh.Keys)

{

string[] a = neigh[key].ToString().Split(',');

for(i = 0 ; i < a.Length; i++)

Console.WriteLine("{1}{0}{2}{0}{3}{0}", fs, key, i, a[ i ]);

}

}

Friday 21 December 2012

Adding Meta Tags Dynamically


Adding Meta Tags Dynamically


The easiest way to add META TAGS to the <head> element of your web page is to add it
declaratively in HTML of your ASP.NET page like this:

     <META name="Description" content="Asp.Net FAQs Home Page.">

But We can add this Programmatically like this -->

Add the following code to our Page_Init method:

    protected void Page_Init(object sender, EventArgs e)
    {
        HtmlMeta meta1 = new HtmlMeta();
        meta1.Name = "Description";
        meta1.Content = "Page description";
        this.Page.Header.Controls.Add(meta1);

        HtmlMeta meta2 = new HtmlMeta();
        meta2.Name = "Keywords";
        meta2.Content = "Asp.Net .NET";
        this.Page.Header.Controls.Add(meta2);
    }

Adding Javascript Programmatically to a Webpage


Adding Javascript Programmatically to a Webpage


Add this code to the Page_Init Event handler:

    protected void Page_Init(object sender, EventArgs e)
    {
        HtmlGenericControl js = new HtmlGenericControl("script");
        js.Attributes["type"] = "text/javascript";
        js.Attributes["src"] = "jscript/formfunctions.js";
        Page.Header.Controls.Add(js);
    }

Disable Form Submission On Enter Keypress


Disable Form Submission On Enter Keypress


All we need to do to is to add JavaScript code to the OnKeyDown event of the TextBox instance that will prevent form submission if ENTER key is pressed.

Just add this code to your Page_Init method of the page where you want this behavior:


    protected void Page_Init(object sender, EventArgs e)

    {

        TextBox1.Attributes.Add("onkeydown",

        "if(event.which || event.keyCode){if (event.keyCode == 13) return false;}");

    }

Your TextBox will continue to work like before, but if user presses ENTER key, your Web Form will not be submitted.

Thursday 20 December 2012

Validating URL Programatically Using Regex


Validating URL Programatically Using Regex


Using this Code One could check whether the URL is in existence ie., being currently hosted by any server..


public bool IsURLValid(string strURL)

{

    string strResponse = "";

    try

    {

        string pattern = @"((http|ftp|https):\/\/w{3}[\d]*.|(http|ftp|https):

        \/\/|w{3}[\d]*.)([\w\d\._\-#\(\)\[\]\\,;:]+@[\w\d\._\-#\(\)\[\]\\,;:])?

        ([a-z0-9]+.)*[a-z\-0-9]+.([a-z]{2,3})?[a-z]{2,6}(:[0-9]+)?(\/[\/a-z0-9\._\-,]+)

        *[a-z0-9\-_\.\s\%]+(\?[a-z0-9=%&\.\-,#]+)?";

        //validatng url in case if it hasn't been validated earlier

        if(Regex.IsMatch(strURL,pattern))

        {

            WebRequest request = HttpWebRequest.Create(strURL);

            request.Timeout = 5000;

            strResponse = ((HttpWebResponse)request.GetResponse()).StatusCode.ToString();

        }

    }

    catch(Exception exp)

    {

        strResponse = "";

    }

    return (strResponse=="OK")? true: false;

}

Prevent User from Opening your Webpage in Iframe Using Javascript


Prevent User from Opening your Webpage in Iframe Using Javascript


Use the following Javascript Code to prevent People from Opening your webpage/HTML page in an iframe:
(Put this javascript in between the head tag of your concerned Page)


<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

<title>Iframe Blocker</title>

<script type="text/javascript">

if( (self.parent && !(self.parent===self))

    &&(self.parent.frames.length!=0)){

    self.parent.location=document.location

}

</script>

</head>

<body>

<h1>Cannot Open in Iframe</h1>

</body>

</html>

Alternatively Use this script:


<script type="text/javascript">

//<![CDATA[

    if (window.top !== window.self) {

        document.write = "";

        window.top.location = window.self.location;

        setTimeout(function () {

            document.body.innerHTML = '';

        }, 1);

        window.self.onload = function (evt) {

            document.body.innerHTML = '';

        };

    }

//]]>

</script>

Wednesday 19 December 2012

Showing CSV/Excel Data in Gridview

Showing CSV/Excel Data in Gridview


Design Part:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default3.aspx.cs" Inherits="Default3" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head id="Head1" runat="server">

    <title>Auto Complete Example 1</title>

</head>

<body>

    <form id="form1" runat="server">

    <div>

        <asp:GridView ID="GridView1" runat="server">

        </asp:GridView>

    </div>

    </form>

</body>

</html>

Code-Behind:


using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Data.SqlClient;

using System.Configuration;

using System.Web.Services;

using System.Collections;

public partial class Default3 : System.Web.UI.Page

{

    protected void Page_Load(object sender, EventArgs e)

    {

        System.Data.Odbc.OdbcConnection Conn = null;

        System.Data.DataTable dt = new System.Data.DataTable();

        System.Data.Odbc.OdbcDataAdapter da = null;

        string strConnstr = null;

        string strImportfolder = null;

        string strFilename = null;

        strImportfolder = "E:\\rakesh\\temp\\";

        //strFilename = "test.csv";

        strFilename = "file.csv";

        //this is the csv file to be imported

        strConnstr = "Driver={Microsoft Text Driver (*.txt; *.csv)};Dbq=" + strImportfolder + ";";

        Conn = new System.Data.Odbc.OdbcConnection(strConnstr);

        da = new System.Data.Odbc.OdbcDataAdapter("select * from [" + strFilename + "]", Conn);

        da.Fill(dt);

        GridView1.DataSource = dt;

        GridView1.DataBind();

    }

}
 

Tuesday 18 December 2012

Convert DataReader To Datatable Manually

Convert DataReader To Datatable Manually


Use the following Code Snippet to convert DataReader to DataTable:


private void ConvertDataReaderToTableManually()

    {

        SqlConnection conn = null;

        try

        {

            string connString = ConfigurationManager.ConnectionStrings["NorthwindConn"].ConnectionString;

            conn = new SqlConnection(connString);

            string query = "SELECT * FROM Customers";

            SqlCommand cmd = new SqlCommand(query, conn);

            conn.Open();

            SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);

            DataTable dtSchema = dr.GetSchemaTable();

            DataTable dt = new DataTable();

            // You can also use an ArrayList instead of List<>

            List<DataColumn> listCols = new List<DataColumn>();

            if (dtSchema != null)

            {

                foreach (DataRow drow in dtSchema.Rows)

                {

                    string columnName = System.Convert.ToString(drow["ColumnName"]);

                    DataColumn column = new DataColumn(columnName, (Type)(drow["DataType"]));

                    column.Unique = (bool)drow["IsUnique"];

                    column.AllowDBNull = (bool)drow["AllowDBNull"];

                    column.AutoIncrement = (bool)drow["IsAutoIncrement"];

                    listCols.Add(column);

                    dt.Columns.Add(column);

                }

            }

            // Read rows from DataReader and populate the DataTable

            while (dr.Read())

            {

                DataRow dataRow = dt.NewRow();

                for (int i = 0; i < listCols.Count; i++)

                {

                    dataRow[((DataColumn)listCols[i])] = dr[i];

                }

                dt.Rows.Add(dataRow);

            }

            GridView2.DataSource = dt;

            GridView2.DataBind();

        }

        catch (SqlException ex)

        {

            // handle error

        }

        catch (Exception ex)

        {

            // handle error

        }

        finally

        {

            conn.Close();

        }

    }

Create DataTable Manually bind it to a Gridview


Create Datatable Manually bind it to a Gridview


Design Part:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default6.aspx.cs" Inherits="Default6" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

    <title></title>

</head>

<body>

    <form id="form1" runat="server">

    <div>

        <asp:GridView ID="GridView1" runat="server">

        </asp:GridView>

    </div>

    </form>

</body>

</html>

Code-Behind: 


using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Data;

public partial class Default6 : System.Web.UI.Page

{

    protected void Page_Load(object sender, EventArgs e)

    {

        DataSet _ds = new DataSet();

        DataTable _dt = new DataTable();

        DataRow _dr;

        try

        {

            _dt.Columns.Add(new DataColumn("srno", typeof(int)));

            _dt.Columns.Add(new DataColumn("Name", typeof(string)));

            _dt.Columns.Add(new DataColumn("Address", typeof(string)));

            _dt.Columns.Add(new DataColumn("MobileNo", typeof(int)));

            _dt.Columns.Add(new DataColumn("EmailAddress", typeof(string)));

            _dr = _dt.NewRow();

            _dr[0] = 1;

            _dr[1] = "Name1";

            _dr[2] = "Address1";

            _dr[3] = 93221489;

            _dr[4] = "EmailAddress1";

            _dt.Rows.Add(_dr);

            _ds.Tables.Add(_dt);

            GridView1.DataSource = _ds;

            GridView1.DataBind();

        }

        catch(Exception ex)

        {

        }

    }   

}
 

Sunday 16 December 2012

Test Email without Mail Server

Test Email without Mail Server


The tip I am going to share today is an old one but many developers do not know about it. Assume you are creating an application and need to test a module that sends out bulk mails, like a newsletter. Your first thought would be to configure an SMTP server to test the email module. However there is a trick that you can make use of while testing your code. Use the following setting in your web.config:
<system.net>
  <
mailSettings>
      <
smtp deliveryMethod="SpecifiedPickupDirectory">
     <specifiedPickupDirectory pickupDirectoryLocation="C:\Mails\"/>
      </smtp>
  </mailSettings>
</system.net>

The specifiedPickupDirectory element configures the local directory for a Simple Mail Transport Protocol (SMTP) server. The pickupDirectoryLocation is a directory where the application saves e-mail for later processing by the SMTP server. Make sure the directory exists before using it.
That’s it. Test this setting using the following code:
protected void btnMail_Click(object sender, EventArgs e)
{
    MailMessage message = new MailMessage("abc@somedomain.com",
        "abc@abcdefgh.com",
        "Newsletter", "This is a test mail");

    SmtpClient client = new SmtpClient("localhost");
    client.Send(message);
}
Run the application and click on the Send button. Now open the Mails folder in your C Drive and you should see your mail there. Similarly you can test your entire newsletter module without sending out mails to real email addresses.



Cool ain’t it! Just make sure that if you are using IIS, it should have read-write permissions to this folder.

Saturday 15 December 2012

Change Default Port Number in Visual Studio


Change Default Port Number in Visual Studio


When you use the ASP.NET Development Server to run a file-system Web site, by default, the Web server is invoked on a randomly selected port for localhost. For example, if you are testing a page called Default.aspx, when you run the page using the built-in ASP.NET Development Server, the URL of the page might be the following:
http://localhost:3499/Default.aspx
You do have the option to control which port is used when using the built-in development server.  The steps to specify the port to be used are slightly different depending on whether you are using a website project or a web application project.
To specify a port for the ASP.NET Development Server - WebSite / WebServices projects
  1. In Solution Explorer, click the name of the application.
  2. In the Properties pane, click the down-arrow beside Use dynamic ports and select False from the dropdown list.
    This will enable editing of the Port number property.
  3. In the Properties pane, click the text box beside Port number and type in a port number.
  4. Click outside of the Properties pane. This saves the property settings.
Each time you run a file-system Web site within Visual Web Developer, the ASP.NET Development Server will listen on the specified port.
To specify a port for the ASP.NET Development Server - Web Application project
  1. Right click the Project in the Solution Explorer, and then select “Properties”
  2. Click “Web” tab. 
  3. Check “Specific port” instead of “Auto-assign Port”.
If you want to debug with IIS, please follow the first and second steps above, and then check “Use IIS Web Server” instead of “Use Visual Studio Development Server”. Also, click the “Create Virtual Directory” button.
Note: Visual Web Developer cannot guarantee that the port you specify will be available when you run your file-system Web site. If the port is in use when you run a page, Visual Web Developer displays an error message.

Shutting down an entire Website for Maintenance


Shutting down an entire Website for Maintenance


The best way to implement this is using the app_offline.htm file. ASP.NET 2.0 has provided a fantastic functionality using which the users will automatically be redirected to the “Down for Maintenance” page. Just add an HTML file named “app_offline.htm” to the root directory of your website. Adding this file will clear the server cache. When ASP.NET sees the app_offline.htm file, it will shut-down the app-domain for the application (and not restart it for requests), and instead send back the contents of the app_offline.htm file in response to all new dynamic requests for the application.

Please take a note that the size of the file should be more that 512 bytes to be displayed. If the size of the file is less that 512 bytes, then IE browser settings need to be changed manually. The "Show Friendly HTTP Errors" check box from the Tools->Internet Options->Advanced tab within IE settings need to be unchecked. If this check-box is not unchecked and the app_offline.htm file size is less that 512 bytes, then the standard IE “Page cannot be displayed” message will be shown.

To start the website again, just remove this file from the root folder of your website. This will trigger the ASP.NET engine to cache all the page contents and display the pages.

Hope It Helps..

 :-)

Inserting Logo in Image using C#


Inserting Logo in Image using C#



if (fuProfilePic.HasFile)
                {
                   
                    //byte cmp = 2;
                    int imgSize = fuProfilePic.PostedFile.ContentLength;

                 
                    string UniqueName = "MyImg" + DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString() + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString();
                    string Path = "./Images/MyImages/" + UniqueName + fuProfilePic.FileName;
                   
                    imageName = UniqueName + fuProfilePic.FileName;
                 

                 

                    ///////////////////////////////////////////////////////////////////////////////
                    //set a working directory
                    string WorkingDirectory = Server.MapPath("~/Images/MyImages/");

                    //define a string of text to use as the Copyright message
                    string Copyright = "TEXT TO WATERMARK";

                    //SAVE UPLOADED PHOTO
                    //fuProfilePic.SaveAs(Server.MapPath(Path));

                    //create a image object containing the photograph to watermark
                    //Bitmap imgPhoto = (Bitmap)System.Drawing.Image.FromFile(WorkingDirectory + "watermark_photo.jpg", true); ACTUAL LINE OF CODE
                    Bitmap imgPhoto = new Bitmap(fuProfilePic.PostedFile.InputStream);
                    int phWidth = imgPhoto.Width;
                    int phHeight = imgPhoto.Height;

                    //create a Bitmap the Size of the original photograph
                    Bitmap bmPhoto = new Bitmap(phWidth, phHeight, PixelFormat.Format24bppRgb);

                    bmPhoto.SetResolution(imgPhoto.HorizontalResolution, imgPhoto.VerticalResolution);

                    //load the Bitmap into a Graphics object
                    Graphics grPhoto = Graphics.FromImage(bmPhoto);

                    //create a image object containing the watermark
                    Bitmap imgWatermark = new Bitmap(WorkingDirectory + "logo.png");
                    int wmWidth = imgWatermark.Width;
                    int wmHeight = imgWatermark.Height;

                    //------------------------------------------------------------
                    //Step #1 - Insert Copyright message
                    //------------------------------------------------------------

                    //Set the rendering quality for this Graphics object
                    grPhoto.SmoothingMode = SmoothingMode.AntiAlias;

                    //Draws the photo Image object at original size to the graphics object.
                    grPhoto.DrawImage(
                        imgPhoto,                               // Photo Image object
                        new Rectangle(0, 0, phWidth, phHeight), // Rectangle structure
                        0,                                      // x-coordinate of the portion of the source image to draw.
                        0,                                      // y-coordinate of the portion of the source image to draw.
                        phWidth,                                // Width of the portion of the source image to draw.
                        phHeight,                               // Height of the portion of the source image to draw.
                        GraphicsUnit.Pixel);                    // Units of measure

                    //-------------------------------------------------------
                    //to maximize the size of the Copyright message we will
                    //test multiple Font sizes to determine the largest posible
                    //font we can use for the width of the Photograph
                    //define an array of point sizes you would like to consider as possiblities
                    //-------------------------------------------------------
                    int[] sizes = new int[] { 16, 14, 12, 10, 8, 6, 4 };

                    Font crFont = null;
                    SizeF crSize = new SizeF();

                    //Loop through the defined sizes checking the length of the Copyright string
                    //If its length in pixles is less then the image width choose this Font size.
                    for (int i = 0; i < 7; i++)
                    {
                        //set a Font object to Arial (i)pt, Bold
                        crFont = new Font("arial", sizes[i], FontStyle.Bold);
                        //Measure the Copyright string in this Font
                        crSize = grPhoto.MeasureString(Copyright, crFont);

                        if ((ushort)crSize.Width < (ushort)phWidth)
                            break;
                    }

                    //Since all photographs will have varying heights, determine a
                    //position 5% from the bottom of the image
                    int yPixlesFromBottom = (int)(phHeight * .05);

                    //Now that we have a point size use the Copyrights string height
                    //to determine a y-coordinate to draw the string of the photograph
                    float yPosFromBottom = ((phHeight - yPixlesFromBottom) - (crSize.Height / 2));

                    //Determine its x-coordinate by calculating the center of the width of the image
                    float xCenterOfImg = (phWidth / 2);

                    //Define the text layout by setting the text alignment to centered
                    StringFormat StrFormat = new StringFormat();
                    StrFormat.Alignment = StringAlignment.Center;

                    //define a Brush which is semi trasparent black (Alpha set to 153)
                    SolidBrush semiTransBrush2 = new SolidBrush(Color.FromArgb(153, 0, 0, 0));

                    //Draw the Copyright string
                    grPhoto.DrawString(Copyright,                 //string of text
                        crFont,                                   //font
                        semiTransBrush2,                           //Brush
                        new PointF(xCenterOfImg + 1, yPosFromBottom + 1),  //Position
                        StrFormat);

                    //define a Brush which is semi trasparent white (Alpha set to 153)
                    SolidBrush semiTransBrush = new SolidBrush(Color.FromArgb(153, 255, 255, 255));

                    //Draw the Copyright string a second time to create a shadow effect
                    //Make sure to move this text 1 pixel to the right and down 1 pixel
                    grPhoto.DrawString(Copyright,                 //string of text
                        crFont,                                   //font
                        semiTransBrush,                           //Brush
                        new PointF(xCenterOfImg, yPosFromBottom),  //Position
                        StrFormat);                               //Text alignment



                    //------------------------------------------------------------
                    //Step #2 - Insert Watermark image
                    //------------------------------------------------------------

                    //Create a Bitmap based on the previously modified photograph Bitmap
                    Bitmap bmWatermark = new Bitmap(bmPhoto);
                    bmWatermark.SetResolution(imgPhoto.HorizontalResolution, imgPhoto.VerticalResolution);
                    //Load this Bitmap into a new Graphic Object
                    Graphics grWatermark = Graphics.FromImage(bmWatermark);

                    //To achieve a transulcent watermark we will apply (2) color
                    //manipulations by defineing a ImageAttributes object and
                    //seting (2) of its properties.
                    ImageAttributes imageAttributes = new ImageAttributes();

                    //The first step in manipulating the watermark image is to replace
                    //the background color with one that is trasparent (Alpha=0, R=0, G=0, B=0)
                    //to do this we will use a Colormap and use this to define a RemapTable
                    ColorMap colorMap = new ColorMap();

                    //My watermark was defined with a background of 100% Green this will
                    //be the color we search for and replace with transparency
                    colorMap.OldColor = Color.FromArgb(255, 0, 255, 0);
                    colorMap.NewColor = Color.FromArgb(0, 0, 0, 0);

                    ColorMap[] remapTable = { colorMap };

                    imageAttributes.SetRemapTable(remapTable, ColorAdjustType.Bitmap);

                    //The second color manipulation is used to change the opacity of the
                    //watermark.  This is done by applying a 5x5 matrix that contains the
                    //coordinates for the RGBA space.  By setting the 3rd row and 3rd column
                    //to 0.3f we achive a level of opacity
                    float[][] colorMatrixElements = {
                                                                                                new float[] {1.0f,  0.0f,  0.0f,  0.0f, 0.0f},
                                                                                                new float[] {0.0f,  1.0f,  0.0f,  0.0f, 0.0f},
                                                                                                new float[] {0.0f,  0.0f,  1.0f,  0.0f, 0.0f},
                                                                                                new float[] {0.0f,  0.0f,  0.0f,  0.3f, 0.0f},
                                                                                                new float[] {0.0f,  0.0f,  0.0f,  0.0f, 1.0f}};
                    ColorMatrix wmColorMatrix = new ColorMatrix(colorMatrixElements);

                    imageAttributes.SetColorMatrix(wmColorMatrix, ColorMatrixFlag.Default,
                        ColorAdjustType.Bitmap);

                    //For this example we will place the watermark in the upper right
                    //hand corner of the photograph. offset down 10 pixels and to the
                    //left 10 pixles

                    int xPosOfWm = ((phWidth - wmWidth) - 10);
                    int yPosOfWm = 10;

                    grWatermark.DrawImage(imgWatermark,
                        new Rectangle(xPosOfWm, yPosOfWm, wmWidth, wmHeight),  //Set the detination Position
                        0,                  // x-coordinate of the portion of the source image to draw.
                        0,                  // y-coordinate of the portion of the source image to draw.
                        wmWidth,            // Watermark Width
                        wmHeight,     // Watermark Height
                        GraphicsUnit.Pixel, // Unit of measurment
                        imageAttributes);   //ImageAttributes Object

                    //Replace the original photgraphs bitmap with the new Bitmap
                    imgPhoto = bmWatermark;
                    grPhoto.Dispose();
                    grWatermark.Dispose();

                    //save new image to file system.
                    imgPhoto.Save(WorkingDirectory + imageName, ImageFormat.Jpeg);
                    imgPhoto.Dispose();
                    imgWatermark.Dispose();

                    //change imageName
                    //imageName = "w".ToString() + imageName;

                    ///////////////////////////////////////////////////////////////////////////////////
                }

Interview with Andrei Ignat


Interview with Andrei Ignat




Andrei Ignat is current Microsoft MVP and one of the moderators of ASP.Net Forums.

Mr. Andrei Currently work as Senior Programmer in Ubisoft. He is an exceptional Programmer with more than 15 Years of Experience in IT Industry.

You can visit him @ his website http://msprogrammer.serviciipeweb.ro/

Here are the glimpses of the Interview:

Q1.Tell Something  About Yourself?
I am Andrei Ignat , MVP in C#. I view myself as a skilled programmer.

Q2.What do you do?
I develop applications and I learn programming.

 Q3.What is your Development Environment?
Visual Studio and more, more tools. You can find my tools at http://msprogrammer.serviciipeweb.ro/programmer-tools/
 
Q4.What is your Area of Interest?
Primary, WebDevelopment. Secondary Asp.NET MVC

Q5.How did you get started Programming?
I have had a copy of Basic. Then Visual Basic 3.0

Q6.How has the developer Community Influenced your coding?
By reading others code – and see what’s worst.

Q7. Your Role Model/Programmer?
Scott Hanselman

Q8.Your Favourite Websites and Blogs?
Any programming blogs.

Q9.Your Hobbies?
Chess , Literature, Travel, programming.

Q10.Apart from Programming what do you  do?
Teaching others.

Q11. If you were not a programmer  what would be you?
Teacher.

Q12.Your Favourite Holiday Spot?
Any sea and any mountain

Q13.Advice to New Programmers ?
Read and program.
back to top