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 
----------------------------------------


File Delete using jQuery in ASP.NET

In the page body add 
<script language="javascript" type="text/javascript" src="jquery_bundle/jquery-1.9.1.js"></script>
<input id="Button1" type="button" value="delete" runat="server" onclick="deleteFile();" />
<script language="javascript" type="text/javascript">
    function deleteFile() {
        var fileName = "1st.jpg";
        $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            url: "WebService.asmx/deleteFile",
            data: "{'fileName':'" + fileName + "'}",
            dataType: "json",
            async: true,
            success: function(data) {
            alert(data.d);
            },
            error: function(result) {
                alert("Error");
            }
        });
    }
</script>
Add a webservice
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;

/// <summary>
/// Summary description for WebService
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]

public class WebService : System.Web.Services.WebService
{
    public WebService()
    {
    }
   [WebMethod]
    public IList<string> deleteFile(string fileName)
    {
        IList<string> result = new List<string>();
        try
        {
            string completePath = Server.MapPath("~/upload/" + fileName);
            if (System.IO.File.Exists(completePath))
            {
                System.IO.File.Delete(completePath);
            }
            result.Add("Y");
            return result;
        }
        catch
        {
            return null;
        }
    }
}

Monday, 27 May 2013

How to Encoding and Decoding Base64 strings in C# and SQL server


In C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
public class encode_decode
{
    public static string EncodeTo64(string toEncode)
    {
        byte[] toEncodeAsBytes = System.Text.Encoding.UTF8.GetBytes(toEncode);
        string returnValue = System.Convert.ToBase64String(toEncodeAsBytes);
        return returnValue;
    }
    public static string DecodeFrom64(string encodedData)
    {
        byte[] encodedDataAsBytes = System.Convert.FromBase64String(encodedData);
        string returnValue = System.Text.Encoding.UTF8.GetString(encodedDataAsBytes);
        return returnValue;
    }
}
In SQL server
CREATE  FUNCTION [dbo].[fn_base64_encode_decode]
(
@in_mode INT ,
@in_input VARCHAR(MAX)
)
RETURNS VARCHAR(MAX)
AS
BEGIN
DECLARE @encoded_decode_base64 VARCHAR(MAX),@source VARBINARY(MAX)
IF @in_mode = 1 --ENCODE
BEGIN
SET @source = CONVERT(VARBINARY(MAX), @in_input)
SELECT @encoded_decode_base64 = CAST(N'' AS
                xml).value('xs:base64Binary(sql:variable("@source"))', 'VARCHAR(MAX)')
END
IF @in_mode = 2 --DECODE
BEGIN
SELECT @encoded_decode_base64 = CAST(N'' AS
                xml).value('xs:base64Binary(sql:variable("@in_input"))', 'VARBINARY(MAX)')
END
RETURN @encoded_decode_base64
END

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             ...