Tuesday, May 28, 2013

Grab Youtube Images and Save it in Folder

using System;
using System.Collections.Generic;
//using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Drawing;
public partial class Default2 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
       
    }
    public System.Drawing.Image DownloadImageFromUrl(string imageUrl)
    {
        System.Drawing.Image image = null;
        try
        {
            System.Net.HttpWebRequest webRequest = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(imageUrl);
            webRequest.AllowWriteStreamBuffering = true;
            webRequest.Timeout = 30000;
            System.Net.WebResponse webResponse = webRequest.GetResponse();
            System.IO.Stream stream = webResponse.GetResponseStream();
            image = System.Drawing.Image.FromStream(stream);
            webResponse.Close();
        }
        catch (Exception ex)
        {
            return null;
        }
        return image;
    }
    protected void btnSave_Click(object sender, EventArgs e)
    {
        System.Drawing.Image image = DownloadImageFromUrl("http://img.youtube.com/vi/MnyYCyIP--c/1.jpg"); //txtUrl.Text.Trim()
         string rootPath = @"C:\DownloadedImageFromUrl";
       // string fileName = System.IO.Path.Combine(rootPath, "test.gif");
        string fileName = Server.MapPath("~/Images/" + "test.gif");//
        image.Save(fileName);
        //Note:- if gdi+ error occurs,it means, the path which u are saving does not exists or wrong path...
    }
}

How to capture web page screenshot in asp.net

Introduction

This article describes how you can take a screenshot of a special webpage programmatically with ASP.NET. The goal of this sample is to find a way to capture a webpage’s image. The parameter is just a special url. Only by knowing this url we want to be able to take a screenshot of this webpage – a bitmap of what the user would see if he/she types this url in the browser.

How to take a screenshot of browser-content?

Here I have used one utility program to take screen shot of browser content name is IECapt.exe. IECapt is a small command-line utility to capture Internet Explorer’s rendering of a web page into a BMP, JPEG or PNG image file. We have to put IECapt.exe on the server and define that we have the right to execute it. Download IECapt.exe Here is the sample application for the same. Step 1: Create the web application with two web page & in first page create screen like this

Download IECapt.exe

Here is the sample application for the same.

Step 1: Create the web application with two web page & in first page create screen like this

WebPage

Here is the html for that:

<table cellpadding="10" cellspacing="0" width="700" style="border-style:solid; background-color:green;">
llpadding="10" cellspacing="0" width="700" style="border-style:solid; background-color:green;">
           <tr>
               <td align="center" colspan="2">
                   <h1>
           Take a Snap of Web page</h1> <hr />
               </td>
           </tr>
           <tr>
               <td align="right">
                   Url:
               </td>
               <td align="left">
                   <asp:TextBox ID="txtUrl" runat="server" Width="300">http://www.google.com</asp:TextBox>
               </td>
           </tr>
           <tr>
               <td align="right">
                   Width:
               </td>
               <td align="left">
                   <asp:TextBox ID="txtWidth" runat="server">500</asp:TextBox>
               </td>
           </tr>
           <tr>
               <td align="right">
                   Height:
               </td>
               <td align="left">
                   <asp:TextBox ID="txtHeight" runat="server">500</asp:TextBox>
               </td>
           </tr>
           <tr>
               <td align="right">
                   Save image with this name :
               </td>
               <td align="left">
                   <asp:TextBox ID="txtDestImage" runat="server">MyImage3</asp:TextBox>
               </td>
           </tr>
           <tr>
               <td align="right">
               </td>
               <td align="left">
                   <asp:Button ID="btnCapture" runat="server" OnClick="btnCapture_Click" Text="Capture"
                        />
               </td>
           </tr>
       </table>



Step 2: On Button click event call the class method & redirect to new page to show the image



Code behind would be like this:



protected void btnCapture_Click(object sender, EventArgs e)
   {
       int Width, Height;
       Width = Convert.ToInt32(txtWidth.Text);
       Height = Convert.ToInt32(txtHeight.Text);
       CaptureWebPage cwp = new CaptureWebPage();
       string imagePath = cwp.GetImage(txtUrl.Text, txtDestImage.Text, Server.MapPath("~"), Width, Height);
       Response.Redirect("~/Default2.aspx?Path=" + imagePath);
   }


Step 3: Create class CaptureWebPage.cs



using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Diagnostics;
using System.Drawing.Imaging;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.IO;
 
public class CaptureWebPage
{
    private const string EXTRACTIMAGE_EXE = "IECapt.exe";
    private const int TIMEOUT = 60000;
    private const string TMP_NAME = "InBetween.png";
 
    public CaptureWebPage()
    {
    }
 
    private void Shot(string url, string rootDir)
    {
        Process p = new Process();
        p.StartInfo.FileName = rootDir + "\\" + EXTRACTIMAGE_EXE;
        p.StartInfo.Arguments = String.Format("\"{0}\" \"{1}\"", url, rootDir + "\\" + TMP_NAME);
        p.StartInfo.UseShellExecute = false;
        p.StartInfo.CreateNoWindow = false;
        p.Start();
        p.WaitForExit();
        p.Dispose();
    }
 
    private System.Drawing.Image Scale(System.Drawing.Image imgPhoto,int Width, int Height)
    {
        int srcWidth = imgPhoto.Width;
        int srcHeight = imgPhoto.Height;
        int srcX = 0; int srcY = 0;
        int destX = 0; int destY = 0;
 
        float percent = 0; float percentWidth = 0; float percentHeight = 0;
 
        percentWidth = ((float)Width / (float)srcWidth);
        percentHeight = ((float)Height / (float)srcHeight);
 
        if (percentHeight < percentWidth)
        {
            percent = percentWidth;
            destY = 0;
        }
        else
        {
            percent = percentHeight;
            destX = 0;
        }
 
        int destWidth = (int)(srcWidth * percent);
        int destHeight = (int)(srcHeight * percent);
 
        System.Drawing.Bitmap bmPhoto = new System.Drawing.Bitmap(Width,
                Height, PixelFormat.Format24bppRgb);
        bmPhoto.SetResolution(imgPhoto.HorizontalResolution,
                imgPhoto.VerticalResolution);
 
        Graphics grPhoto = Graphics.FromImage(bmPhoto);
        grPhoto.InterpolationMode =
                InterpolationMode.HighQualityBicubic;
 
        grPhoto.DrawImage(imgPhoto,
            new Rectangle(destX, destY, destWidth, destHeight),
            new Rectangle(srcX, srcY, srcWidth, srcHeight),
            GraphicsUnit.Pixel);
 
        grPhoto.Dispose();
        return bmPhoto;
    }
 
    public string GetImage(string url, string name, string rootDir, int width, int height)
    {
        string fileName = rootDir + "\\" + TMP_NAME;
        Shot(url, rootDir);
        System.Drawing.Image thumbImage = System.Drawing.Image.FromFile(fileName);
        Scale(thumbImage, width, height);
        System.Drawing.Image scaledImg = Scale(thumbImage, width, height);
        fileName = rootDir + "\\" + name + ".png";
        if (File.Exists(fileName))
            File.Delete(fileName);
        scaledImg.Save(fileName, ImageFormat.Png);
        return name + ".png";
    }
}


Step 4: Create new page Default2.aspx to display the shot taken



Here is the html for that:



<asp:Image ID="theImage" runat="server" />
 <asp:Button ID="Button1" runat="server" Text="Go Back" OnClick="Button1_Click" />


Code behind would be:



protected void Page_Load(object sender, EventArgs e)
   {
       if (Request.QueryString["Path"] != null)
       {
           theImage.ImageUrl = "~//" + Request.QueryString["Path"].ToString();
       }
   }
   protected void Button1_Click(object sender, EventArgs e)
   {
       Response.Redirect("~/Default.aspx");
   }


Step 5: Most important thing is Download IECapt.exe from the above link & put at the rool level. (place InBetween.png by default in project)



Run the Application



 



 



MyImage3





Great !!!



Now enjoy taking the snap of the web page in your web application when ever required or application demands.

Thursday, April 11, 2013

GridView CheckBox Alert

Scenario :
In GridView,when One checkBox Selected, the Same Row another CheckBox
has to be selected : 
Following is the code:
----------------------
    <asp:GridView ID="Gv1" runat="server" OnRowDataBound="Gv1_OnRowDataBound"
     OnRowCommand="Gv1_OnRowCommand" AutoGenerateColumns="false"> 
     <Columns>
     <asp:TemplateField>
     <ItemTemplate>
     <asp:CheckBox ID="chk1" runat="server" />
     </ItemTemplate>
     </asp:TemplateField>
     <asp:TemplateField>
     <ItemTemplate>
     <asp:Label ID="lblName" runat="server"></asp:Label>
     </ItemTemplate>
     </asp:TemplateField>
     <asp:TemplateField>
     <ItemTemplate>
     <asp:CheckBox ID="chk2" runat="server" />
     </ItemTemplate>
     </asp:TemplateField>
     </Columns>
     </asp:GridView>
<asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="btnSubmit_Click" OnClientClick="return validate();" />
 
----------------------------------------------------------\
Javascript
------------
<script type="text/javascript">
        function validate() {
            var isValid = false;
            var gridView = document.getElementById('Gv1');
            for (var i = 1; i < gridView.rows.length; i++) {
                var inputs = gridView.rows[i].getElementsByTagName('input');
                if (inputs != null) {
                    if (inputs[1].type == "checkbox") {
                        if (inputs[1].checked) {
                            if (inputs[0].checked == false) {
                                alert("Please select atleast one checkbox");
                            }
                            else {
                                isValid = true;
                                return true;
                            }
                            
                        }
                    }
                }
            }
            alert("Please select atleast one checkbox");
            return false;
        }
    </script>


Output:



-----------



GridView_Image

Wednesday, March 27, 2013

Save DateTime in dd/MM/yyyy format

  //this.Text = "22/11/2009";
        string CreatedDate = DateTime.Now.ToString("dd/MM/yyyy");
        string LastUpdatedDate = DateTime.Now.ToString("dd/MM/yyyy");
        string CreatedTime = DateTime.Now.ToString("hh:mm:ss");  //txtStartTime.Text
        string FinalDateTime = CreatedDate + " " + CreatedTime;
        DateTime CreatedDates = DateTime.ParseExact(FinalDateTime, "dd/MM/yyyy hh:mm:ss", null);
        DateTime LastUpdatedDates = DateTime.ParseExact(CreatedDate, "dd/MM/yyyy", null);
        objUserDetail.CreateDate = CreatedDates;
        objUserDetail.LastUpdatedDate = LastUpdatedDates;
        Repository.UserProvider.Save(objUserDetail);
Use the following code for dd/MM/yyyy:
---------------------------------------
string format = "dd/MM/yyyy"; 
DateTime dt = DateTime.ParseExact(dateString, format, provider);
Use the following code for MM/dd/yyyy:
-------------------------------------
string format = "MM/dd/yyyy"; 
DateTime dt = DateTime.ParseExact(dateString, format, provider);

Thursday, March 21, 2013

Asp.Net Xml-Xslt Template

Default.aspx
----------------
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="EmailSend.aspx.cs" Inherits="DUMMY_EmailSend" %>
<!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:Button ID="btnSend" runat="server" Text="Email Template" OnClick="btnSend_Click"/>
    </div>
    </form>
</body>
</html>


Default.aspx.cs
-----------------
protected void btnSend_Click(object sender, EventArgs e)
    {
       // WebRegistration regApplicant = new WebRegistration();
        string ImageOutput = "1";
        bool bEmailSent = GenericEmailProvider.SendRealtorRegistrationAcknowledgementEmail(ImageOutput);
    }


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;
using System.IO;
/// <summary>
/// Summary description for GenericEmailProvider
/// </summary>
public class GenericEmailProvider
{
    public static bool SendRealtorRegistrationAcknowledgementEmail(string ImageOutput)
    {
        bool bResult = true;
        string WebPageUrl = "http://localhost/TestApp/";
        string xslFileName = HttpContext.Current.Server.MapPath("~/EmailTemplates/XsltTemplates/RealtorsRegistrationAcknowledgement.xslt");
        string xslContent = File.ReadAllText(xslFileName);
        StringBuilder sbHTML = new StringBuilder();
        sbHTML.Append("<Email>");
        if (ImageOutput == "1")
        {
            sbHTML.AppendFormat("<IsUrl>{0}</IsUrl>", "1");
            sbHTML.AppendFormat("<imagepath1>{0}</imagepath1>", "http://www.google.com/Default.aspx?ID=1");
        }
        if (ImageOutput == "0")
        {
            sbHTML.AppendFormat("<IsUrl>{0}</IsUrl>", "0");
            sbHTML.AppendFormat("<imagepath1>{0}</imagepath1>", "http://www.yahoo.com/Default.aspx?ID=1");
        }
        //Test.Mail objMail = new Test.Mail();
        //sbHTML.AppendFormat("<Firstname>{0}</Firstname>", regApplicant.FirstName);
        //bool check = false;
        //sbHTML.AppendFormat("<IsUrlorName>{0}</IsUrlorName>", check ? "1" : "0");
        //sbHTML.AppendFormat("<Lastname>{0}</Lastname>", regApplicant.LastName);
        //sbHTML.AppendFormat("<Reference>{0}</Reference>", regApplicant.AddressId.ToString());
        //sbHTML.AppendFormat("<EmailAddress>{0}</EmailAddress>", regApplicant.Email);
        //sbHTML.AppendFormat("<WebUrl>{0}</WebUrl>", WebPageUrl);
        
        sbHTML.Append("</Email>");
        //objMail.Subject = "test.com - Registration Acknowledgement";
        string transformedEmailText = XslTransformation.TransformXMLtoXsl(sbHTML.ToString(), xslContent);
        //objMail.FromAddress = "noreply@test.com";
        //objMail.To.Add(regApplicant.Email);
        //objMail.Body = transformedEmailText;
        //objMail.SenderName = "noreply@test.com ";
        //try
        //{
        //    objMail.SendEmail(regApplicant.Email, "test.com - Registration Acknowledgement", transformedEmailText);
        //}
        //catch (Exception appError)
        //{
        //    bResult = false;
        //}
        return bResult;
    }
}


XslTransformation.cs
----------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;
using System.Xml.Xsl;
using System.IO;
using System.Xml;
using System.Xml.XPath;
/// <summary>
/// Summary description for XslTransformation
/// </summary>
public class XslTransformation
{
    public static string TransformXMLtoXsl(string xmlDoc, string xslDoc)
    {
        return XslTransformation.TransformXMLtoXsl(xmlDoc, xslDoc, null);
    }
    public static string TransformXMLtoXsl(string xmlDoc, string xslDoc, Dictionary<string, object> xslArgs)
    {
        StringBuilder sbOutput = new StringBuilder();
        try
        {
            XsltArgumentList argList = new XsltArgumentList();
            if (xslArgs != null)
            {
                foreach (KeyValuePair<string, object> de in xslArgs)
                {
                    argList.AddParam(de.Key, string.Empty, de.Value);
                }
            }
            //read xml string
            TextReader trEmail = new StringReader(xmlDoc);
            XmlTextReader xtrEmailXml = new XmlTextReader(trEmail);
            XPathDocument xmlPathDoc = new XPathDocument(xtrEmailXml);
            //read xsl
            TextReader trXsl = new StringReader(xslDoc);
            XmlTextReader xtrXslEmailTemplate = new XmlTextReader(trXsl);
            XslCompiledTransform xslTransform = new XslCompiledTransform();
            xslTransform.Load(xtrXslEmailTemplate);
            //Output stream
            TextWriter twOut = new StringWriter(sbOutput);
            xslTransform.Transform(xmlPathDoc, argList, twOut);
            xslTransform = null;
        }
        catch (Exception error)
        {
            throw new ApplicationException(string.Format("Transformation Error : {0}", error.Message), error);
        }
        return sbOutput.ToString();
    }
}


EmailTemplates/XsltTemplates/RealtorsRegistrationAcknowledgement.xslt
-----------------------------------------------------------------------
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:template match="/">
    <html xmlns="http://www.w3.org/1999/xhtml">
      <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>Domain Authorization Code</title>
        <style type="text/css">            p{ margin-bottom: 12px;            margin-top: 12px;            }            a:link{color:#999;}          </style>
      </head>
      <body>
        <table border="0" cellspacing="0" cellpadding="0" style="width: 100%;">
          <tr>
            <td width="50%">              </td>
            <td style="width: 600px; padding: 20px 15px 0px 15px; background: #ebebeb;">
              <!--MainEmailContent starts here-->
              <table border="0" cellspacing="0" cellpadding="0" style="width: 600px; margin: 20px 0 0 0;                      background: #fff;">
                
                
                <tr>
                  <td>
                    <table width="100%" style="background-color:blue">
                      <tr>
                        <td style="padding: 0 10px 0px; 10px;">
                          <xsl:if test="Email/IsUrl = 0">
                            <xsl:variable name="cname" select="Email/imagepath1"/>
                            <a href="{$cname}">Contact Us</a>
                          </xsl:if>
                          <xsl:if test="Email/IsUrl = 1">
                            <xsl:variable name="cname" select="Email/imagepath1"/>
                            <a href="{$cname}">Contact Us</a>
                          </xsl:if>
                        </td>
                      </tr>
                    </table>
                  </td>
                </tr>
             
              </table>
              <!--Main Email Content Ends -->
            </td>
            <td width="50%">              </td>
          </tr>
        </table>
      </body>
    </html>
  </xsl:template>
</xsl:stylesheet>


 



Output:



-----------



 



image