Wednesday 18 December 2013

Assigning value to sqlvariable from dynamic query - SQL Server

Declare @sql nvarchar(max),
            @sql_id INT

SELECT @sql=N'SELECT TOP 1 @sql_id =colName FROM Table1'

EXEC sp_executesql @sql, N'@sql_id INT output', @sql_id output

SELECT @sql_id 

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


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

Thursday 16 May 2013

Autocomplete TextBox from database using jQuery in ASP.NET

We need to jQuery package from http://jqueryui.com/ and jQuery-UI plugin and jQuery styles.
Download the packages http://jqueryui.com/autocomplete
In VS 2008 or 2010 Create web site, in the page header add jQuery packages and style as a following:

<link rel="stylesheet" href="jquery_bundle/themes/base/jquery.ui.all.css" />
<script language="javascript" type="text/javascript" src="jquery_bundle/jquery-1.9.1.js"></script>
<script language="javascript" type="text/javascript" src="jquery_bundle/ui/jquery.ui.core.js"></script>
<script language="javascript" type="text/javascript" src="jquery_bundle/ui/jquery.ui.widget.js"></script><script language="javascript" type="text/javascript" src="jquery_bundle/ui/jquery.ui.position.js"></script>
<script language="javascript" type="text/javascript" src="jquery_bundle/ui/jquery.ui.autocomplete.js"></script>
<script language="javascript" type="text/javascript" src="jquery_bundle/ui/jquery.ui.menu.js"></script>
<link rel="stylesheet" href="jquery_bundle/themes/demos.css" />
    <style>
     /* prevent horizontal scrollbar */
        .ui-autocomplete
        {
            max-height: 100px;
            overflow-y: auto;
            overflow-x: hidden;
        }
      * html .ui-autocomplete
        {
            height: 100px;
        }
    </style>
In the page body add TextBox Control and name it txtMemberName:

 <asp:TextBox ID="txtMemberName" runat="server" Style="padding: 5px; width: 400px;
 font: 11pt Verdana;"></asp:TextBox>
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;
[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> GetAllMember(string keywords)
    {
        //TODO: implement real search here!
        IList<string> result = new List<string>();
        string constr = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["conn"].ConnectionString;
        SqlConnection con = new SqlConnection(constr);
        SqlCommand cmd = con.CreateCommand();
        cmd.CommandText = "select first_name from tbl_member where first_name like '%" + keywords +      "%'";
        try
        {
            con.Open();
            SqlDataReader dr = cmd.ExecuteReader();
            while (dr.Read())
            {
                result.Add(dr["first_name"].ToString());
            }
            con.Close();
            return result;
        }
        catch
        {
            return null;
        }
    }
}
To implement autocomplete to a TextBox add the following script in the page header. This jQuery script will call the function that we declared in the web service and passing to it the typed keywords in the textbox.

<script language="javascript" type="text/javascript">
    $(document).ready(function() {
        $('#<%= txtMemberName.ClientID %>').autocomplete({
            source: function(request, response) {
                $.ajax({
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    url: "WebService.asmx/GetAllMember",
                    data: "{'keywords':'" + request.term + "'}",
                    dataType: "json",
                    async: true,
                    success: function(data) {
                        response(data.d);
                    },
                    error: function(result) {
                        //alert("Error");
                    }
                });
            }
        });
    });
</script>





Friday 10 May 2013

Securing Images in ASP.NET c#

add new imageHandler.aspx

using System.IO;

protected void Page_Load(object sender, EventArgs e)
{
        string fileName = Request.QueryString["src"];
        long fileSize = 0;
        if (string.IsNullOrEmpty(fileName))
        {
            fileName = "empty.gif";
        }
        fileName = Server.MapPath("..\\images\\" + fileName);
        FileStream fileStream = default(FileStream);
        fileStream = new FileStream(fileName, FileMode.Open);
        fileSize = fileStream.Length;
        byte[] Buffer = new byte[Convert.ToInt32(fileSize) + 1];
        fileStream.Read(Buffer, 0, Convert.ToInt32(fileSize));
        fileStream.Close();
        Response.BinaryWrite(Buffer);
}

add new default.aspx
<img src="imageHandler.aspx?src=1.jpg" />

Replace all special characters in c# from string

Solution 1 : 
using System.Text.RegularExpressions;
public string RemoveSpecialCharacters(string str)
{
    return Regex.Replace(str, "[^a-zA-Z0-9_.]+", "", RegexOptions.Compiled);
}

Solution 2 :

public string RemoveSpecialChars(string str)
{
    string[] chars = new string[] { ",", ".", "/", "!", "@", "#", "$", "%", "^", "&", "*", "'", "\"", ";","_","(", ")", ":", "|", "[", "]" };

  for (int i = 0; i< chars.Lenght; i++)
  {
if (str.Contains(chars[i]))
{
str = str.Replace(chars[i],"");
}
   }
return str;
}

Thursday 9 May 2013

Way in asp.net c# to force https for an entire site?


protected void Application_BeginRequest(Object sender, EventArgs e)
{
   if (HttpContext.Current.Request.IsSecureConnection.Equals(false) &&      
   HttpContext.Current.Request.IsLocal.Equals(false))
   {
       Response.Redirect("https://" + Request.ServerVariables["HTTP_HOST"]
       + HttpContext.Current.Request.RawUrl);
   }
}


That would go in the global.asax.cs

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