Tuesday, December 29, 2015

SignalR Implementation in XAML Page

XAML Page:

using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using Microsoft.AspNet.SignalR.Client;

namespace SignalRDemo
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        HubConnection _connection;
        IHubProxy _hub;

        // Keep track of when fake "drag and drop" mode is enabled.
        private bool isDragging = false;

        // Store the location where the user clicked the control.
        private double clickOffsetX, clickOffsetY;

        private void window_Loaded(object sender, RoutedEventArgs e)
        {
            Start();
        }

        void label_MouseDown(object sender, MouseButtonEventArgs e)
        {
            isDragging = true;
            var position = e.GetPosition(window);

            var label = sender as Label;
            var l = (double)label.GetValue(Canvas.LeftProperty);
            var t = (double)label.GetValue(Canvas.TopProperty);

            clickOffsetX = l - position.X;
            clickOffsetY = t - position.Y;
        }

        void label_MouseMove(object sender, MouseEventArgs e)
        {
            if (isDragging == true)
            {
                // The control coordinates are converted into form coordinates
                // by adding the label position offset.
                // The offset where the user clicked in the control is also
                // accounted for. Otherwise, it looks like the top-left corner
                // of the label is attached to the mouse.

                var label = sender as Label;
                var position = e.GetPosition(window);

                var x = position.X + clickOffsetX;
                var y = position.Y + clickOffsetY;

                SetShapePosition(label, x, y);

                _hub.Invoke("MoveShape", int.Parse(label.Name.Replace("shape", "")), x, y);
            }
        }

        void label_MouseUp(object sender, MouseButtonEventArgs e)
        {
            isDragging = false;
        }

        private void Start()
        {
            _connection = new HubConnection("http://localhost/SignalRChat/myhubs/hubs");

            _hub = _connection.CreateHubProxy("SignalRHub");

            _connection.Start().Wait();

            _hub.On<int>("usersConnected", (count) =>
            {
                this.Dispatcher.Invoke(() =>
                    UpdateUserCount(count)
                );
            });

            _hub.On<List<Common.Shape>>("shapeList", (list) =>
            {
                this.Dispatcher.Invoke(() =>
                {
                    canvas.Children.Clear();

                    list.ForEach(q =>
                    {
                        var label = new Label();

                        label.Name = string.Format("shape{0}", q.Id);
                        label.Content = q.Name;
                        label.Height = 100;
                        label.Width = 100;
                        label.Padding = new Thickness(10, 10, 0, 0);
                        label.Background = new SolidColorBrush((Color)ColorConverter.ConvertFromString(q.Color));
                        SetShapePosition(label, q.X, q.Y);
                        label.FontSize = 20;

                        label.MouseDown += label_MouseDown;
                        label.MouseMove += label_MouseMove;
                        label.MouseUp += label_MouseUp;

                        canvas.Children.Add(label);
                    });
                });
            });

            _hub.On<Common.Shape>("shapeMoved", (shape) =>
            {
                this.Dispatcher.Invoke(() =>
                    UpdatePosition(shape)
                );
            });

            _hub.Invoke("GetShapeList");
        }

        private void SetShapePosition(Label label, double x, double y)
        {
            if (label != null)
            {
                label.SetValue(Canvas.LeftProperty, x);
                label.SetValue(Canvas.TopProperty, y);
            }
        }

        private void UpdateUserCount(int count)
        {
            lblCount.Content = count;
        }

        private void UpdatePosition(Common.Shape shape)
        {
            var label = UIHelper.FindChild<Label>(Application.Current.MainWindow, string.Format("shape{0}", shape.Id));
            SetShapePosition(label, shape.X, shape.Y);
        }
    }

    public class UIHelper
    {
        /// <summary>
        /// Finds a Child of a given item in the visual tree. 
        /// </summary>
        /// <param name="parent">A direct parent of the queried item.</param>
        /// <typeparam name="T">The type of the queried item.</typeparam>
        /// <param name="childName">x:Name or Name of child. </param>
        /// <returns>The first parent item that matches the submitted type parameter. 
        /// If not matching item can be found, 
        /// a null parent is being returned.</returns>
        public static T FindChild<T>(DependencyObject parent, string childName)
           where T : DependencyObject
        {
            // Confirm parent and childName are valid. 
            if (parent == null) return null;

            T foundChild = null;

            int childrenCount = VisualTreeHelper.GetChildrenCount(parent);
            for (int i = 0; i < childrenCount; i++)
            {
                var child = VisualTreeHelper.GetChild(parent, i);
                // If the child is not of the request child type child
                T childType = child as T;
                if (childType == null)
                {
                    // recursively drill down the tree
                    foundChild = FindChild<T>(child, childName);

                    // If the child is found, break so we do not overwrite the found child. 
                    if (foundChild != null) break;
                }
                else if (!string.IsNullOrEmpty(childName))
                {
                    var frameworkElement = child as FrameworkElement;
                    // If the child's name is set for search
                    if (frameworkElement != null && frameworkElement.Name == childName)
                    {
                        // if the child's name is of the request name
                        foundChild = (T)child;
                        break;
                    }
                }
                else
                {
                    // child element found.
                    foundChild = (T)child;
                    break;
                }
            }

            return foundChild;
        }
    }

}

SignalR Hub Page :

using Microsoft.AspNet.SignalR;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Common;

namespace SignalRChat
{
    public class SignalRHub : Hub
    {
        public SignalRHub()
        {

        }

        #region Moveable Shape
        public async Task GetShapeList() // this method will be called from the client, when the user drag/move the shape
        {
            await Clients.Caller.shapeList(ShapeHandler.Instance.ShapeList); // this method will send the coord x, y to the other users but the user draging the shape
        }

        public async Task MoveShape(int id, double x, double y) // this method will be called from the client, when the user drag/move the shape
        {
            var shape = ShapeHandler.Instance.GetShape(id, x, y);

            if (shape.X != x || shape.Y != y) await Clients.Caller.shapeMoved(shape);

            await Clients.Others.shapeMoved(shape); // this method will send the coord x, y to the other users but the user draging the shape
        }

        public override Task OnConnected() //override OnConnect, OnReconnected and OnDisconnected to know if a user is connected or disconnected
        {
            ShapeHandler.Instance.ConnectedIds.Add(Context.ConnectionId); //add a connection id to the list
            Clients.All.usersConnected(ShapeHandler.Instance.ConnectedIds.Count()); //this will send to ALL the clients the number of users connected
            return base.OnConnected();
        }

        public override Task OnReconnected()
        {
            ShapeHandler.Instance.ConnectedIds.Add(Context.ConnectionId);
            Clients.All.usersConnected(ShapeHandler.Instance.ConnectedIds.Count());
            return base.OnConnected();
        }

        public override Task OnDisconnected(bool stopCalled)
        {
            ShapeHandler.Instance.ConnectedIds.Remove(Context.ConnectionId);
            Clients.All.usersConnected(ShapeHandler.Instance.ConnectedIds.Count());
            return base.OnDisconnected(stopCalled);
        }
        #endregion
    }
}

SignalR Implementation in HTML Page

Html Page :

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
</head>
<body>
    <label id="serverDate"></label>
    <button id="initTimer">Start Timer</button>

    <!--Script references. -->
    <script src="Scripts/jquery-1.6.4.min.js"></script>
    <script src="Scripts/jquery.signalR-2.0.0.js"></script>

    <!--Reference the autogenerated SignalR hub script. -->
    <script src="signalR/hubs"></script>
    <script type="text/javascript">
        $(function () {
            // Declare a proxy to reference the hub.
            var hub = $.connection.demoHub;

            hub.client.serverDateTimeInfo = function (time) {
                $("#serverDate").text(time);
            };

            $.connection.hub.start().done(function () {
                alert('Server connected');

                hub.server.getServerDatetime();

                $("#initTimer").click(function () {
                    hub.server.initTimer();
                });
            });
        });
    </script>
</body>
</html>

SignalR Hub Page :

using Microsoft.AspNet.SignalR;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Timers;
using System.Web;

namespace SignalRChat
{
    public class DemoHub :Hub
    {
        public void GetServerDatetime()
        {
            SendNotification();
        }

        private void SendNotification()
        {
            try
            {
                Clients.Caller.serverDateTimeInfo(DateTime.Now.ToString());
            }
            catch { }
        }

        public void InitTimer()
        {
            Timer timer = new Timer(1000);
            timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);
            timer.AutoReset = true;
            timer.Enabled = true;
        }

        public void timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            SendNotification();
        }
        
    }
}

Thursday, March 15, 2012

Diffrence between CROSS APPLY and OUTER APPLY of SQL XML


Sample XML :
DECLARE @XML XML =
'<Root>
<UserInfo Id="1" Name="Name 1">
<CityInfo Id="2" City="City 1" />
<CityInfo Id="3" City="City 2" >
<PrefInfo Id="33" Name="Show Whether" />
</CityInfo>
</UserInfo>
<UserInfo Id="2" Name="Name 2">
<CityInfo Id="4" City="City 3" />
<CityInfo Id="5" City="City 4" >
<PrefInfo Id="33" Name="Show Temprature" />
</CityInfo>
</UserInfo>
</Root>'


Cross Apply : Cross apply is basically use inner join of two xml collection
SELECT
UserInfo.value('@Id', 'BIGINT') as UserId
, UserInfo.value('@Name', 'VARCHAR(20)') as UserName
, CityInfo.value('@Id', 'BIGINT') as CityId
, CityInfo.value('@City', 'VARCHAR(20)') as CityName
, PrefInfo.value('@Id', 'BIGINT') as PrefId
, PrefInfo.value('@Name', 'VARCHAR(20)') as PrefName
FROM @xml.nodes('/Root/UserInfo')e(UserInfo)
CROSS APPLY UserInfo.nodes('CityInfo')b(CityInfo)
CROSS APPLY CityInfo.nodes('PrefInfo')c(PrefInfo)

Output :

UserId UserName CityId CityName PrefId PrefName
-------- --------- ------- --------- -------- ----------------
1 Name 1 3 City 2 33 Show Whether
2 Name 2 5 City 4 33 Show Temprature

Outer Apply : Outer apply is basically use left outer join of two xml collection
SELECT
UserInfo.value('@Id', 'BIGINT') as UserId
, UserInfo.value('@Name', 'VARCHAR(20)') as UserName
, CityInfo.value('@Id', 'BIGINT') as CityId
, CityInfo.value('@City', 'VARCHAR(20)') as CityName
, PrefInfo.value('@Id', 'BIGINT') as PrefId
, PrefInfo.value('@Name', 'VARCHAR(20)') as PrefName
FROM @xml.nodes('/Root/UserInfo')e(UserInfo)
CROSS APPLY UserInfo.nodes('CityInfo')b(CityInfo)
OUTER APPLY CityInfo.nodes('PrefInfo')c(PrefInfo)

Output :
UserId UserName CityId CityName PrefId PrefName
------- --------- ------- --------- ------- ----------------
1 Name 1 2 City 1 NULL NULL
1 Name 1 3 City 2 33 Show Whether
2 Name 2 4 City 3 NULL NULL
2 Name 2 5 City 4 33 Show Temprature

Wednesday, March 14, 2012

How to Handle button click event in jquery

Code :

<script type="text/javascript" language="javascript">
$(document).ready(function () {
$("[id*='btnSave']").click(function (event) {
event.preventDefault();
if (confirm("Want to save data?")) {
$(this).unbind('click').click()
}
});

});
</script>

Tuesday, September 20, 2011

jQuery Selector


#No Syntax Description
---------------------------------------------------------------------------------------
1. $(this) Current HTML element
2. $(".intro") All elements with class="intro"
3. $("#intro") The first element with id="intro"
4. $("p") All <p> elements
5. $("p.intro") All <p> elements with class="intro"
6. $("p#intro") All <p> elements with id="intro"
7. $("p#intro:first-child") The first <p> element with id="intro"
8. $("ul li:first-child") The first <li> element of each <ul>
9. $("ul li:last-child") The last <li> element of each <ul>
10. $("ul li:nth-child(4)") The fourth <li> element of each <ul>
11. $("div#intro .head") All elements with class="head" and id="intro" of DIV
12. $("[href*='User']") All elements with href contains "User"
13. $("[href^='User']") All elements with href start with "User"
14. $("[href$='.html']") All elements with an href attribute
that ends with ".html"
15. $("[href*='User'] div") AND condition for Getting all element
which have href contains "User" and inner element div
16. $("[href*='User'],div") OR condition for Getting all element
which have href contains "User" or div element
17. $("[href!='UserInfo.html']") NOT condition for Getting all element
which have href not equle to "UserInfo.html"
18. $("div > input#User") Getting all element which have a parent element is
DIV and next element is INPUT have a id User
19. $("div").find("input#User") Getting all element of parent element is
DIV and child element is INPUT have a id User
20. $("div").not(".UserInfo, #UserId") Getting all div element which not have a
class USERINFO or id is USERID

Monday, August 29, 2011

Rounding date in SQL query


Query :
SELECT
DATEADD( MI, DATEDIFF( MI, 0, DATEADD( SS, 30, Dates.SampleDate) ), 0) AS RoundedDate
FROM
(
SELECT SampleDate = CONVERT( DATETIME, '8/29/2011 12:59:29.998')
UNION ALL
SELECT SampleDate = CONVERT( DATETIME, '8/29/2011 12:59:30.000')
) Dates

Results :

RoundedDate
-----------------------
2011-08-29 12:59:00.000
2011-08-29 13:00:00.000

Friday, July 1, 2011

Use of Rollup, Grouping, Grouping_ID and Cube in Group By


ROLLUP = Generates the simple GROUP BY aggregate rows
, plus subtotal or super-aggregate rows
, and also a grand total row.
GROUPING = Indicates whether a specified column expression in a GROUP BY list is aggregated or not.
GROUPING_ID = Is a function that computes the level of grouping.
CUBE = Generates simple GROUP BY aggregate rows, the ROLLUP super-aggregate rows, and cross-tabulation rows.

Sample Data

DECLARE @Sales TABLE (Year INT, Quarter VARCHAR(50), SalesPerson VARCHAR(50), Amount FLOAT)

INSERT INTO @Sales values
(1998, 'Q1', 'SalePerson1', 123)
, (1998, 'Q2', 'SalePerson2', 234)
, (1998, 'Q3', 'SalePerson4', 345)
, (1998, 'Q4', 'SalePerson3', 556)
, (1999, 'Q1', 'SalePerson1', 623)
, (1999, 'Q2', 'SalePerson2', 734)
, (1999, 'Q3', 'SalePerson3', 845)
, (1999, 'Q4', 'SalePerson4', 956)

Example 1 : (Single field in grouping)

SELECT
[Year]
, AVG(Amount) as Average
, GROUPING([Year]) as [YearRollUp?]
FROM
@Sales
GROUP BY
[Year] WITH ROLLUP

Output :

Year Average YearRollUp?
----------- ---------------------- -----------
1998 314.5 0
1999 789.5 0
NULL 552 1

Example 2 : (Multipal field in grouping)

SELECT
[Year]
, Quarter
, AVG(Amount) as Average
, GROUPING( [Year] ) as [YearRollUp?]
FROM
@Sales
GROUP BY
GROUPING SETS (( [Year], Quarter), ( [Year] ), ())

Output :

Year Quarter Average YearRollUp?
----------- ------- ---------------------- -----------
1998 Q1 123 0
1998 Q2 234 0
1998 Q3 345 0
1998 Q4 556 0
1998 NULL 314.5 0
1999 Q1 623 0
1999 Q2 734 0
1999 Q3 845 0
1999 Q4 956 0
1999 NULL 789.5 0
NULL NULL 552 1

Example 3 :( Example of Grouping_ID )

SELECT
[Year]
, Quarter
, AVG(Amount) as Average
, GROUPING_ID( [Year], Quarter) as [x]
FROM
@Sales
GROUP BY
GROUPING SETS (( [Year], Quarter), ( [Year] ), ( [Quarter] ), ())

Output :

Year Quarter Average x
----------- ------- ---------------------- -----------
1998 Q1 123 0
1999 Q1 623 0
NULL Q1 373 2
1998 Q2 234 0
1999 Q2 734 0
NULL Q2 484 2
1998 Q3 345 0
1999 Q3 845 0
NULL Q3 595 2
1998 Q4 556 0
1999 Q4 956 0
NULL Q4 756 2
NULL NULL 552 3
1998 NULL 314.5 1
1999 NULL 789.5 1

Example 4:(Example of Cube)

SELECT
[Year]
, [Quarter]
, AVG(Amount) as Average
, GROUPING_ID( [Year], [Quarter]) as [x]
FROM
@Sales
GROUP BY
CUBE( [Year], [Quarter])

Output :

Year Quarter Average x
----------- ------- ---------------------- -----------
1998 Q1 123 0
1999 Q1 623 0
NULL Q1 373 2
1998 Q2 234 0
1999 Q2 734 0
NULL Q2 484 2
1998 Q3 345 0
1999 Q3 845 0
NULL Q3 595 2
1998 Q4 556 0
1999 Q4 956 0
NULL Q4 756 2
NULL NULL 552 3
1998 NULL 314.5 1
1999 NULL 789.5 1

Thursday, June 30, 2011

Query with static output

Query :



select * from
(
values (1, 2), (2, 3), (3, 4)
) as MyTable(Col1, Col2)

Output :


Col1 Col2
----------- -----------
1 2
2 3
3 4

Thursday, April 28, 2011

Genrate table to ENUM


DECLARE @TableName  VARCHAR(20) = 'tblFileType'        -------------> type table name

DECLARE @ValueField VARCHAR(20) = 'Id'                -------------> type ValueField Name

DECLARE @NameField  VARCHAR(20) = 'Name'            -------------> type NAme Field Name



BEGIN

    DECLARE @SqlQuery VARCHAR(MAX) = 

    'SELECT ''public enum enum' + REPLACE( @TableName, 'tbl''')  + ''' AS enum 

    UNION ALL

    SELECT ''{''

    UNION ALL

    SELECT ( REPLACE('
 + @NameField + ', '' '', '''') + '' = '' + CAST( ' + @ValueField + ' AS VARCHAR(10) ) ) + '','' FROM ' + @TableName

    + ' UNION ALL SELECT ''}'' ' 

    

    PRINT @SqlQuery

    EXECUTE( @SqlQuery )

    -- SELECT Name + ' = ' + CAST( Id AS VARCHAR(10) ) + ',' FROM tblUserRoll

END

Thursday, November 18, 2010

MVC Application Configration in IIS

I have referred this site to get the MVC applicaiton working using Virtual directory. There is no direct way to get the MCV working on the IIS. It can run through port by default but making it work with IIS Virtual Directory follow this link.

1) http://haacked.com/archive/2008/11/26/asp.net-mvc-on-iis-6-walkthrough.aspx
2) http://www.asp.net/mvc/tutorials/using-asp-net-mvc-with-different-versions-of-iis-vb

Tuesday, July 20, 2010

Get All Relationship of Primary Key


SELECT
PKTableInfo.TABLE_NAME AS PK_Table_Name
, ConstarintReference.UNIQUE_CONSTRAINT_NAME AS PK_CONSTRAINT_NAME
, STUFF( (
SELECT
',' + kcu.COLUMN_NAME
FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS kcu
WHERE kcu.TABLE_CATALOG = PKTableInfo.TABLE_CATALOG
AND kcu.TABLE_SCHEMA = PKTableInfo.TABLE_SCHEMA
AND kcu.TABLE_NAME = PKTableInfo.TABLE_NAME
AND kcu.CONSTRAINT_CATALOG = PKTableInfo.CONSTRAINT_CATALOG
AND kcu.CONSTRAINT_SCHEMA = PKTableInfo.CONSTRAINT_SCHEMA
AND kcu.CONSTRAINT_NAME = PKTableInfo.CONSTRAINT_NAME
ORDER BY kcu.ORDINAL_POSITION
FOR XML PATH('')
), 1, 1, '') AS [PK_CONSTRAINT_COLUMNS]
, FKTableInfo.TABLE_NAME AS FK_Table_Name
, ConstarintReference.CONSTRAINT_NAME AS FK_CONSTRAINT_NAME
, STUFF( (
SELECT
',' + kcu.COLUMN_NAME
FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS kcu
WHERE kcu.TABLE_CATALOG = FKTableInfo.TABLE_CATALOG
AND kcu.TABLE_SCHEMA = FKTableInfo.TABLE_SCHEMA
AND kcu.TABLE_NAME = FKTableInfo.TABLE_NAME
AND kcu.CONSTRAINT_CATALOG = FKTableInfo.CONSTRAINT_CATALOG
AND kcu.CONSTRAINT_SCHEMA = FKTableInfo.CONSTRAINT_SCHEMA
AND kcu.CONSTRAINT_NAME = FKTableInfo.CONSTRAINT_NAME
ORDER BY kcu.ORDINAL_POSITION
FOR XML PATH('')
), 1, 1, '') AS [FK_CONSTRAINT_COLUMNS]
FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS AS ConstarintReference
INNER JOIN INFORMATION_SCHEMA.CONSTRAINT_TABLE_USAGE AS PKTableInfo ON PKTableInfo.CONSTRAINT_CATALOG = ConstarintReference.UNIQUE_CONSTRAINT_CATALOG
AND PKTableInfo.CONSTRAINT_SCHEMA = ConstarintReference.UNIQUE_CONSTRAINT_SCHEMA
AND PKTableInfo.CONSTRAINT_NAME = ConstarintReference.UNIQUE_CONSTRAINT_NAME
INNER JOIN INFORMATION_SCHEMA.CONSTRAINT_TABLE_USAGE AS FKTableInfo ON ConstarintReference.CONSTRAINT_CATALOG = FKTableInfo.CONSTRAINT_CATALOG
AND ConstarintReference.CONSTRAINT_SCHEMA = FKTableInfo.CONSTRAINT_SCHEMA
AND ConstarintReference.CONSTRAINT_NAME = FKTableInfo.CONSTRAINT_NAME
ORDER BY PK_Table_Name, FK_Table_Name
GO

Wednesday, July 14, 2010

Searching and Multipal Selection Criteria in JQuery



<div>
<div style="float: left; width: 150px">
Your Gender :
</div>
<div style="float: left; width: 250px">
<asp:RadioButtonList ID="rdbGender" runat="server">
<asp:ListItem Text="Male" Value="1"></asp:ListItem>
<asp:ListItem Text="Female" Value="0"></asp:ListItem>
</asp:RadioButtonList>
</div>
</div>
<div style="clear: both">
<div style="float: left; width: 150px">
Searching :
</div>
<div style="float: left; width: 250px">
<asp:RadioButtonList ID="rdbSearching" runat="server">
<asp:ListItem Text="Groom" Value="1"></asp:ListItem>
<asp:ListItem Text="Bride" Value="0"></asp:ListItem>
</asp:RadioButtonList>
</div>
</div>

<script type="text/javascript" language="javascript">
$(document).ready(function() {
$("input[id*='rdbGender'], input[id*='rdbSearching']").click(function() {

var foundIn = $(this).attr('id').toString().search(new RegExp(/rdbGender/i));

var strOpositeRadioButton = "rdbGender";

if (foundIn > -1) {
strOpositeRadioButton = "rdbSearching";
}

if ($(this).val() == 1) {
$("input[id*=" + strOpositeRadioButton + "][value=0]").attr("checked", "checked");
}
else {
$("input[id*=" + strOpositeRadioButton + "][value=1]").attr("checked", "checked");
}
});
});
</script>

Monday, July 12, 2010

JQuery


Ready
-----------------------------------
$(document).read(function(){
alert('hi');
})

$(document).read(FormSetting)
Function FormSetting()
{
alert('hi');
}
-----------------------------------

Selection Criteria
-----------------------------------
=> ID
$("#txtUserName")

=> Control
$("input")
$("div")

=> Inner Control
$("div div input")

=> Class
$(".button")

=> Selection on standard attributes
$("input[type='button']")

=> Selection on custome attributes
<input type="text" IsGridText="True" />
$("input[IsGridText ='True']")
-----------------------------------

Functions
-----------------------------------
=> VAL()
Var strUserName = $("#txtUserName).val();
$("
#txtUserName).val("jsd24");

=> HTML()
Var strInnerHtml = $("#divUserInfo).html();
$("
#divUserInfo).html("<a href='#' OnClick='Alert(1)'>Click Me</a>");

=> Attr ( attribute)
var IsGridText = $("#txtUserName").attr("IsGridText");
$("#txtUserName").attr("IsGridText", "False");
$("#txtUserName").attr({IsGridText:'True', IsSelected:'True'});

=> Css (style sheet)
var color = $("#txtUserName").css("color");
$("#txtUserName").css("color", "red");
$("#txtUserName").css({'width': '100px', 'height':'25px'});

=> Each
$("input").each(function() { $(this).val("jd"); })

=> addClass()
$("input[type='button']").addClass("button");

=> removeClass()
$("input[type='button']").removeClass("button");

=> haseClass()
$("#txtUserName").haseClass("UserName");
$("#txtUserName").haseClass("EmailID");

=> toggleClass()
$("#divUserInfo").toggleClass("Content");

=> height()
$("#divUserInfo").height();

=> innerHeight()
$("#divUserInfo").innerHeight();

=> outerHeight()
$("#divUserInfo").outerHeight();

=> width()
$("#divUserInfo").width();

=> innerWidth ()
$("#divUserInfo").innerWidth ();

=> outerWidth ()
$("#divUserInfo").outerWidth ();

=> fadeIn()
$("#divUserInfo").fadeIn();

=> fadeOut()
$("#divUserInfo").fadeOut ();

=> hide()
$("#divUserInfo").hide();

=> show()
$("#divUserInfo").show();

=> appendTo
$("Hello").appendTo("#divUserInfo");

=> clone
$("#divUserInfo").clone().appendTo("#divUserInfo1");

=> not
$("#ddlProductList option").not("[value*='Computer']").clone().appendTo("#ddlFilterList");
-----------------------------------

Multiple Action in single line
-----------------------------------
$("#txtUserName").val("JSD24").css("color", "green").attr("IsSelected", "true")
-----------------------------------

Events
-----------------------------------
=> change()
$("#txtUserName").change(function(){});

=> click()
$("a").click(function(){});

=> dblclick()
$("a").dblclick(function(){});

=> focus()
$("#txtUserName").focus();

=> focusIn()
$("#txtUserName").focusIn(function());

=> focusOut()
$("#txtUserName").focusOut(function());

=> hover()
$("#txtUserName").hover(function());

=> keydown()
$("#txtUserName").keydown(function());

=> keyup()
$("#txtUserName").keyup(function());

=> keypress ()
$("#txtUserName").keypress(function());

=> mousedown()
$("#txtUserName").mousedown(function());

=> mouseup()
$("#txtUserName").mouseup(function());

=> mousemove()
$("#txtUserName").mousemove(function());
-----------------------------------

AJAX / JSON
-----------------------------------
$.ajax({
url : "test.html",
type:"GET" , //Post
data : { id : "2", pid : "1" },
context: document.body,
datatype : "html" //JSON, XML
success : handleResponse,
error : handleError
});

Function handleResponse(data)
{
alert(data);
}

Function handleError(msg)
{
alert(msg);
}
-----------------------------------

Sunday, July 11, 2010

Using Enum in Javascript


<script type="text/javascript" language="javascript">
var enumTabInfo = {
BasicInformation: 1,
SkillDetail: 2,
EducationDetail: 3,
ProjectDetail: 4,
CompanyDetail: 5
}

$(document).ready(function(){
$("div.UserTab").Hide();

var intTabNo = Number($("#<%= hdnCurrentTab.ClientID %>").val());

switch (intTabNo) {
case enumPageStep.BasicInformation:
$("#divBasicInformation").show();
break;

case enumPageStep.SkillDetail:
$("#divSkillDetail").show();
break;

case enumPageStep.EducationDetail:
$("#divEducationDetail").show();
break;

case enumPageStep.ProjectDetail:
$("#divProjectDetail").show();
break;

case enumPageStep.CompanyDetail:
$("#divCompanyDetail").show();
break;
}
});
</script>

Saturday, July 10, 2010

Enum Extention

Enum Extention :

public static class EnumExtention
{
public static Dictionary<int, string> GetEnumData(this Type EnumType)
{
Dictionary<int, string> objEnumList = new Dictionary<int, string>();

if (EnumType != null && EnumType.IsEnum)
{
foreach (int intCount in Enum.GetValues(EnumType))
{
objEnumList.Add(intCount, Enum.GetName(EnumType, intCount).ToString().Replace("_", " "));
}
}
return objEnumList;
}
}
Get Enum Data :

private enum enumUserType
{
Admin,
Sales_Department,
Purchase_Department,
Guest
}

protected void Page_Load(object sender, EventArgs e)
{
ddlUserType.DataSource = typeof(enumUserType).GetEnumData();

ddlUserType.DataTextField = "Value";
ddlUserType.DataValueField = "Key";

ddlUserType.DataBind();
}
Output :

<select name="ddlUserType" id="ddlUserType">
<option value="1">Admin</option>
<option value="2">Sales Department</option>
<option value="3">Purchase Department</option>
<option value="4">Guest</option>
</select>

Friday, July 9, 2010

OUTPUT Clause

SQL QUERY :

CREATE TABLE #tblSource ( ID INT, GroupID INT, Name VARCHAR(10) )
CREATE TABLE #tblTarget ( ID INT, GroupID INT, Name VARCHAR(10) )
CREATE TABLE #tblOutPut ( OutputAction VARCHAR(20), ID INT, GroupID INT, NewValueName VARCHAR(10), OldValueName VARCHAR(10) )

INSERT INTO #tblSource VALUES (1,1,'a11')
INSERT INTO #tblSource VALUES (2,1,'a21')
INSERT INTO #tblSource VALUES (3,1,'a31')

--- Inserted
BEGIN
INSERT INTO #tblTarget
OUTPUT
'Inserted' AS OutputAction
, INSERTED.ID
, INSERTED.GroupID
, INSERTED.Name
, NULL
INTO #tblOutPut
SELECT * FROM #tblSource
UNION ALL
SELECT ID + 10, GroupID, Name FROM #tblSource;
END

--- Updated
BEGIN
UPDATE #tblTarget
SET Name = CAST(ID AS VARCHAR) + ' : ' + Name
OUTPUT
'Updated' AS OutputAction
, INSERTED.ID
, INSERTED.GroupID
, INSERTED.Name
, deleted.Name
INTO #tblOutPut;
END

--- Deleted
BEGIN
DELETE FROM #tblTarget
OUTPUT
'Deleted' AS OutputAction
, deleted.ID
, deleted.GroupID
, null
, deleted.Name
INTO #tblOutPut
WHERE ID >= 10;
END

SELECT * FROM #tblOutPut

DROP TABLE #tblSource
DROP TABLE #tblTarget
DROP TABLE #tblOutPut
Output :
OutputAction         ID          GroupID     NewValueName OldValueName
-------------------- ----------- ----------- ------------ ------------
Inserted 1 1 a11 NULL
Inserted 2 1 a21 NULL
Inserted 3 1 a31 NULL
Inserted 11 1 a11 NULL
Inserted 12 1 a21 NULL
Inserted 13 1 a31 NULL
Updated 1 1 1 : a11 a11
Updated 2 1 2 : a21 a21
Updated 3 1 3 : a31 a31
Updated 11 1 11 : a11 a11
Updated 12 1 12 : a21 a21
Updated 13 1 13 : a31 a31
Deleted 11 1 NULL 11 : a11
Deleted 12 1 NULL 12 : a21
Deleted 13 1 NULL 13 : a31

Merge Statement with insert into output table


DECLARE @tblMergeOutput TABLE
(
ID BIGINT IDENTITY(1,1)
, MergeAction NVARCHAR(100)
, InsertedId INT
, DeletedId INT
, GroupID INT
)

CREATE TABLE #tblSource ( ID INT, GroupID INT, Name VARCHAR(10) )
CREATE TABLE #tblTarget ( ID INT, GroupID INT, Name VARCHAR(10) )

INSERT INTO #tblSource VALUES (1,1,'a11')
INSERT INTO #tblSource VALUES (2,1,'a21')
INSERT INTO #tblSource VALUES (3,1,'a31')
INSERT INTO #tblSource VALUES (4,1,'a41')

INSERT INTO #tblTarget VALUES (1,1,'a1')
INSERT INTO #tblTarget VALUES (3,1,'a3')
INSERT INTO #tblTarget VALUES (5,1,'a5')
INSERT INTO #tblTarget VALUES (6,2,'b2')
INSERT INTO #tblTarget VALUES (7,2,'b1')


---- Method 2 : Using Output insert into table
BEGIN
INSERT INTO @tblMergeOutput
SELECT MergeAction, InsertedId, DeletedID, GroupID
FROM
(
MERGE #tblTarget
USING (
SELECT *
FROM #tblSource
) AS tblSource
ON tblSource.GroupID = #tblTarget.GroupID
AND tblSource.ID = #tblTarget.ID
WHEN MATCHED THEN
UPDATE
SET Name = tblSource.Name
WHEN NOT MATCHED THEN
INSERT (
ID
, GroupID
, Name
)
VALUES (
tblSource.ID
, tblSource.GroupID
, tblSource.Name
)
WHEN NOT MATCHED BY SOURCE AND #tblTarget.GroupID = 1
THEN DELETE
OUTPUT
$action AS MergeAction
, inserted.Id AS InsertedId
, deleted.Id AS DeletedID
, tblSource.GroupID AS GroupID
) AS MergeOutput (MergeAction, InsertedId, DeletedID, GroupID);
END

SELECT * FROM #tblTarget order by GroupID, ID
SELECT * FROM @tblMergeOutput

DROP TABLE #tblSource
DROP TABLE #tblTarget

Thursday, July 8, 2010

Enable AD Hoc Distributed Queries OPENROWSET

By default Ad Hoc Distributed Queries are disabled on SQL server

If you try to run OPENROWSET you will get this error message

Server: Msg 15281, Level 16, State 1, Line 1

SQL Server blocked access to STATEMENT 'OpenRowset/OpenDatasource' of component 'Ad Hoc Distributed Queries' because this component is turned off as part of the security configuration for this server. A system administrator can enable the use of 'Ad Hoc Distributed Queries' by using sp_configure. For more information about enabling 'Ad Hoc Distributed Queries', see "Surface Area Configuration" in SQL Server Books Online.


To enable it do this

EXECUTE sp_configure 'show advanced options', 1
RECONFIGURE WITH OVERRIDE
GO

EXECUTE sp_configure 'Ad Hoc Distributed Queries', '1'
RECONFIGURE WITH OVERRIDE
GO

EXECUTE sp_configure 'show advanced options', 0
RECONFIGURE WITH OVERRIDE
GO

Openrowset Command in SQL

Syntax :

OPENROWSET
( { 'provider_name', { 'datasource';'user_id';'password'
| 'provider_string' }
, { [ catalog. ] [ schema. ] object
| 'query'
}
| BULK 'data_file',
{ FORMATFILE ='format_file_path' [ <bulk_options> ]
| SINGLE_BLOB | SINGLE_CLOB | SINGLE_NCLOB }
} )<bulk_options> ::=
[ , CODEPAGE = { 'ACP' | 'OEM' | 'RAW' | 'code_page' } ]
[ , ERRORFILE ='file_name' ]
[ , FIRSTROW = first_row ]
[ , LASTROW = last_row ]
[ , MAXERRORS = maximum_errors ]
[ , ROWS_PER_BATCH =rows_per_batch ]
Import CSV File :

SELECT
'EmployeeInfo.csv' AS FileName
, '.csv' AS FileType
, BulkColumn
FROM OPENROWSET(BULK N'C:\EmployeeInfo.csv', SINGLE_CLOB) AS Document;
Output :
FileName         FileType BulkColumn
---------------- -------- ----------------------------------------------
EmployeeInfo.csv .csv Eugene Malarky,Grove Street Smithtown,New York
Example Of SQL Database :

SELECT JSDTest.*
FROM OPENROWSET('SQLOLEDB','PC\SQLSERVER2008';'sa';'softweb',
'SELECT CategoryName, ProductName
FROM JSDTest.dbo.Product AS Product
INNER JOIN JSDTest.dbo.Category AS Category ON Category.CategoryID = Product.CategoryID
ORDER BY CategoryName, ProductName'
) AS JSDTest
Example of MDB :

SELECT a.*
FROM OPENROWSET('Microsoft.Jet.OLEDB.4.0',
'c:\MSOffice\Access\Samples\northwind.mdb';'admin';'mypwd', Orders)
AS a
Example of Excel :

SELECT *
INTO db1.dbo.table1
FROM OPENROWSET('MSDASQL',
'Driver={Microsoft Excel Driver (*.xls)};DBQ=c:\book1.xls',
'SELECT * FROM [sheet1$]')