Monday 29 July 2013

Split in SQL

CREATE FUNCTION dbo.Split(@String nvarchar(4000), @Delimiter char(1))
RETURNS @Results TABLE (Items nvarchar(4000))
AS
BEGIN
DECLARE @INDEX INT
DECLARE @SLICE nvarchar(4000)

SELECT @INDEX = 1
WHILE @INDEX !=0
BEGIN
-- GET THE INDEX OF THE FIRST OCCURENCE OF THE SPLIT CHARACTER
SELECT @INDEX = CHARINDEX(@Delimiter,@STRING)
-- NOW PUSH EVERYTHING TO THE LEFT OF IT INTO THE SLICE VARIABLE
IF @INDEX !=0
SELECT @SLICE = LEFT(@STRING,@INDEX - 1)
ELSE
SELECT @SLICE = @STRING
-- PUT THE ITEM INTO THE RESULTS SET
INSERT INTO @Results(Items) VALUES(@SLICE)

SELECT @STRING = RIGHT(@STRING,LEN(@STRING) - @INDEX)

IF LEN(@STRING) = 0 BREAK
END
RETURN
END

Monday 22 July 2013

Get Client IP Address in SQL Server

CREATE FUNCTION [dbo].[GetCurrentIP] ()
RETURNS varchar(255)
AS
BEGIN
    DECLARE @IP_Address varchar(255);
 
    SELECT @IP_Address = client_net_address
    FROM sys.dm_exec_connections
    WHERE Session_id = @@SPID;
 
    Return @IP_Address;
END

Sunday 21 July 2013

Error Log in Asp.net C#

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.IO;
using System.Globalization;

/// <summary>
/// Summary description for ErrHandler
/// </summary>
public class ErrHandler
{
    public ErrHandler()
    {
        //
        // TODO: Add constructor logic here
        //
    }

    /// Handles error by accepting the error message
    /// Displays the page on which the error occured
    public static void WriteError(string errorMessage)
    {
        try
        {
            string path = "~/Error/" + DateTime.Today.ToString("yyyy-MM-dd") + ".txt";
            if (!File.Exists(System.Web.HttpContext.Current.Server.MapPath(path)))
            {
                File.Create(System.Web.HttpContext.Current.Server.MapPath(path)).Close();
            }
            using (StreamWriter w = File.AppendText(System.Web.HttpContext.Current.Server.MapPath(path)))
            {
                w.WriteLine("\r\nLog Entry : ");
                w.WriteLine("{0}", DateTime.Now.ToString(CultureInfo.InvariantCulture));
                string err = "Error in: " + System.Web.HttpContext.Current.Request.Url.ToString() +
                              ". Error Message:" + errorMessage;
                w.WriteLine(err);
                w.WriteLine("__________________________");
                w.Flush();
                w.Close();
            }
        }
        catch (Exception ex)
        {
            WriteError(ex.Message);
        }

    }
}

Embed mail with Gmail

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

<!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>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Button ID="SendMail" runat="server" Text="Send Mail"
            onclick="SendMail_Click" />
    </div>
    </form>
</body>
</html>

CS Page
-------
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.Xml.Linq;
using System.Collections.Specialized;
using System.Net.Mail;
using System.Text;
using System.IO;

public partial class EmbedMail : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void SendMail_Click(object sender, EventArgs e)
    {
        SendHTMLMail();
    }

    // Method Which is used to Get HTML File and replace HTML File values with dynamic values and send mail
    public void SendHTMLMail()
    {
        //StreamReader reader = new StreamReader(Server.MapPath("~/top.html"));
        StreamReader reader = new StreamReader(Server.MapPath("~/MailContent.aspx"));
        string readFile = reader.ReadToEnd();
        string myString = "";
        myString = readFile;
    
        MailMessage Msg = new MailMessage();
       // MailAddress fromMail = new MailAddress("");
        // Sender e-mail address.
        Msg.From = fromMail;
        // Recipient e-mail address.
        Msg.To.Add(new MailAddress("To email id"));
        // Subject of e-mail
        Msg.Subject = "Send Mail with HTML File";
        Msg.Body = myString.ToString();
        Msg.IsBodyHtml = true;
        string sSmtpServer = "";
       
        sSmtpServer = "smtp.gmail.com";

        SmtpClient a = new SmtpClient();
        a.Host = sSmtpServer;
        a.Port = 587;
        a.Credentials = new System.Net.NetworkCredential("Your gmail id", "Your Password");
        a.EnableSsl = true;
        a.Send(Msg);
        reader.Dispose();
    }
}

Resize Image

ASPX Page
-------------
<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!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>Generate a Thumbnails from Uploaded Image</title>
<script type="text/javascript" src="lightbox.js"></script>
<link href="lightbox.css" rel="stylesheet" type="text/css" />
</head>
<body>
<form id="form1" runat="server">
<div>
Height :
    <asp:TextBox ID="txtHeight" runat="server"></asp:TextBox>
    Weidth :
    <asp:TextBox ID="txtWeidth" runat="server"></asp:TextBox>
    <br />
<asp:FileUpload ID="fileupload1" runat="server" />
<asp:Button ID="btnsave" runat="server" Text="Upload" onclick="btnsave_Click" />
</div>
<div>
<asp:DataList ID="dtlist" runat="server" RepeatColumns="3" CellPadding="5">
<ItemTemplate>
<asp:Image ID="Image1" ImageUrl='<%# Bind("Name", "~/Images/{0}") %>' runat="server" Height="180px" Width="160px"/>
<br />
<asp:HyperLink ID="HyperLink1" Text='View'  style="text-decoration:none" rel="lightbox" Target="_blank"  NavigateUrl='<%# Bind("Name", "~/Images/{0}") %>' runat="server"/>
</ItemTemplate>
<ItemStyle BorderColor="Brown" BorderStyle="dotted" BorderWidth="3px" HorizontalAlign="Center"
VerticalAlign="Bottom" />
</asp:DataList>
</div>
</form>
</body>
</html>

CS Page
---------
using System;
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.Xml.Linq;

using System.Collections;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.IO;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindDataList();
        }
    }
    protected void BindDataList()
    {
        DirectoryInfo dir = new DirectoryInfo(MapPath("Images"));
        FileInfo[] files = dir.GetFiles();
        ArrayList listItems = new ArrayList();
        foreach (FileInfo info in files)
        {
            listItems.Add(info);
        }
        dtlist.DataSource = listItems;
        dtlist.DataBind();

    }
    protected void btnsave_Click(object sender, EventArgs e)
    {
  
        string filename = Path.GetFileName(fileupload1.PostedFile.FileName);
        string targetPath = Server.MapPath("Images/" +System.DateTime.Now.ToString("yyyyMMddhhmmss")+"_"+filename);
        Stream strm = fileupload1.PostedFile.InputStream;
        var targetFile = targetPath;
        //Based on scalefactor image size will vary
        GenerateThumbnails(0.5, strm, targetFile);
        BindDataList();
    }
    private void GenerateThumbnails(double scaleFactor, Stream sourcePath, string targetPath)
    {
        using (var image = System.Drawing.Image.FromStream(sourcePath))
        {
            //var newWidth = (int)(image.Width * scaleFactor);
            //var newHeight = (int)(image.Height * scaleFactor);

            var newWidth = Convert.ToInt32(this.txtWeidth.Text.Trim());
            var newHeight = Convert.ToInt32(this.txtHeight.Text.Trim());
            var thumbnailImg = new Bitmap(newWidth, newHeight);
            var thumbGraph = Graphics.FromImage(thumbnailImg);
            thumbGraph.CompositingQuality = CompositingQuality.HighQuality;
            thumbGraph.SmoothingMode = SmoothingMode.HighQuality;
            thumbGraph.InterpolationMode = InterpolationMode.HighQualityBicubic;
            var imageRectangle = new Rectangle(0, 0, newWidth, newHeight);
            thumbGraph.DrawImage(image, imageRectangle);
            thumbnailImg.Save(targetPath, image.RawFormat);
        }
    }
}