C# | .NET : Smart Duration Class

C# | .NET : Smart Duration Class

[Originally posted on 11 October 13]

Sometimes you need to have start and end dates, validate whether these dates define valid duration, or determine overlapping duration/timespan in two given duration(s)? I wrote an MVVM ready, equitable, duration class which does all the above and a little more. :-). I call this class TimeDuration. Let’s go through the code of the class.

TimeDuration implements two interfaces,  IEquatable and INotifyPropertyChanged. In later parts we will see the implementation of methods for IEquatable, let’s see INotifyPropertyChanged implementation first.  It has System.ComponentModel and a PropertyChangedEventHandler type public event PropertyChanged. It has a private method onPropertyChanged with a return type void. The complete INotifyPropertyChanged implementation looks like this:

using System;
using System.ComponentModel;

namespace Demo.DateExtentions
{
    public class TimeDuration : IEquatable, INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
        private void onPropertyChanged(string name)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(name));
            }
        }
    }
}

The class encapsulate two basic information elements – start time and end time. To expose this information class has two public DateTime type properties; Start and End. To notify views when the basic information changes in VM the class calls onPropertyChanged method from inside settters of both these properties. The implementation code looks like this:

        DateTime start;
        DateTime end;
        public DateTime Start
        {
            get { return start; }
            set
            {
                if (start != value)
                {
                    start = value;
                    onPropertyChanged("Start");
                }
            }
        }
        public DateTime End
        {
            get { return end; }
            set
            {
                if (end != value)
                {
                    end = value;
                    onPropertyChanged("End");
                }
            }
        }

The class initializes DateTime structured in the constructor so that object based on this class is ready for use on initialization. Constructor looks like so:

        public TimeDuration()
        {
            start = new DateTime();
            end = new DateTime();
        }

(Fields could have been initialized at the time of defining the field and not have the constructor at all.)
Duration represents a time span, so TimeDuration class has a TimeSpan type public property named Duration. This property returns the difference of start and end times. Code is like this:

        public TimeSpan Duration { get { return end - start; } }

This part makes the class a smart duration class. TimeDuration is capable of telling intersecting duration/timespan between two given durations. Following figure illustrates intersecting durations:
DurationFigure

In the figure above AB, CD, EF, and GH represent durations. Class returns information regarding CB in the context of AB and CD, where starting part of CD overlaps with end part of AB. The method returns overlap duration if one duration completely falls inside of another duration, as in AB and EF, where EF completely lies inside AB. The third scenario is where tail part of one duration overlaps with head part of another duration as in AB and GH where overlap is occurring at AH. Following is the code to return appropriate type, TimeSpan or TimeDuration, after checking the intersection.

        public TimeSpan IntersectingSpan(TimeDuration other)
        {
            return getIntersection(other).Duration;
        }
        public TimeDuration IntersectingDuration(TimeDuration other)
        {
            return getIntersection(other);
        }
        private TimeDuration getIntersection(TimeDuration other)
        {
            if (this.Equals(other)) return this;
            DateTime iStart = this.Start < other.Start ? other.Start : this.Start;
            DateTime iEnd = this.End < other.End ? this.End : other.End;
            return iStart < iEnd ? new TimeDuration(iStart, iEnd) : new TimeDuration();
        }

IEquatable interface implementation:

        public bool Equals(TimeDuration compareWith)
        {
            return CompareWith.Start == this.Start && CompareWith.End == this.End;
        }
        public override int GetHashCode()
        {
            return _start.GetHashCode() ^ _end.GetHashCode();
        }

The entire SmartDuration class:

/*
 * Disclaimer
 * Unless otherwise noted, code snippets in this repository are licensed under a Creative Commons Attribution 4.0 International license (http://creativecommons.org/licenses/by/4.0/)
 * Please do not forget to credit if you choose to use code in any which way.  You can credit in any way you please as below:
        By Sanjay (http://sharpsnippets.wordpress.com/)
        By Sanjay (http://www.twitter.com/SanjayAtPilcrow)
 * Blog post about following code: http://wp.me/p2iWZr-4T
 * General Notes
 *      - This is working code, but not production code.
 *      - Code follows universal C# code convention but might not follow your company's internal convention.
 *      - Code is more of POC and thus does not have full exception handling and parameter checking.
 *      - If you choose to use the code in production, do re-code to make it production ready as per your org's engineering policy.
*/
using System;
using System.ComponentModel;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace POCs.Sanjay.SharpSnippets.Dates
{
    public class TimeDuration : IEquatable, INotifyPropertyChanged
    {
        DateTime start;
        DateTime end;
        public DateTime Start
        {
            get { return start; }
            set
            {
                if (start != value)
                {
                    start = value;
                    onPropertyChanged("Start");
                }
            }
        }
        public DateTime End
        {
            get { return end; }
            set
            {
                if (end != value)
                {
                    end = value;
                    onPropertyChanged("End");
                }
            }
        }
        public event PropertyChangedEventHandler PropertyChanged;
        public TimeDuration()
        {
            start = new DateTime();
            end = new DateTime();
        }
        public TimeDuration(DateTime start, DateTime end)
        {
            start = start;
            end = end;
        }
        public bool IsValidDuration
        {
            get { return _start <= _end; }
        }
        public TimeSpan Duration { get { return end - start; } }
        public TimeSpan IntersectingSpan(TimeDuration other)
        {
            return getIntersection(other).Duration;
        }
        public TimeDuration IntersectingDuration(TimeDuration other)
        {
            return getIntersection(other);
        }
        private TimeDuration getIntersection(TimeDuration other)
        {
            if (this.Equals(other)) return this;
            DateTime iStart = this.Start < other.Start ? other.Start : this.Start;
            DateTime iEnd = this.End < other.End ? this.End : other.End;
            return iStart < iEnd ? new TimeDuration(iStart, iEnd) : new TimeDuration();
        }

        #region Equatable
        public bool Equals(TimeDuration compareWith)
        {
            return CompareWith.Start == this.Start && CompareWith.End == this.End;
        }
        public override int GetHashCode()
        {
            return _start.GetHashCode() ^ _end.GetHashCode();
        }
        #endregion //Equatable

        #region notify property changed
        private void onPropertyChanged(string name)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(name));
            }
        }
        #endregion

    }
}

Find code on my GitHub repository.

 

iPhone 6 Project For App Prototyping in Microsoft SketchFlow

iPhone 6 Project For App Prototyping in Microsoft SketchFlow

I have updated Microsoft Blend SketchFlow project for latest iPhone 6 frame. Download projects from GitHib. As earlier the project has built in iPhone 6 frame, animated keyboard image, iPhone 6 home screen, and clickable home button.

My earlier posts have detailed information about other Sketchflow projects and video tutorial of how to use them.

SketchFlow is a powerful prototyping tool. In last post I shared Windows Phone SketchFlow template project. Here I am sharing iPhone skeleton project for SketchFlow. Both these projects are similar in functionality with different phone frames. Android projects are on their way. Read more…

Cortana in Microsoft Office 16 and in Smartwatch (Vine Videos)

Cortana in Microsoft Office 16 and in Smartwatch (Vine Videos)

“Cortana in Office” Vine videos are below in the post.

I heard some new features are coming to Office 16. One of them will supposedly be some assistant similar to Clippy. I suggest, let’s not bother Clippy any more, just say – “Cortana, will you assist Office users on Windows 9″. She gladly will. After all, Cortana is a Personal Digital Assistant. Following are some scenarios I envisioned with MS Office:

  • “Cortana, create a table with 5 rows and 10 columns”.
  • “Cortana, in cell A5, find the average of values in cells A1 to A4.
  • “Cortana, find a 200 word excerpt from Shakespeare’s Macbeth and insert in the document.”

So I virtually (yes) put Cortana in Office 16 in these Vine videos (feels real with sound, so enable sound):






And here is Cortana helping with Formula. (enable sound, disable the first one :D)






How about Cortana reminding on a smartwatch!? (And if you are interested this is my smart timekeeping app for your Windows Phone, free and no adverts)

I like Cortana. If you do too, you might like my other futuristic Cortana integration fact-ions.

Cortana, find me the nearest top-rated coffee shop?

App Marketing: Perspective Marketing Image Template (PSD)

App Marketing: Perspective Marketing Image Template (PSD)

Recently I created an XCF template for app marketing and wrote a post about how to use it.

Nokia Lumia 1520 is a gorgeous phone. So is your Windows Phone app’s hub in panorama. And you do know that a well developed app is just the half way. Getting the app to its audience is the second half. I created this layered GIMP image to easily sandwich a panorama hub between the layers and showcase your app with your own shining colors. You need to do following to create your app’s panorama with this template: Read more…

Some people wanted the template in PSD format. So, here you are.

Hope you find it useful.

ASO Tool: Cover Your Keywords

ASO Tool: Cover Your Keywords

Download KeywordsSearch.xlsx from GitHub.

ASO stands for Application Search Optimization (like SEO; Search Engine Optimization). Know more here. To improve the chances of search engines or app stores (Windows Phone Store, Google Play, Apple iPhone, iPAD Store) finding your app, your app needs a good description which includes as many related words. To achieve this, you would typically first decide your app related keywords and use them in app description. This is easier said than done. To help, I created this small tool in Microsoft Excel, which you can use to list down the keywords with value of importance, type description, and see the coverage of keywords you have used in your description. Download KeywordsSearch.xlsx from GitHub.

How to use?

ASO Excel Tool for Application Search Optimization Google Play Store Windows Phone

  1. Decide keywords and type them according to their value in the respective columns. High value keywords are those which are a must for app’s discoverability. Medium value keywords are important and low value ones are good to have.
  2. Type app’s description in this cell. Try to include as many keywords as possible in your text. As and when you want to see which of the keywords you have used in your description, either exit out of the cell by pressing Tab or press ctrl + Enter. You will notice that the words you have used in the text have now green background, and those which are still not used remain with red background. Keep typing and try to turn as many words as possible, green.
  3. The coverage section will show what percent of High, Medium, and Low value keywords you have used in the text you have typed.
  4. Legend section talks about meaning of color and formatting of text in keyword list.

Prototype iPhone Apps in SketchFlow

Prototype iPhone Apps in SketchFlow

Edit: Updated for iPhone 6

Download projects from GitHib.

SketchFlow is a powerful prototyping tool. In last post I shared Windows Phone SketchFlow template project. Here I am sharing iPhone skeleton project for SketchFlow. Both these projects are similar in functionality with different phone frames. Android projects are on their way.

Download projects from GitHib.

Excerpt from earlier Post:

Those who have exposure to Visual Studio Blend, WPF/Silverlight developers, SketchFlow comes as natural extension to quickly prototype app ideas. Other prototyping tools are – Pencil, Balsamiq,Axure, SmartDraw, Visio etc. Recently, I wrote an introductory post about open source prototyping tool, Pencil, with example navigation flow screens. In my experience I found SketchFlow to be very efficient in creating high-fidelity prototypes. This project template gives, out-of-the-box, phone frame images, dummy keyboard with interactive states, back button, and home button. The phone frame images included are – Windows Phone emulator stock image, Nokia Lumia 925, Nokia Lumia 1520, and HTC One. Android phones and iPhone are in plans.

For a quick demo, have a look at this video:

Following are some screen shots of the SketchFlow player:

SketchFlow Prototype Project iPhone iOS Keyboard Windows Phone AppDev Blend Visual Studio WFP XAML Animation

SketchFlow Prototype Project iPhone iOS Keyboard Windows Phone AppDev Blend Visual Studio WFP XAML Animation

Prototype Windows Phone App in SketchFlow

Prototype Windows Phone App in SketchFlow

Download the template project from GitHub.

[This post got a mention on Microsoft Channel 9 This Week]

SketchFlow is one of the best prototyping tools available. SketchFlow is part of Blend which is now an integrated tool with Visual Studio. Those who have exposure to Blend, WPF/Silverlight developers, SketchFlow comes as natural extension to quickly prototype app ideas. Other prototyping tools are – Pencil, Balsamiq,Axure, SmartDraw, Visio etc. Recently, I wrote an introductory post about open source prototyping tool, Pencil, with example navigation flow screens. In my experience I found SketchFlow to be very efficient in creating high-fidelity prototypes. SketchFlow provides free form screens to create any type of prototypes – web site, web app, SPI, desktop app, or smartphone apps. This is powerful. But, with great power comes great boilerplate work :D. I so needed some kind of Windows Phone specific template project in SketchFlow which I could use to quickly draw my pages in and let template take care of generic phone specific look and feel (interactions). I didn’t find one. So I created one. This project template gives, out-of-the-box, phone frame images, dummy keyboard with interactive states, back button, and home button. The phone frame images included are – Windows Phone emulator stock image, Nokia Lumia 925, Nokia Lumia 1520, and HTC One. Android phones and iPhone are in plans.

Watch this video for a quick go through of the project and also to know how you can swap phone frames in seconds, throughout all prototype screens in the project:

Following are some of the screen shots of the project in action:

SketchFlow Prototype Nokia Lumia 1520 Windows Phone AppDev Blend Visual Studio

SketchFlow Prototype Project Nokia Lumia 1520 Windows Phone AppDev Blend Visual Studio

SketchFlow Prototype Application Emulator Windows Phone AppDev Blend Visual Studio

And yes, with my other project you can create prototypes for iPhone in Microsoft SketchFlow.

Happy mocking-up! :D