Tuesday, 29 October 2013

Compress ViewState and remove whitespace from HTML Using baseclass

1. Create Compressor class
using System;
using System.Data;
using System.Configuration;
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.IO.Compression;
using System.IO;
public static class Compressor
{
    public static byte[] Compress(byte[] data)
    {
        MemoryStream output = new MemoryStream();
        GZipStream gzip = new GZipStream(output, CompressionMode.Compress, true);
        gzip.Write(data, 0, data.Length);
        gzip.Close();
        return output.ToArray();
    }

    public static byte[] Decompress(byte[] data)
    {
        MemoryStream input = new MemoryStream();
        input.Write(data, 0, data.Length);
        input.Position = 0;
        GZipStream gzip = new GZipStream(input, CompressionMode.Decompress, true);
        MemoryStream output = new MemoryStream();
        byte[] buff = new byte[64];
        int read = -1;
        read = gzip.Read(buff, 0, buff.Length);
        while (read > 0)
        {
            output.Write(buff, 0, read);
            read = gzip.Read(buff, 0, buff.Length);
        }
        gzip.Close();
        return output.ToArray();
    }
}
----------------------------------------------
2. create BaseClass 
using System;
using System.Data;
using System.Configuration;
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.IO;
using System.Text.RegularExpressions;
using System.Collections.ObjectModel;

public class BaseClass : Page
{
    private static readonly Regex RegexBetweenTags = new Regex(@">(?! )\s+", RegexOptions.Compiled);
    private static readonly Regex RegexLineBreaks = new Regex(@"([\n\s])+?(?<= {2,})<", RegexOptions.Compiled);

    protected override object LoadPageStateFromPersistenceMedium()
    {
        string viewState = Request.Form["__VSTATE"];
        byte[] bytes = Convert.FromBase64String(viewState);
        bytes = Compressor.Decompress(bytes);
        LosFormatter formatter = new LosFormatter();
        return formatter.Deserialize(Convert.ToBase64String(bytes));
    }
    protected override void SavePageStateToPersistenceMedium(object viewState)
    {
        LosFormatter formatter = new LosFormatter();
        StringWriter writer = new StringWriter();
        formatter.Serialize(writer, viewState);
        string viewStateString = writer.ToString();
        byte[] bytes = Convert.FromBase64String(viewStateString);
        bytes = Compressor.Compress(bytes);
        ClientScript.RegisterHiddenField("__VSTATE", Convert.ToBase64String(bytes));
    }
    protected override void Render(HtmlTextWriter writer)
    {
        using (HtmlTextWriter htmlwriter = new HtmlTextWriter(new System.IO.StringWriter()))
        {
            base.Render(htmlwriter);
            string html = htmlwriter.InnerWriter.ToString();
            html = Regex.Replace(html, @"(?<=[^])\t{2,}|(?<=[>])\s{2,}(?=[<])|(?<=[>])\s{2,11}(?=[<])|(?=[\n])\s{2,}", string.Empty);
            writer.Write(RemoveWhitespaceFromHtml(html));
        }
    }
    public static string RemoveWhitespaceFromHtml(string html)
    {
        html = RegexBetweenTags.Replace(html, ">");
        html = RegexLineBreaks.Replace(html, "<");
        return html.Trim();
    }
}
----------------------------------------------
3. Now crate a page and used 
public partial class portal : BaseClass instand of public partial class portal : System.Web.UI.Page

Thursday, 3 October 2013

How to masking in SQL server

CREATE  FUNCTION [dbo].[fn_text_masking]
(
 @in_input VARCHAR(MAX),
 @in_mask_len INT
)
RETURNS VARCHAR(MAX)
AS
BEGIN
 DECLARE @mask_text VARCHAR(MAX), @mask_char VARCHAR(20)
 SET @mask_char = 'XXXXXXXXXXXXXXXXXXXX'

 SELECT @mask_text = REPLACE(@in_input, SUBSTRING(@in_input, 1, LEN(@in_input) - @in_mask_len),
SUBSTRING(@mask_char, 1, LEN(@in_input) - @in_mask_len))

 RETURN @mask_text
END
------------------------------------------------
SELECT dbo.fn_text_masking('123456789',4)

Friday, 27 September 2013

jquery ajax call success, how do i change a global variable in the JavaScript function?

Sometimes we have problems on jquery success function.

we are assign a global variable value within the sucess function,
now we want to access that variable, we will see that variable till now hold the 1st value not taking the assign value.
How We solve the problem...

var strValue  =null;
function validateEmail() {
var obj = {
          emailText: $('#txtemail').val(),
          int_mode: 2
        };

$.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "webservice/remote_service.asmx/webserviceTestEmail",
dataType: "json",
        data: "JSON.stringify(obj),
        success: onSuccess,
        error: function(result) {
           alert("Error");
        }
      });
}

function onSuccess {
    if (result.strControlerMessage == 'n') {
      strValue = "n";
    }
    else {
      strValue = "y";
    }
}
function validateForm(){
  validateEmail();
 
  alert(strValue); /////we will see its return ""
 
}
//////////////////////////////////////////////////////////////
Solution Of this problem 
use  cache: false,
     async: false,
before jquery success

$.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "webservice/remote_service.asmx/webserviceTestEmail",
dataType: "json",
cache: false,
        async: false,
        data: "JSON.stringify(obj),
        success: onSuccess ,
        error: function(result) {
         alert("Error");
        }
      });

Sunday, 30 June 2013

Generate list of months in sqlserver

DECLARE @year INT
SET @year = 2013

;WITH mths AS(
    SELECT 1 AS mth, DATENAME(MONTH, CAST(@year*100+1 AS VARCHAR) + '01')  AS monthname
    UNION ALL
    SELECT mth+1, DATENAME(MONTH, CAST(@year*100+(mth+1) AS VARCHAR) + '01') FROM mths WHERE mth < 12
)
SELECT * FROM mths 

Monday, 10 June 2013

Send E-mail by javascript/ jquery using webservice

<style>
        /*------------------POPUPS------------------------*/#fade
        {
            display: none;
            background: #fff;
            position: fixed;
            left: 0;
            top: 0;
            z-index: 10;
            width: 100%;
            height: 100%;
            opacity: .50;
            z-index: 9999;
        }
        .popup_block
        {
            display: none;
            background: #fff;
            padding: 10px;
            border: 5px solid #ddd;
            float: left;
            font-size: 1.2em;
            position: fixed;
            top: 50%;
            left: 50%;
            z-index: 99999;
            -webkit-box-shadow: 0px 0px 20px #000;
            -moz-box-shadow: 0px 0px 20px #000;
            box-shadow: 0px 0px 20px #000;
            -webkit-border-radius: 10px;
            -moz-border-radius: 10px;
            border-radius: 10px;
        }
        img.btn_close
        {
            float: right;
            margin: -40px -40px 0 0;
        }
        .popup p
        {
            padding: 5px 10px;
            margin: 5px 0;
        }
        /*--Making IE6 Understand Fixed Positioning--*/*html #fade
        {
            position: absolute;
        }
        *html .popup_block
        {
            position: absolute;
        }
        #fade
        {
            z-index: 0;
        }
    </style>
 <script language="javascript" type="text/javascript" src="jquery_bundle/jquery-1.9.1.js"></script>
    <script language="javascript" type="text/javascript">

        jQuery.fn.EncHTML = function() {
            return String(this.html())
            .replace(/&/g, '&amp;')
            .replace(/"/g, '&quot;')
            .replace(/'/g, '&#39;')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;');
        };

        function sendMail() {
            popUp('80', 'divTaskPopup');
            var message = "";
            message = "<div> Hi i am -----------------------.";
            message += "<table align='left' border='0' cellpadding='0' cellspacing='3' width='100%'> ";
            message += " <tr> ";
            message += "<td width='250' height='34' align='left' valign='top'>";
            message += " Reason";
            message += " </td>";
            message += " <td width='313' align='left' valign='top'>";
            message += " XXXXXXX";
            message += "</td>";
            message += "</tr>";
            message += "<tr>";
            message += "<td width='250' height='34' align='left' valign='top'>";
            message += " Would you like to sing up in future ?";
            message += "</td>";
            message += "<td width='313' align='left' valign='top'>";
            message += " XXXXXXX";
            message += "</td>";
            message += "</tr>";
            message += "<tr>";
            message += "<td width='250' height='120px' align='left' valign='top'>";
            message += " Description";
            message += "</td>";
            message += "<td width='313' align='left' valign='top' colspan='3'>";
            message += " XXXXXXX XX X X X XXXX X X X X XX X X X X X X X X X XX X X";
            message += "</td>";
            message += "</tr>";
            message += "</table>";
            message += "</div>";
            //Encode HTML
            var message = $(message).EncHTML();
            $.ajax({
                type: "POST",
                contentType: "application/json; charset=utf-8",
                url: "webservice/remote_service.asmx/sendMailAnsService",
                data: "{'message':'" + message + "'}",
                dataType: "json",
                async: true,
                success: function(data) {
                    popUpClose();
                },
                error: function(result) {
                    alert("Error");
                }
            });

        }
     
        function popUp(width, popUpID) {
            var popID = popUpID;
            var popWidth = width;
            //Fade in the Popup and add close button
            $('#' + popID).fadeIn().css({ 'width': Number(popWidth) }).prepend('<a href="javascript:void(0)" class="close"><img src="../images/close_pop.png" class="btn_close" title="Close Window" alt="Close" onclick="popUpClose();" /></a>');
            //Define margin for center alignment (vertical + horizontal)
            var popMargTop = ($('#' + popID).height() + 80) / 2;
            var popMargLeft = ($('#' + popID).width() + 80) / 2;
            //Apply Margin to Popup
            $('#' + popID).css({
                'margin-top': -popMargTop,
                'margin-left': -popMargLeft
            });
            //Fade in Background
            $('body').append('<div id="fade"></div>');
            //Add the fade layer to bottom of the body tag.
            $('#fade').css({ 'filter': 'alpha(opacity=80)' }).fadeIn();
            //Fade in the fade layer
            return false;
        }
        function popUpClose() {
            $('#fade , .popup_block').fadeOut(function() {
                $('#fade, a.close').remove();
                $('#headerMessage').fadeOut();
            });
        }
   
    </script>
 <form id="form1" runat="server">
    <div>
        <input type="button" value="send" onclick="sendMail();" />
    </div>
    <div id="divTaskPopup" class="popup_block">
        <div align="center">
            <img src="http://sierrafire.cr.usgs.gov/images/loading.gif" style="height: 50px;
                width: 50px" />
        </div>
    </div>
 </form>
------remote_service
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Data.SqlClient;
using System.Web.Script.Serialization;

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class remote_service : System.Web.Services.WebService
{
    public remote_service()
    {
        //Uncomment the following line if using designed components
        //InitializeComponent();
    }

    [WebMethod]
    public IList<string> sendMailAnsService(string message)
    {
        IList<string> result = new List<string>();
        //Decode  html
        message = Server.HtmlDecode(message);
        string strSenderMailId = "xxxxxx@xxxx.com";
        string strSenderMailPassword = "xxxxxxxxxx";
        string strMailFrom = "xxxxxxxxxx";
        string strSmtpClient = "smtp.gmail.com";
        int strSmtpPort = 587;
        int r = sendMail.sendMailHandler(strSenderMailId, strSenderMailPassword, strMailFrom, strSmtpClient, strSmtpPort, "xxxxxxxxx@gmail.com", message, "testMail");
        result.Add(r.ToString());
        return result;
    }
}
---------sendMailHandler
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

public class sendMail
{
public sendMail()
{
}
    public static int sendMailHandler(string strSenderMailId, string strSenderMailPassword, string strMailFrom, string strSmtpClient, int strSmtpPort, string sendTo, string strMessage, string strSubject)
    {
        try
        {
            string emailID = strSenderMailId;
            string password = strSenderMailPassword;
            System.Net.Mail.MailMessage myMail = new System.Net.Mail.MailMessage();
            System.Net.NetworkCredential cred = new System.Net.NetworkCredential(emailID, password);
            myMail.To.Add(sendTo);
            myMail.Subject = strSubject;
            myMail.From = new System.Net.Mail.MailAddress(strMailFrom);
            myMail.IsBodyHtml = true;
            myMail.Body = strMessage;
            System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient(strSmtpClient);
            smtp.UseDefaultCredentials = false;
            smtp.Credentials = cred;
            smtp.EnableSsl = true;
            smtp.Port = strSmtpPort;
            smtp.Send(myMail);
            return 1;
        }
        catch
        {
            return 0;
        }
    }

}

Friday, 7 June 2013

Whats wrong with IsNumeric() Or Alternative of isnumeric

SQL's ISNUMERIC() function has a problem. It can falsely interpret non-numeric letters and symbols (such as D, E ,',' ), and even tabs (CHAR(9)) as numeric.like 12,90

CREATE FUNCTION dbo.isReallyNumeric
(
    @num VARCHAR(64)
)
RETURNS BIT
BEGIN
    IF LEFT(@num, 1) = '-'
        SET @num = SUBSTRING(@num, 2, LEN(@num))

    DECLARE @pos TINYINT

    SET @pos = 1 + LEN(@num) - CHARINDEX('.', REVERSE(@num))

    RETURN CASE
    WHEN PATINDEX('%[^0-9.-]%', @num) = 0
        AND @num NOT IN ('.', '-', '+', '^')
        AND LEN(@num)>0
        AND @num NOT LIKE '%-%'
        AND
        (
            ((@pos = LEN(@num)+1)
            OR @pos = CHARINDEX('.', @num))
        )
    THEN
        1
    ELSE
    0
    END
END
go
----------------------------------
CREATE FUNCTION dbo.isReallyInteger
(
    @num VARCHAR(64)
)
RETURNS BIT
BEGIN
    IF LEFT(@num, 1) = '-'
        SET @num = SUBSTRING(@num, 2, LEN(@num))

    RETURN CASE
    WHEN PATINDEX('%[^0-9-]%', @num) = 0
        AND CHARINDEX('-', @num) <= 1
        AND @num NOT IN ('.', '-', '+', '^')
        AND LEN(@num)>0
        AND @num NOT LIKE '%-%'
    THEN
        1
    ELSE
        0
    END
END
GO

Tuesday, 28 May 2013

Executing stored procedure or query through batch file

(1) Create a batch file with .bat extension.
Open a notepad and save it as .bat instead of .txt
Now this file becomes executable. I gave EXEC.bat as filename.
Write the following text inside the bat file.
----------------------------------------
@ECHO OFF
SQLCMD -S yourservername -d database_name -U username -P password -i "C:\Documents and Settings\sudiptasanyal\Desktop\TEST\some.sql" -o "C:\Documents and Settings\sudiptasanyal\Desktop\TEST\output.txt"
----------------------------------------
 SQLCMD - It is another means to execute queries and do lot more that we perform in SQL Server 
but in COMMAND PROMPT.
    -S is used to provide the server name that i'm pointing to[Here i'm pointing to my local system only].
    -d is the database.
    -U is user to provide the server username.
    -P is used to provide the server password.
    -i is used to provide input file location/path to SQLCMD from which it executes. Here i'm taking on .sql file which contains multiple queries.
    -o is used to provide output file location/path to SQLCMD where the messages from SQL Server 
----------------------------------------
(2) Now open notepad and save it with .sql extension. Write whatever queries that you want to execute here in this file which needs to be executed.
in my case i have written like this(remove these lines)
----------------------------------------
USE yourdatabasename
GO
SELECT member_id,last_name,first_name FROM tbl_member 
----------------------------------------


Get all non-clustered indexes

DECLARE cIX CURSOR FOR     SELECT OBJECT_NAME(SI.Object_ID), SI.Object_ID, SI.Name, SI.Index_ID         FROM Sys.Indexes SI             ...