Friday, September 25, 2015

Read from Microsoft PowerPoint file ppt

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Office.Core;
using PowerPoint = Microsoft.Office.Interop.PowerPoint;

namespace Naresh
{
    class Program
    {
        static void Main(string[] args)
        {
            Microsoft.Office.Interop.PowerPoint.Application PowerPoint_App = new Microsoft.Office.Interop.PowerPoint.Application();
            Microsoft.Office.Interop.PowerPoint.Presentations multi_presentations = PowerPoint_App.Presentations;
            Microsoft.Office.Interop.PowerPoint.Presentation presentation = multi_presentations.Open(@"C:\naresh\testing.pptx");
            string presentation_text = "";
            for (int i = 0; i < presentation.Slides.Count; i++)
            {
                foreach (var item in presentation.Slides[i+1].Shapes)
                {
                    var shape = (PowerPoint.Shape)item;
                    if (shape.HasTextFrame == MsoTriState.msoTrue)
                    {
                        if (shape.TextFrame.HasText == MsoTriState.msoTrue)
                        {
                            var textRange = shape.TextFrame.TextRange;
                            var text = textRange.Text;
                            presentation_text += text+" ";
                        }
                    }
                }
            }
            PowerPoint_App.Quit();
            Console.WriteLine(presentation_text);
        }
    }
}

Upload Files in ASP.NET MVC

<h2>Basic File Upload</h2>
@using (Html.BeginForm("Index",
                        "Home",
                        FormMethod.Post,
                        new { enctype = "multipart/form-data" }))
{
    <label for="file">Upload Image:</label>
    <input type="file" name="file" id="file" /><br><br>
    <input type="submit" value="Upload Image" />
    <br><br>
    @ViewBag.Message
}

        [HttpPost]
        public ActionResult Index(HttpPostedFileBase file)
        {
            if (file != null && file.ContentLength > 0)
                try
                {
                    string path = Path.Combine(Server.MapPath("~/Images"),
                                               Path.GetFileName(file.FileName));
                    file.SaveAs(path);
                    ViewBag.Message = "File uploaded successfully";
                }
                catch (Exception ex)
                {
                    ViewBag.Message = "ERROR:" + ex.Message.ToString();
                }
            else
            {
                ViewBag.Message = "You have not specified a file.";
            }
            return View();

        }

Thursday, September 24, 2015

A Simple CAPTCHA Image Verification in C# and ASP.Net

Captcha.ashx
<%@ WebHandler Language="C#" Class="Captcha" %>
using System;
using System.Web;
using System.Drawing;
using System.IO;
using System.Web.SessionState;

public class Captcha : IHttpHandler, IReadOnlySessionState
{
   
    public void ProcessRequest (HttpContext context) {
        Bitmap bmpOut = new Bitmap(200, 50);
        Graphics g = Graphics.FromImage(bmpOut);
        g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
        g.FillRectangle(Brushes.Black, 0, 0, 200, 50);
        g.DrawString(context.Session["Captcha"].ToString(), new Font("Verdana", 18), new SolidBrush(Color.White), 0, 0);
        MemoryStream ms = new MemoryStream();
        bmpOut.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
        byte[] bmpBytes = ms.GetBuffer();
        bmpOut.Dispose();
        ms.Close();
        context.Response.BinaryWrite(bmpBytes);
        context.Response.End();
    }

    public bool IsReusable {
        get {
            return false;
        }
    }

}
Read my previous code snippet that explains how to generate image from a string using C# and ASP.NET. The above HttpHandler uses the same code discussed in the code snippet. Rendering the contents as an image will prevent the automatic software programs from reading its contents.

How to use it in our ASPX page?

It is very simple. Include an ASPX page (Default.aspx in our example). Drag an Image control and textbox control to enter the displayed code. With the help of custom validator control, we can validate the user input with Session variable content. Refer the below code that has the ASPX markup.

Default.aspx
<div>
      <asp:CustomValidator ID="CustomValidator2" runat="server" ControlToValidate="txtVerify"
            ErrorMessage="You have Entered a Wrong Verification Code!Please Re-enter!!!" OnServerValidate="CAPTCHAValidate"></asp:CustomValidator>      
     <asp:Image ID="imCaptcha" ImageUrl="~/CAPTCHA/Captcha.ashx" runat="server" />
        <asp:TextBox ID="txtVerify" runat="server"></asp:TextBox>
        <asp:Button ID="btnSave" runat="server" OnClick="btnSave_Click" Text="Save" /></div>

Default.aspx.cs
public partial class CAPTCHA_Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        //ImageVerification
        if (!IsPostBack)
        {
            SetVerificationText();          
        }
    }
    public void SetVerificationText()
    {
        Random ran = new Random();
        int no = ran.Next();
        Session["Captcha"] = no.ToString();
    }
    protected void CAPTCHAValidate(object source, ServerValidateEventArgs args)
    {
        if (Session["Captcha"] != null)
        {
            if (txtVerify.Text != Session["Captcha"].ToString())
            {               
                SetVerificationText();
                args.IsValid = false;
                return;
            }
        }
        else
        {          
            SetVerificationText();
            args.IsValid = false;
            return;
        }
     
    }
    protected void btnSave_Click(object sender, EventArgs e)
    {
        if (!Page.IsValid)
        {
            return;
        }
            //Save the content
        Response.Write("You are not a SPAMMER!!!");
        SetVerificationText();
    }
}

The above code initializes the Session variable (Session["Captcha"]) with a random number which is then rendered as a image by the HttpHandler on execution of the page.

Block or Disable Cut, Copy and Paste operation in ASP.Net TextBox Using jQuery

<script src="_scripts/jquery-1.4.1.min.js" type="text/javascript"></script>    
    <script type="text/javascript">
        $(function() {
        $("#<% =txtEmail.ClientID %>,#<% =txtConfirmEmail.ClientID%>").bind("cut copy paste", function(event) {
                event.preventDefault();
            });
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>    
        <b>Email </b><asp:TextBox ID="txtEmail" runat="server"></asp:TextBox><br />
        <b>Confirm Email </b><asp:TextBox ID="txtConfirmEmail" runat="server"></asp:TextBox>

Read a Text File in C# and ASP.Net

string root = Server.MapPath("~");
string Template = root +"\\filetext.txt";
StringBuilder line = new StringBuilder();
using (StreamReader rwOpenTemplate = new StreamReader(Template))
{
while (!rwOpenTemplate.EndOfStream)
{
line.Append(rwOpenTemplate.ReadToEnd());
}
}