Friday, 23 September 2016

Force browsers to get latest js and css files in asp.net

1. Crete a class named FileUtility

using System.Web;

public class FileUtility
{
    public static string SetJsVersion(HttpContext context, string filename)
    {
        string version = GetJsFileVersion(context, filename);
        return filename + version;
    }

    private static string GetJsFileVersion(HttpContext context, string filename)
    {
        if (context.Cache[filename] == null)
        {
            string filePhysicalPath = context.Server.MapPath(filename);

            string version = "?v=" + GetFileLastModifiedDateTime(context, filePhysicalPath, "yyyyMMddhhmmss");

            return version;
        }
        else
        {
            return string.Empty;
        }
    }

    public static string GetFileLastModifiedDateTime(HttpContext context, string filePath, string dateFormat)
    {
        return new System.IO.FileInfo(filePath).LastWriteTime.ToString(dateFormat);
    }
}

2.Rendered HTML 
For Css : <link href="<%=FileUtility.SetJsVersion(Context,"css/bootstrap.css")%>" rel="stylesheet" />
For js : <script type="text/javascript" src='<%=FileUtility.SetJsVersion(Context,"/js/json.js") %>'></script>

SQL Server thousands separator for a column

SELECT CONVERT(VARCHAR,CONVERT(MONEY, 234234234),1)

Tuesday, 30 August 2016

Filter or Search ASP.Net DropDownList Using JavaScript

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="DemoChosen.aspx.cs" Inherits="Demo.DemoChosen" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet" />
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>

    <link href="http://cdnjs.cloudflare.com/ajax/libs/chosen/1.1.0/chosen.min.css" rel="stylesheet" />
    <script src="http://cdnjs.cloudflare.com/ajax/libs/chosen/1.1.0/chosen.jquery.min.js"></script>

    <title></title>

    <style>
        .panel-heading
        {
            cursor: pointer;
        }

        select.form-control + .chosen-container.chosen-container-single .chosen-single
        {
            display: block;
            width: 100%;
            height: 34px;
            padding: 6px 12px;
            font-size: 14px;
            line-height: 1.428571429;
            color: #555;
            vertical-align: middle;
            background-color: #fff;
            border: 1px solid #ccc;
            border-radius: 4px;
            -webkit-box-shadow: inset 0 1px 1px rgba(0,0,0,0.075);
            box-shadow: inset 0 1px 1px rgba(0,0,0,0.075);
            -webkit-transition: border-color ease-in-out .15s,box-shadow ease-in-out .15s;
            transition: border-color ease-in-out .15s,box-shadow ease-in-out .15s;
            background-image: none;
        }

            select.form-control + .chosen-container.chosen-container-single .chosen-single div
            {
                top: 4px;
                color: #000;
            }

        select.form-control + .chosen-container .chosen-drop
        {
            background-color: #FFF;
            border: 1px solid #CCC;
            border: 1px solid rgba(0, 0, 0, 0.15);
            border-radius: 4px;
            -webkit-box-shadow: 0 6px 12px rgba(0, 0, 0, 0.175);
            box-shadow: 0 6px 12px rgba(0, 0, 0, 0.175);
            background-clip: padding-box;
            margin: 2px 0 0;
        }

        select.form-control + .chosen-container .chosen-search input[type=text]
        {
            display: block;
            width: 100%;
            height: 34px;
            padding: 6px 12px;
            font-size: 14px;
            line-height: 1.428571429;
            color: #555;
            vertical-align: middle;
            background-color: #FFF;
            border: 1px solid #CCC;
            border-radius: 4px;
            -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
            box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
            -webkit-transition: border-color ease-in-out 0.15s, box-shadow ease-in-out 0.15s;
            transition: border-color ease-in-out 0.15s, box-shadow ease-in-out 0.15s;
            background-image: none;
        }

        select.form-control + .chosen-container .chosen-results
        {
            margin: 2px 0 0;
            padding: 5px 0;
            font-size: 14px;
            list-style: none;
            background-color: #fff;
            margin-bottom: 5px;
        }

            select.form-control + .chosen-container .chosen-results li,
            select.form-control + .chosen-container .chosen-results li.active-result
            {
                display: block;
                padding: 3px 20px;
                clear: both;
                font-weight: normal;
                line-height: 1.428571429;
                color: #333;
                white-space: nowrap;
                background-image: none;
            }

                select.form-control + .chosen-container .chosen-results li:hover,
                select.form-control + .chosen-container .chosen-results li.active-result:hover,
                select.form-control + .chosen-container .chosen-results li.highlighted
                {
                    color: #FFF;
                    text-decoration: none;
                    background-color: #428BCA;
                    background-image: none;
                }

        select.form-control + .chosen-container-multi .chosen-choices
        {
            display: block;
            width: 100%;
            min-height: 34px;
            padding: 6px;
            font-size: 14px;
            line-height: 1.428571429;
            color: #555;
            vertical-align: middle;
            background-color: #FFF;
            border: 1px solid #CCC;
            border-radius: 4px;
            -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
            box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
            -webkit-transition: border-color ease-in-out 0.15s, box-shadow ease-in-out 0.15s;
            transition: border-color ease-in-out 0.15s, box-shadow ease-in-out 0.15s;
            background-image: none;
        }

            select.form-control + .chosen-container-multi .chosen-choices li.search-field input[type="text"]
            {
                height: auto;
                padding: 5px 0;
            }

            select.form-control + .chosen-container-multi .chosen-choices li.search-choice
            {
                background-image: none;
                padding: 3px 24px 3px 5px;
                margin: 0 6px 0 0;
                font-size: 14px;
                font-weight: normal;
                line-height: 1.428571429;
                text-align: center;
                white-space: nowrap;
                vertical-align: middle;
                cursor: pointer;
                border: 1px solid #ccc;
                border-radius: 4px;
                color: #333;
                background-color: #FFF;
                border-color: #CCC;
            }

                select.form-control + .chosen-container-multi .chosen-choices li.search-choice .search-choice-close
                {
                    top: 8px;
                    right: 6px;
                }

        select.form-control + .chosen-container-multi.chosen-container-active .chosen-choices,
        select.form-control + .chosen-container.chosen-container-single.chosen-container-active .chosen-single,
        select.form-control + .chosen-container .chosen-search input[type=text]:focus
        {
            border-color: #66AFE9;
            outline: 0;
            -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075),0 0 8px rgba(102, 175, 233, 0.6);
            box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075),0 0 8px rgba(102, 175, 233, 0.6);
        }

        select.form-control + .chosen-container-multi .chosen-results li.result-selected
        {
            display: list-item;
            color: #ccc;
            cursor: default;
            background-color: white;
        }
    </style>

</head>
<body>
    <form id="form1" runat="server">
        <div>
            <div class="form-group">
                <label for="id_tipo_equipo" class="control-label">Tipo</label>
                <select name="id_tipo_equipo" id="id_tipo_equipo" class="form-control chosen" data-placeholder="[Tipo]">
                    <option value="1">Access Point</option>
                    <option value="2">Adaptador</option>
                    <option value="3">Adaptador DVI a VGA</option>
                    <option value="4">Adaptador Electrico para Discos</option>
                    <option value="5">Aire Acondicionado</option>
                    <option value="6">Amplificador</option>
                    <option value="7">Antena</option>
                    <option value="8">Antena Poe</option>
                    <option value="9">Bases de Monitor</option>
                    <option value="10">Bluetooth</option>
                    <option value="11">Cable de Poder</option>
                    <option value="12">Cable USB</option>
                    <option value="13">Cable UTP</option>
                    <option value="14">Cables Conectores</option>
                    <option value="15">Camara de Fotos</option>
                    <option value="16">Camara de Video</option>
                </select>

               
            </div>

              <button onclick=" return getVal();">Get Selected Value</button>
        </div>
    </form>
</body>
<script>
    $(document).ready(function () {
        // $('select').chosen({ width: '100%' });
        var config = {
            '#id_tipo_equipo': {},
            '.chosen-select-deselect': { allow_single_deselect: true },
            '.chosen-select-no-single': { disable_search_threshold: 10 },
            '.chosen-select-no-results': { no_results_text: 'Oops, nothing found!' },
            '.chosen-select-width': { width: "95%" }
        }

        for (var selector in config) {
            $(selector).chosen(config[selector]);
        }
    });

    function getVal() {
        alert(document.getElementById("id_tipo_equipo").value);
        return false;
    }
</script>
</html>

Wednesday, 27 July 2016

Reading and write a text file with SQL Server 2008

1. /*-- To allow advanced options to be changed.
EXEC sp_configure 'show advanced options', 1;
GO
-- To update the currently configured value for advanced options.
RECONFIGURE;
GO
-- To enable the feature.
EXEC sp_configure 'xp_cmdshell', 1;
GO
-- To update the currently configured value for this feature.
RECONFIGURE;
GO
*/

2. --------INSERT DATA INTO SERVER AND STORE THE TEXT FILE INTO SERVER

DECLARE
 @saveas VARCHAR(2048)
,@query VARCHAR(2048)
,@bcpquery VARCHAR(2048)
,@bcpconn VARCHAR(64)
,@bcpdelim VARCHAR(2)

 SET @query      = 'select * from tbl_name'
 SET @saveas     = 'D:\tbl_name.txt'
 SET @bcpdelim   = '|'
 SET @bcpconn    = '-T' -- Trusted
 SET @bcpconn    = '-U sql_database -P sql_password -d database_name -S server_name' -- SQL authentication


SET @bcpquery = 'bcp "' + replace(@query, char(10), '') + '" QUERYOUT "' + @saveas + '" -c -t^' + @bcpdelim + ' ' + @bcpconn
EXEC master..xp_cmdshell @bcpquery

3. --------TAKE COPY THE TXT FILE FROM SERVER AND PAST Destination machine
BULK INSERT dbo.tbl_bulkinsert
FROM 'D:\tbl_name.txt'
WITH ( FIELDTERMINATOR ='|', FIRSTROW =1 )



4. SELECT * FROM tbl_bulkinsert

Sunday, 6 March 2016

Find all children for multiple parents in SQL query

CREATE TABLE #tbl_product(
product_id INT IDENTITY(1,1) NOT NULL,
product_name nvarchar(200),
belongs_to INT
)

INSERT INTO #tbl_product(product_name,belongs_to) VALUES('Electronics',NULL)
INSERT INTO #tbl_product(product_name,belongs_to) VALUES('Furniture',NULL)
INSERT INTO #tbl_product(product_name,belongs_to) VALUES('MObile',1)
INSERT INTO #tbl_product(product_name,belongs_to) VALUES('Samsung Edge',3)
INSERT INTO #tbl_product(product_name,belongs_to) VALUES('Lenovo GT',3)
INSERT INTO #tbl_product(product_name,belongs_to) VALUES('Body Trimmer',1)
INSERT INTO #tbl_product(product_name,belongs_to) VALUES('Car Fregnance',1)
INSERT INTO #tbl_product(product_name,belongs_to) VALUES('Car Fregnance',1)
INSERT INTO #tbl_product(product_name,belongs_to) VALUES('Chair',2)
INSERT INTO #tbl_product(product_name,belongs_to) VALUES('NIlkomal Chair',9)
INSERT INTO #tbl_product(product_name,belongs_to) VALUES('Queen size bed',2)

;WITH cte AS(
SELECT
product_id,
product_name,
belongs_to,
[level] = 0,
Sortid = CAST(product_id AS VARCHAR(MAX))
FROM #tbl_product
WHERE ISNULL(belongs_to,0) = 0
UNION ALL
SELECT
a.product_id,
a.product_name,
a.belongs_to,
[level] = [level] + 1,
Sortid = Sortid + CAST(a.product_id AS VARCHAR(MAX))
FROM #tbl_product a
JOIN cte b
ON a.belongs_to = b.product_id
)
SELECT
product_id,
REPLICATE(' ¦  ', [level]) + product_name,
belongs_to
FROM cte
ORDER BY Sortid


DROP TABLE #tbl_product

Monday, 18 January 2016

C# Regular Expression Get Text Between Brackets

//string regularExpressionPattern = @"\<(.*?)\>"; // FOR right angles < >
//string regularExpressionPattern = @"\((.*?)\)"; // FOR parenthesis ( )
//string regularExpressionPattern = @"\{(.*?)\}"; // FOR curly brackets { }

string regularExpressionPattern = @"\[(.*?)\]"; //FOR []

string inputText = "Find string inside brackets [test1] and [test2] in [ASP.net]";

Regex re = new Regex(regularExpressionPattern);

foreach (Match m in re.Matches(inputText))
{
       //Put Your LOGIC
}

Tuesday, 2 June 2015

Cross Domain GET request to ASP.NET web service

Add a webservice name "web_service_cross.asmx"

using System.Linq;
using System.Web;
using System.Web.Services;
using System.Data.SqlClient;
using System.Web.Script.Serialization;
using System.Web.Script.Services;

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]

public class web_service_cross : System.Web.Services.WebService
{
    [WebMethod]
    [ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
    public string Add(string x)
    {
        x = (Convert.ToInt32(x) + 5).ToString();
        return new JavaScriptSerializer().Serialize(x);
    }

Add a class file name ContentTypeHttpModule.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Text;

namespace ContentTypeHttpModule
{
    public class ContentTypeHttpModule : IHttpModule
    {
        private const string JSON_CONTENT_TYPE = "application/json; charset=utf-8";

        #region IHttpModule Members
        public void Dispose()
        {
        }

        public void Init(HttpApplication app)
        {
            app.BeginRequest += OnBeginRequest;
            app.ReleaseRequestState += OnReleaseRequestState;
        }
        #endregion

        public void OnBeginRequest(object sender, EventArgs e)
        {
            HttpApplication app = (HttpApplication)sender;
            HttpRequest resquest = app.Request;
            if (!resquest.Url.AbsolutePath.Contains("web_service_cross.asmx")) return;

            if (string.IsNullOrEmpty(app.Context.Request.ContentType))
            {
                app.Context.Request.ContentType = JSON_CONTENT_TYPE;
            }
        }

        public void OnReleaseRequestState(object sender, EventArgs e)
        {
            HttpApplication app = (HttpApplication)sender;
            HttpResponse response = app.Response;
            if (app.Context.Request.ContentType != JSON_CONTENT_TYPE) return;

            response.Filter = new JsonResponseFilter(response.Filter);
        }
    }

    public class JsonResponseFilter : Stream
    {
        private readonly Stream _responseStream;
        private long _position;

        public JsonResponseFilter(Stream responseStream)
        {
            _responseStream = responseStream;
        }

        public override bool CanRead { get { return true; } }

        public override bool CanSeek { get { return true; } }

        public override bool CanWrite { get { return true; } }

        public override long Length { get { return 0; } }

        public override long Position { get { return _position; } set { _position = value; } }

        public override void Write(byte[] buffer, int offset, int count)
        {
            string strBuffer = Encoding.UTF8.GetString(buffer, offset, count);
            strBuffer = AppendJsonpCallback(strBuffer, HttpContext.Current.Request);
            byte[] data = Encoding.UTF8.GetBytes(strBuffer);
            _responseStream.Write(data, 0, data.Length);
        }

        private string AppendJsonpCallback(string strBuffer, HttpRequest request)
        {
            return request.Params["callback"] + "(" + strBuffer + ");";
        }

        public override void Close()
        {
            _responseStream.Close();
        }

        public override void Flush()
        {
            _responseStream.Flush();
        }

        public override long Seek(long offset, SeekOrigin origin)
        {
            return _responseStream.Seek(offset, origin);
        }

        public override void SetLength(long length)
        {
            _responseStream.SetLength(length);
        }

        public override int Read(byte[] buffer, int offset, int count)
        {
            return _responseStream.Read(buffer, offset, count);
        }
    }
}

Create a html file 

<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript">
    </script>
     <script language="javascript" src="Scripts/json2.js"></script>
    <script language="javascript" type="text/javascript">

        function click_test() {
            $.ajax({ url: "http://localhost:50535/WebSite14/web_service_cross.asmx/Add",//change the url
                data: { x: JSON.stringify("10") }, //, y: JSON.stringify("2nd param") 
                dataType: "jsonp",
                success: function (json) {
                    alert(json.d);
                },
                error: function () {
                    alert("Hit error fn!");
                }
            });
        }    
    </script>
</head>

<body>
 <input type="button" value="TEST" onclick="click_test();" />
</body>
</html>




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