Saturday, October 31, 2015

JQuery: Using Draggable control from JQuery

Draggable:

Below JSFiddle demo provides simple way to drag drop <div> around. It is very simple code and can be done easily using JQuery.
For more details visit JQuery website i.e. http://jqueryui.com/draggable/
Below is JSFiddle link where you can play with Draggable control.

JSFiddle:

Thursday, October 29, 2015

JavaScript: Opening HTML dropdown panel on MouseOver using JavaScript.

There could be a scenario where you have to open Dropdown panel on ‘mouseover’. It could become more irritating if you don't do it right. I got a JavaScript method to do that.

The code is below and demo could be seen here. (https://jsfiddle.net/SiddharthMishra/kzdkpmvq/1/embedded/result/)

You can play with it by using JSFiddle.

JSFiddle:


HTML Code

We have created a simple HTML Dorpdown element here.

<select id="actionList">
       <option action="">ACTIONS</option>
       <option action="add">ADD NEW</option>
<option action="edit">EDIT</option>
</select>


JavaScript Code: 

We will add JavaScript methods to ‘ onmouseover ’ and ‘onmouseleave’ events.

 
var actionList = document.getElementById("actionList");

actionList.onchange = 
function () { templateAction(templateActionList); }

actionList.onmouseover = 
function () { selectElementMouseover(actionList); }

actionList.onmouseleave = 
function () { selectElementMouseleave(actionList); }

function selectElementMouseover(element) {
    fireEvent(element, "mousedown");
    fireEvent(element, "mouseup");
}
 
function selectElementMouseleave(element) {
    fireEvent(element, "mousedown");
}


Now below method will take care of the rest:
// To fire any event from JavaScript.
function fireEvent(node, eventName) {
    var doc;
    if (node.ownerDocument) {
        doc = node.ownerDocument;
    } else if (node.nodeType == 9) {
        doc = node;
    } else {
        throw new Error("Invalid node passed to fireEvent: " + node.id);
    }
 
    if (node.dispatchEvent) {
        var eventClass = "";
 
        // Different events have different event classes.
        switch (eventName) {
            case "click"// 'click' works correctly in Safari. 
                          // For other we should use 'mousedown' or 'mouseup'.
            case "mousedown":
            case "mouseup":
                eventClass = "MouseEvents";
                break;
 
            case "focus":
            case "change":
            case "blur":
            case "select":
                eventClass = "HTMLEvents";
                break;
 
            default:
                throw "fireEvent: Couldn't find an event class for event '" 
                        + eventName + "'.";
                break;
        }
        var event = doc.createEvent(eventClass);
 
        var bubbles = eventName == "change" ? false : true;

        // All events created as bubbling and cancelable.
        event.initEvent(eventName, bubbles, true); 
 
        event.synthetic = true
        node.dispatchEvent(event, true);
    } else if (node.fireEvent) {
        var event = doc.createEventObject();
        event.synthetic = true
        node.fireEvent("on" + eventName, event);
    }
};


Reference: http://jsfiddle.net/mendesjuan/rHMCy/4/

Thursday, March 12, 2015

WPF: Simple TimePicker User Control for WPF

Hey Guys!
WPF gives us DatePicker but it doesn’t give us TimePicker. I tried to create a very simple TimePicker user control.

And the bumper offer is that it is free. Use it wherever you want. J
Hope this will help you a lot.

XAML Code:
==========

I used TextBlocks to show Hours and Minutes. Up and Down buttons are attached to increment decrement hours and minutes. Drop down with AM/PM values actually add/subtracts 12 hours from actual time based on your selection. I have created SelectedTime dependency property to do bindings.

<UserControl x:Class="UserControls.ucDateTimeUpDown"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             mc:Ignorable="d">
    <Grid>
        <Border BorderBrush="Black" BorderThickness=".25" />
        <StackPanel Orientation="Horizontal">


            <TextBlock x:Name="AddHoursTextBox"
                       MinWidth="20"
                       HorizontalAlignment="Center"
                       VerticalAlignment="Center"
                       Text="{Binding DisplayTimeHours,
                                      Mode=OneWay}"
                       TextAlignment="Center" />
            <StackPanel HorizontalAlignment="Center"
                        VerticalAlignment="Center"
                        Orientation="Vertical">
                <Button x:Name="HourUpButton" Click="HourUpButton_OnClick">
                    <Button.Template>
                        <ControlTemplate TargetType="Button">
                            <Border BorderBrush="Black" BorderThickness=".25">
                                <Viewbox Width="10" Height="10">
                                    <Image Source="{StaticResource UpImage}" />
                                </Viewbox>
                            </Border>
                        </ControlTemplate>
                    </Button.Template>
                </Button>

                <Button x:Name="HourDownButton"
                        Margin="0,-1,0,0"
                        Click="HourDownButton_OnClick">
                    <Button.Template>
                        <ControlTemplate TargetType="Button">
                            <Border BorderBrush="Black" BorderThickness=".25">
                                <Viewbox Width="10" Height="10">
                                    <Image Source="{StaticResource DownImage}" />
                                </Viewbox>
                            </Border>
                        </ControlTemplate>
                    </Button.Template>
                </Button>
            </StackPanel>
            <TextBlock Margin="3,0,0,0"
                       HorizontalAlignment="Center"
                       VerticalAlignment="Center"
                       Text="h." />
            <TextBlock Margin="3,0,0,0"
                       HorizontalAlignment="Center"
                       VerticalAlignment="Center"
                       Text=":"
                       TextAlignment="Center" />
            <TextBlock x:Name="AddMinutesTextBox"
                       MinWidth="20"
                       HorizontalAlignment="Center"
                       VerticalAlignment="Center"
                       Text="{Binding DisplayTimeMinutes,
                                      Mode=OneWay}"
                       TextAlignment="Center" />


            <StackPanel HorizontalAlignment="Center"
                        VerticalAlignment="Center"
                        Orientation="Vertical">
                <Button x:Name="MinutesUpButton" Click="MinutesUpButton_OnClick">
                    <Button.Template>
                        <ControlTemplate TargetType="Button">
                            <Border BorderBrush="Black" BorderThickness=".25">
                                <Viewbox Width="10" Height="10">
                                    <Image Source="{StaticResource UpImage}" />
                                </Viewbox>
                            </Border>
                        </ControlTemplate>
                    </Button.Template>
                </Button>

                <Button x:Name="MinutesDownButton"
                        Margin="0,-1,0,0"
                        Click="MinutesDownButton_OnClick">
                    <Button.Template>
                        <ControlTemplate TargetType="Button">
                            <Border BorderBrush="Black" BorderThickness="0.25">
                                <Viewbox Width="10" Height="10">
                                    <Image Source="{StaticResource DownImage}" />
                                </Viewbox>
                            </Border>
                        </ControlTemplate>
                    </Button.Template>
                </Button>
            </StackPanel>
            <TextBlock Margin="3,0,3,0"
                       HorizontalAlignment="Center"
                       VerticalAlignment="Center"
                       Text="m." />

            <ComboBox x:Name="AmPmComboBox"
                      MinWidth="45"
                      HorizontalAlignment="Center"
                      VerticalAlignment="Center"
                      BorderThickness=".25"
                      ItemsSource="{Binding AmPmTypes}"
                      SelectedItem="{Binding DisplayAmPm}" />
        </StackPanel>


    </Grid>
</UserControl>

Code behind:
=========

The code behind may not be so good. We can restructure and re-factor this code. I made this user control in hurry so pardon me for code quality.

using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Windows;
using System.Windows.Controls;

namespace UserControls
{
  /// <summary>
  /// Interaction logic for ucDateTimeUpDown.xaml
  /// </summary>
  public partial class ucDateTimeUpDown : UserControlINotifyPropertyChanged
  {
    #region Private Member variable

    private DateTime _currentTime = DateTime.UtcNow;
    private bool _adHours;
    private bool _addMinutes;
    private ObservableCollection<string> _amPmTypes 
new ObservableCollection<string>();
    private string _displayAmPm;

    #endregion

    #region Constructors

    public ucDateTimeUpDown()
    {
      InitializeComponent();
      this.DataContext = this;
      AmPmTypes.Add("AM");
      AmPmTypes.Add("PM");
      CurrentTime = DateTime.UtcNow.ToLocalTime();
      SelectedTime = CurrentTime.ToLocalTime().ToString("t");
    }

    #endregion

    #region Public Properties

    public ObservableCollection<string> AmPmTypes
    {
      get { return _amPmTypes; }
      set { _amPmTypes = value; }
    }

    public string DisplayTime
    {
      get { return _currentTime.ToLocalTime().ToString("t"); }
    }


    public string DisplayAmPm
    {
      get
      {
        if (_currentTime.ToLocalTime().Hour >= 0 
&& _currentTime.ToLocalTime().Hour < 12)
          _displayAmPm = AmPmTypes.FirstOrDefault(s => s.Equals("AM"));
        else
        {
          if (_currentTime.ToLocalTime().Hour >= 12)
          {
            _displayAmPm = AmPmTypes.FirstOrDefault(s => s.Equals("PM"));
          }
        }

        return _displayAmPm;
      }
      set
      {
        if (!value.Equals(_displayAmPm))
        {
          if (value.Equals("PM"))
            CurrentTime = CurrentTime.ToLocalTime().AddHours(12);
          else
          {
            CurrentTime = CurrentTime.ToLocalTime().AddHours(-12);
          }
        }
        _displayAmPm = value;
      }
    }

    public string DisplayTimeHours
    {
      get
      {
        var hours = _currentTime.ToLocalTime().Hour;
        return hours > 12 ? (hours - 12).ToString("00") : hours.ToString("00");
        //return hours.ToString();
      }
      set
      {
        var hour = 0;
        Int32.TryParse(valueout hour);
        CurrentTime = CurrentTime.ToLocalTime().AddHours(hour);
        OnPropertyChanged("DisplayTime");
        OnPropertyChanged("DisplayTimeHours");
        OnPropertyChanged("DisplayTimeMinutes");
      }
    }

    public string DisplayTimeMinutes
    {
      get { return _currentTime.ToLocalTime().Minute.ToString("00"); }
      set
      {
        var minutes = 0;
        Int32.TryParse(valueout minutes);
        CurrentTime = CurrentTime.ToLocalTime().AddMinutes(minutes);
        OnPropertyChanged("DisplayTime");
        OnPropertyChanged("DisplayTimeHours");
        OnPropertyChanged("DisplayTimeMinutes");
      }
    }

    public DateTime CurrentTime
    {
      get { return _currentTime; }
      set
      {
        _currentTime = value;

        OnPropertyChanged("CurrentTime");
        OnPropertyChanged("DisplayTime");
        OnPropertyChanged("DisplayTimeHours");
        OnPropertyChanged("DisplayTimeMinutes");
        OnPropertyChanged("DisplayAmPm");
        SelectedTime = value.ToLocalTime().ToString("t");
      }
    }

    #endregion

    #region Dependency Properties

    public static readonly DependencyProperty SelectedTimeProperty 
DependencyProperty.Register(
      "SelectedTime"typeof (string), typeof (ucDateTimeUpDown), 
new PropertyMetadata(default(string)));

    public string SelectedTime
    {
      get { return ((DateTime) GetValue(SelectedTimeProperty))
.ToLocalTime().ToString("t"); }
      set { SetValue(SelectedTimeProperty, value); }
    }

    #endregion

    #region Methods

    private void MinutesUpButton_OnClick(object sender, RoutedEventArgs e)
    {
      CurrentTime = CurrentTime.AddMinutes(1);
      SelectedTime = CurrentTime.ToLocalTime().ToString("t");
    }

    private void MinutesDownButton_OnClick(object sender, RoutedEventArgs e)
    {
      CurrentTime = CurrentTime.AddMinutes(-1);
      SelectedTime = CurrentTime.ToLocalTime().ToString("t");
    }

    private void HourUpButton_OnClick(object sender, RoutedEventArgs e)
    {
      CurrentTime = CurrentTime.AddHours(1);
      SelectedTime = CurrentTime.ToLocalTime().ToString("t");
    }

    private void HourDownButton_OnClick(object sender, RoutedEventArgs e)
    {
      CurrentTime = CurrentTime.AddHours(-1);
      SelectedTime = CurrentTime.ToLocalTime().ToString("t");
    }

    #endregion

    #region INotifyPropertyChanged Implementation

    public event PropertyChangedEventHandler PropertyChanged;

    public void OnPropertyChanged(string propertyName)
    {
      if (null != PropertyChanged)
      {
        PropertyChanged(thisnew PropertyChangedEventArgs(propertyName));
      }
    }

    #endregion
  }
}



I hope you will find above user control quite useful. You suggestions are welcome. Please send your comments and improvement suggestion.

Have a good day!