Friday, 26 December 2014

How to add Dynamically Text to Images Retrieved from the Database using an ASP.NET

In this article I am explain How to add text on image. We often create applications where we retrieve images from the database and display it on the page. At times, we may need to add some text or a copyright notice dynamically on the images.

Default.aspx

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Write Text On Image</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
         <img alt="Image" id="imgdynamitext" src="TextOnImageHandler.ashx?id=5" />
    </div>
     </form>
</body>
</html>

I am using an HttpHandler  to get images and then add some text to the retrieved images.

TextOnImageHandler.cs

<%@ WebHandler Language="C#" Class="TextOnImageHandler" %>

using System;
using System.Web;
using System.Drawing;
using System.Configuration;
using System.ComponentModel;
using System.Drawing.Imaging;
using System.Data;
using System.Data.SqlClient;

public class TextOnImageHandler : IHttpHandler {

    byte[] empPic = null;
    long seq = 0;

    public void ProcessRequest(HttpContext context)
    {
        Int32 empno;

        if (context.Request.QueryString["id"] != null)
            empno = Convert.ToInt32(context.Request.QueryString["id"]);
        else
            throw new ArgumentException("No parameter specified");

        // Convert Byte[] to Bitmap
        Bitmap newBmp = ConvertToBitmap(ShowEmpImage(empno));
        // Watermark Text to be added to image
        string text = "Asp.Net Jitendra";
        Bitmap convBmp = AddTextToImage(newBmp, text);
        convBmp.Save(context.Response.OutputStream, ImageFormat.Jpeg);
        newBmp.Dispose();
        convBmp.Dispose();
    }

    // Add Watermark Text to Image
    protected Bitmap AddTextToImage(Bitmap bImg, string msg)
    {
        // To void the error due to Indexed Pixel Format
        Image img = new Bitmap(bImg, new Size(bImg.Width, bImg.Height));
        Bitmap tmp = new Bitmap(img);
        Graphics graphic = Graphics.FromImage(tmp);
        // Watermark effect
        SolidBrush brush = new SolidBrush(Color.FromArgb(120, 255, 255, 255));
        // Draw the text string to the Graphics object at a given position.
        graphic.DrawString(msg, new Font("Times New Roman", 16, FontStyle.Italic),
             brush, new PointF(10, 30));
        graphic.Dispose();
        return tmp;
    }

    // Convert byte array to Bitmap (byte[] to Bitmap)
    protected Bitmap ConvertToBitmap(byte[] bmp)
    {
        TypeConverter tc = TypeDescriptor.GetConverter(typeof(Bitmap));
        Bitmap b = (Bitmap)tc.ConvertFrom(bmp);
        return b;
    }

    public byte[] ShowEmpImage(int empno)
    {
        string conn = ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString;
        SqlConnection connection = new SqlConnection(conn);
        string sql = "SELECT photo FROM Employees WHERE EmployeeID = @ID";
        SqlCommand cmd = new SqlCommand(sql, connection);
        cmd.CommandType = CommandType.Text;
        cmd.Parameters.AddWithValue("@ID", empno);
        connection.Open();
        SqlDataReader dr = cmd.ExecuteReader();
        if (dr.Read())
        {
            seq = dr.GetBytes(0, 0, null, 0, int.MaxValue) - 1;
            empPic = new byte[seq + 1];
            dr.GetBytes(0, 0, empPic, 0, Convert.ToInt32(seq));
            connection.Close();
        }

        return empPic;
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}

You can download Northwind database Here

Output:-




Note: I hope this article is helpful for you. Please Like and Share it.


Friday, 19 December 2014

Using Facebook authentication in ASP.NET MVC (Login With Facebook)

In this article I am explain Login with Facebook in MVC4.0. MVC 4 Provides an easy method to integrate social sites to your application. You can easily login to your site using facebook, twitter, google or microsoft with just a few line of code.


Here are the detailed steps on how its done

Before you can add Facebook login to your web application you will need To register a new Facebook application head over to the Facebook Developer page and select “Create a New App” from the Apps menu at the top of the page.
Create App: Create App using below Steps-

Step1-Click "Add a New App"

Step2-Choose below Option according your requirement


Step3: Write App Name

Step4: Choose Category


Step5:Put the Site Url

Step6:Click on the “Settings” menu in the left hand navigation bar.


Step 7: Take note of the values for the “App ID” and “App Secret” fields as your will need these when enabling Facebook login in your ASP.NET MVC application. To view the App Secret click on the “Show” button next the the app secret.And Add Your Contact Email.

Now Enabling Facebook authentication in your ASP.NET MVC Application


The next step is to add the Facebook login to your ASP.NET MVC application. For this we will create a new ASP.NET MVC application using Visual Studio. Go to File > New > Project and select the template for a new “ASP.NET Web Application” and click “OK”.

Next, select the Internet Application template

Now Open AuthConfig.cs file

Copy paste the appid and secret in authconfig file

Run the Application. Click On Login
Click On Facebook Button and you are login perfectly. But You are not getting Email of user it is Most impotant thing is pass scope=email while redirecting to the facebook oauth dialog. if you need additional fields which require user permission pass the same as parameters.

In the second function I am creating my own AuthenticationResult by calling functions from my custom facebook class
Facebook.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

using MvcApplication1Demo.Extensions;
using MvcApplication1Demo.Include;
using System.Web.Mvc;

namespace MvcApplication1Demo.Include
{
    public class Facebook
    {


        public string Facebook_GraphAPI_Token = "https://graph.facebook.com/oauth/access_token?";
        public string Facebook_GraphAPI_Me = "https://graph.facebook.com/me?";
        public string AppID = "YOUR APP ID";
        public string AppSecret = "YOUR SECRET KEY";

       
        public IDictionary<string, string> GetUserData(string accessCode, string redirectURI)
        {

            string token = Web.GetHTML(Facebook_GraphAPI_Token + "client_id=" + AppID + "&redirect_uri=" + HttpUtility.HtmlEncode(redirectURI) + "%3F__provider__%3Dfacebook" + "&client_secret=" + AppSecret + "&code=" + accessCode);
            if (token == null || token == "")
            {
                return null;
            }
            string data = Web.GetHTML(Facebook_GraphAPI_Me + "fields=id,name,email,username,gender,link&access_token=" + token.Substring("access_token=", "&"));

            // this dictionary must contains
            var userData = new Dictionary<string, string>();
            userData.Add("id", data.Substring("\"id\":\"", "\""));
            userData.Add("username", data.Substring("username\":\"", "\""));
            userData.Add("name", data.Substring("name\":\"", "\""));
            userData.Add("link", data.Substring("link\":\"", "\"").Replace("\\/","/"));
            userData.Add("gender", data.Substring("gender\":\"", "\""));
            userData.Add("email", data.Substring("email\":\"", "\"").Replace("\\u0040", "@"));
            userData.Add("accesstoken", token.Substring("access_token=", "&"));
            return userData;
        }


    }
}

Class File Web . To Read HTML from URL
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Net;
using System.IO;

namespace MvcApplication1Demo.Include
{
    public static class Web
    {
        //
        // Get HTML
        // Author : Jitendra Gangwar
        // Date : Dec 18 2014
        // Modified : Dec 18 2014
        // Changed To Static Method
        //
        public static string GetHTML(string URL)
        {
            string connectionString = URL;

            try
            {
                System.Net.HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(connectionString);
                myRequest.Credentials = CredentialCache.DefaultCredentials;
                //// Get the response
                WebResponse webResponse = myRequest.GetResponse();
                Stream respStream = webResponse.GetResponseStream();
                ////
                StreamReader ioStream = new StreamReader(respStream);
                string pageContent = ioStream.ReadToEnd();
                //// Close streams
                ioStream.Close();
                respStream.Close();
                return pageContent;
            }
            catch (Exception)
            {
            }
            return null;
        }
    }
}

Note:-I hope this article is helpfulfor you.Please Like and Share it....



Tuesday, 16 December 2014

Difference between Asp.Net MVC and Web Forms

Difference between Asp.Net MVC and Web Forms
Asp.Net Web Forms
Asp.Net MVC
Asp.Net Web Form follow a traditional event driven development model.
Asp.Net MVC is a lightweight and follow MVC (Model, View, Controller) pattern based development model.
Asp.Net Web Form has server controls.
Asp.Net MVC has html helpers.
Asp.Net Web Form supports view state for state management at client side.
Asp.Net MVC does not support view state.
Asp.Net Web Form has file-based URLs means file name exist in the URLs must have its physically existence.
Asp.Net MVC has route-based URLs means URLs are divided into controllers and actions and moreover it is based on controller not on physical file.
Asp.Net Web Form follows Web Forms Syntax
Asp.Net MVC follow customizable syntax (Razor as default)
In Asp.Net Web Form, Web Forms(ASPX) i.e. views are tightly coupled to Code behind(ASPX.CS) i.e. logic.
In Asp.Net MVC, Views and logic are kept separately.
Asp.Net Web Form has Master Pages for consistent look and feels.
Asp.Net MVC has Layouts for consistent look and feels.
Asp.Net Web Form has User Controls for code re-usability.
Asp.Net MVC has Partial Views for code re-usability.
Asp.Net Web Form has built-in data controls and best for rapid development with powerful data access.
Asp.Net MVC is lightweight, provide full control over markup and support many features that allow fast & agile development. Hence it is best for developing interactive web application with latest web standards.
Asp.Net Web Form is not Open Source.
Asp.Net Web MVC is an Open Source.

Monday, 15 December 2014

How to Move Over 10 lakh Rows in a MiliSecond in Sql Server


In this Article I am explain how to copy the contents of an entire table into another table?  Traditionally speaking, we as developers will use SELECT INTO or a INSERT INTO statement to load a destination table.  This is a still a great way of accomplishing the task at hand, but it is not nearly fast as what I am about to show you.  The method I am about to show you is not for all scenarios, but it can be very handy.

USE [Gangwar]
GO

IF EXISTS(SELECT 1 FROM sys.tables WHERE NAME = 'TestData')
BEGIN
    DROP TABLE [dbo].[TestData];
END
GO
CREATE TABLE [dbo].[TestData](
RowNum INT PRIMARY KEY,
SomeId INT,
SomeCode CHAR(2)
);
GO

INSERT INTO [dbo].[TestData]
SELECT TOP 10000000 
    ROW_NUMBER() OVER (ORDER BY t1.NAME) AS RowNumber,
    ABS(CHECKSUM(NEWID()))%2500+1 AS SomeId, 
    CHAR(ABS(CHECKSUM(NEWID()))%26+65)
    + CHAR(ABS(CHECKSUM(NEWID()))%26+65) AS SomeCode
FROM 
    Master.dbo.SysColumns t1,
    Master.dbo.SysColumns t2
GO

IF EXISTS(SELECT 1 FROM sys.tables WHERE NAME = 'NewTestData')
BEGIN
    DROP TABLE [dbo].[NewTestData];
END
GO

--Create New Table To Move Data To
CREATE TABLE [dbo].[NewTestData](
RowNum INT PRIMARY KEY,
SomeId INT,
SomeCode CHAR(2)
);
GO
--Now the fun part……. behold the power of SQL Server!!!!!!!!!!!!!!!!
--Move data to the new table
SET STATISTICS TIME ON;
SET STATISTICS IO ON;

ALTER TABLE [dbo].[TestData] SWITCH to [dbo].[NewTestData];

SET STATISTICS TIME OFF;
SET STATISTICS IO OFF;
GO

/*
 SQL Server Execution Times:
   CPU time = 0 ms,  elapsed time = 0 ms.

 SQL Server Execution Times:
   CPU time = 0 ms,  elapsed time = 1 ms.
*/
--Next, I will verify the results.
SELECT COUNT(*) FROM [dbo].[TestData]; --0
SELECT COUNT(*) FROM [dbo].[NewTestData]; --10,000,000

/*
-----------
0
(1 row(s) affected)
-----------
10000000
(1 row(s) affected)
*/