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