Wednesday, December 4, 2013

C# Events – Concepts and Caveats – Part 4

I hope you have gone through the Part 1 to 3 of C# events.
C# Events – NullReferenceException –
If you raise an event without handlers then you get this exception – Object reference not set to instance of an object. Look below screenshot. I have commented the registration of event from Fielder class and similarly for Fan class. Also commented null check from Ball class from event raising code –

 


 
The exception is reported because none of the objects have added their event handlers to an event BallInGround, hence it will be null. Therefore it is always necessary to check null condition before raising an event.

Friday, November 29, 2013

C# Event – Understanding C# events – Part 3


Before going further it is really important to go through the Part 1 and Part 2.
AS discussed in Part 2, I will create an application based on Events. So create BallEventArgs  class as shown below –
public class BallEventArgs : EventArgs
    {
        public int Height { get; set; }
        public int Length { get; set; } 

        public BallEventArgs(int h, int l)
        {
            Height = h;
            Length = l;
        }
    }

Create Ball class as hown below with event declaration –
public class Ball
    {
        //declare event BallInGround
        public event EventHandler BallInGround; 

        /// <summary>
        /// method used for raising the event BallInGround
        /// </summary>
        /// <param name="e">BallEventArgs object</param>
        public void OnBallInGround(BallEventArgs e)
        {
            if (BallInGround != null)
            {
                BallInGround(this, e);
            }
        }
    }

Add a Fielder class as shown below –

Monday, November 11, 2013

C# event – Understanding c# Event, Event Handler and event Arguments – part 2


In this post I will explain how you can declare an Event, event Handler and Event Arguments class in c#.
 
Event Arguments –
As per the example of Cricket application we have discussed in part 1 we need a class who will explain more information about the event BallInGround so that object like Fielder, Umpire and Fan can respond to it. This we will achieve by defining Event Arguments class. .NET framework provides a standard class for declaring event arguments and it is called as EventArgs. This class has no members. This class is used for passing the event arguments to event handler method. So out declaration will be as follows –

public class BallEventArgs : EventArgs 

Event –
Next we need to declare event in a class Ball. This can be declared with c# keyword “Event”. This keyword is used to inform other objects who are interested to subscribe to it. Event declaration is as follows –

public event EventHandler BallInGround; 

Events are usually public so that other interested objects can subscribe to them. In our case other objects will be Fielder, Umpire and Fan. In above event declaration we have used EventHandler keyword. For now understand it as a keyword which used to describe the event handler method signature for this event. This is defined in .NET. When you write EventHandler after an event declaration means you state that the event handler methods will have 2 parameters, an object named sender and an EventArgs class reference variable e and void return type. [EventHandler keyword here is actually a delegate but for now to keep focus on Event understand it as a keyword provided in .NET or understand it as a event of type EventHandler]. 

Event Handler –
Each object of Fielder, Umpire and Fan will subscribe to BallInGround event. Event handler methods you have been using for a long time. When you add a button on UI and double click on it a method get’s added in code behind which is nothing but an event handler method. So event handler method for BallInGround will also be similar to button click event handler method. You might have seen following type of declaration many times –  

Sunday, November 10, 2013

C# event – Understanding c# events – part 1


Event – a noun – described as “something that happens, especially one of importance”.
Example – The formula 1 race was an amazing event to see. 

C# events are no different from description stated above. The only difference being “Something happens on - Objects”. Any c# language feature can be well understood with real life example only. C# being OOP based language; let’s consider a real life example.
 
Let’s consider a popular game of Cricket to understand C# events.
 
Suppose you are developing a wonderful game of cricket for cricket lovers. Assume that this game is going to shake the world of gaming and you will be earning billions with the popularity of this game. At first to develop basic version you need Ball, Fielder, and Umpire and Fan (the person who is crazy about cricket) objects. Here are the responsibilities of every object –
 
Ball – Lets fielder know that I am in the field and catch me.

Fielder – fields or catches the ball when ball is in the ground.

Umpire – Watches the activity when Ball is in the ground and responds accordingly.

Fan – Watches the activities happening on the Ball and yells, cheers up, celebrates and many more!!!

Now everything is in place now you just need to connect everything together. So following diagram illustrates what we wish to do – 
However there is problem because Ball does not know which fielder out of 11 present on the ground will caught or grab him. Similarly Fielder only needs to know about fielding or catching a ball. Hence Ball should only get hit and should not know about the fielder; whereas fielder should only know about catching the ball.

In short – We want every object to know about it and not others. Hence we wish to separate the concerns of each object.

When the ball is hit we will use an EVENT to let fielders know about it. So those, our fielders can respond to the event of ball. Similarly we can make other objects like Umpire, Fan to know about Ball event so that they can also respond to it. So we want Ball object to raise an event. Then we will have other objects subscribed to that type of Ball event. When event is raised the subscribed objects will be notified and they can take the action the way they want. This action to be taken when an event is raised, written in Event Handler. The event handler code is executed every time the event is raised. It is just a method in the subscriber object which runs every time event is raised.

Thursday, October 17, 2013

Gmail Tips – How to avoid sending mail without attachment


You are about to send an important mail. In the body of email you describe to view the attachment to the recipient and accidently you send the mail without attaching required files. This embarrassing moment I have experienced numerous times. Thank god I use Gmail!!
Gmail has come up with excellent feature. Say for example you are drafting a mail in which you will be attaching a file or document in it. So as soon as you start writing mail; keep any of the following wordings typed in advanced – “see attached” or “see attachment”.
In such case even if you accidently click send without file attachment, based on these 2 wording Gmail automatically searches the mail for attachment files and if it does not find any, it will show a pop up message as shown below –
 

This way you get saved from embarrassment!! Cool feature. I really love these Gmail features which are making the life of users so easy and error free.
Cheers…
Happy Gmailing!!!

Thursday, September 5, 2013

Geo Tagging – What is geo tagging and risks involved in geotag photos


Internet, facebbok and twitter kind of social sites from smartphones is very common today. Photos clicked on smartphones are immediately shared on social media like facebook. The potential of sending the information to any corner of world is unbeatable and impressive. However, one needs to understand the risks involved in such spontaneous sharing of photos and information from smart phones. The feature is “Geo Tagging”. This is very useful feature of smartphone but at the same time equally dangerous. 
What is Geo Tagging?
It is the process by which geographical location information is added to various media. Location of earth at which smartphone photo is clicked is attached with photo because of geo tagging feature. So when these photos are published on internet, this location of earth information is also gets published. This information includes latitude, longitude, height, distance, name of place and many things related to location at which photo is taken. Hence people on earth now automatically know where do you stay, where are you right now and may be they can know if you are alone or not in home. So it becomes very easy for a person who wants to track or follow you. Especially Criminals may track information using geo tagging to identify next target for robbery. Action news in America few years back had conducted a program to improve overall literacy in people about geo tagging risks. Video is here - http://www.youtube.com/watch?v=N2vARzvWxwY
Avoiding the risks of geotagging is a thing to keep in mind in this day and age of decreasing privacy.
So what exactly you need to do?

Thursday, August 22, 2013

WPF - The dependency property is already registered


This is the error you will face when you are copy pasting the code to write dependency property. JJoking…That is not the reason of this error. But I have received it when I copy pasted dependency property code from one of the site.
You will land up in this error when you have dependency property written in following way –
public readonly DependencyProperty SelectedItems2 =
            DependencyProperty.Register("SelectedItems2", typeof(string), typeof(ListBox), new PropertyMetadata(null));

What is missing here? - STATIC keyword.
The problem lies in a way you register your dependency property. You should not register in the default constructor of the class, but in static constructor or initialize it at the time of declaration and preceding with Static keyword. Best way to write dependency property without error is code snippet. Type ‘propdp’ then press tab twice. And then customize the property as per your requirement. This is how you can avoid this error; avoid learning of dependency property syntax and save time.
public static readonly DependencyProperty SelectedItems2 =
            DependencyProperty.Register("SelectedItems2", typeof(string), typeof(ListBox), new PropertyMetadata(null));

Hope this helps.
Cheers…
Happy Properting!!!

Wednesday, August 21, 2013

Facebook Tips & Facebook Help – How to get back up of your facebook data



Benefits of Facebook can be the topic of debate, because facebook is mainly being used for gaming, chatting and time passing. So facebook is for time pass and that can be proved without any survey and this is period. However if you have a look at facebook timeline; one can easily get the information of things you had done since you have joined facebook, places you had visited, how had you reacted to certain incidents, new friends and many incidents can be viewed from timeline. This information can be valuable to live the moments you spent. What If you facebook account gets deleted? Or you clicked on some virus based link and your facebook wall has some weird posts and now you only have option to delete the current account and get new? In such scenarios if you have the back up of facebook data then life will be easyJ.
Login to the facebook. Click on Settings icon present in right hand upper corner of your browser. The icon is of “Gear” sign. You will see numerous options on click on Gear sing. Out of these options choose “Account Settings”. You will see the screen as shown below –
 
As shown above choose the option “Download a copy of your facebook data”. Further you will be presented an option to selected for starting archive of your data on facebook as shown below –

Tuesday, August 20, 2013

Value produced by BindingExpression is not valid for target property – WPF-MVVM-Prism and Telerik control



Ahhh, Telerik - what a pain this is…Telerik controls have made my life bit hard…
I am using MaskedTextInput control and trying to Clear the text in it on the click on Clear button which is inbuilt in this control. It clears the text however does not clear the value in property bind to it in XAML. To understand what I mean here refer to following tag –
<ams:AmsMaskedTextInput Value="{Binding TemperatureValue,Mode=TwoWay, NotifyOnSourceUpdated=True,ValidatesOnDataErrors=True}" Mask="###.#" Placeholder=" " Width="150" HorizontalAlignment="Left" /> 

Here if I click on the default clear button available in masked text input, it clears the entered text however value entered by user persisted in TemperatureValue  property. So my aim to make the binding property set to null on click of default clear button available in masked input text control.
I was using the MVVM-Prism framework an hence I defined my command in view model as –
Microsoft.Practices.Prism.Commands.DelegateCommand TemperatureClearCommand { get; private set; } 
 
In initialize view model – TemperatureClearCommand = new Microsoft.Practices.Prism.Commands.DelegateCommand (OnMaskedTextInputClear);
And in callback method –
public void OnMaskedTextInputClear()
        {
                TemperatureValue = null;
                NotifyPropertyChanged(() => TemperatureValue);
        } 

Updated the XAML as follows –

Sunday, August 11, 2013

Google Tips - Create Nominee for Google Account using Inactive Account Manager




Today, Email account is inseparable part of everyone’s life. Email account is major tool of communication for all of your business and office work and up to some extent personal work. So down the line your email account becomes a repository of very important information containing important posts, links, photos and other personal data. It may be possible that for a period of time for example say few months, you could not access your email account due to your busy schedule or you are out for some work where internet connectivity is not available. In such cases it may happen that your email account may get closed. Sorry to write this but situation where in you may encounter an accident or sick or passed away. What will happen to your important personal information? It becomes very much necessary that this personal valuable information should fall in safe hands. 

Recently an incident happened with my friend. He is renowned social worker in India. He went to some remote place for the work and stayed for more than 6 months. After returning back, he found that his email account is closed and all data vanished. Hence letting the email account information to be handed over to known person during your absence is of vital importance.

To let the information fall in hands of the person who is known to you and to send you the notification well before the closure of your email account, Google has provided “Inactive Account Manager”. In short you create a nominee for your bank account; exactly in same way you create a nominee for your Google account.

Thursday, July 18, 2013

How to open SQL profiler in SQL Express LocalDB



SQL Profiler is an extremely wonderful tool to debug the SQL server problems. I personally love this tool very much. Recently while working with one of the project I had to deal with SQL Express LocalDB instance. According to my coding style I was very much sure that, I will need to debug at SQL level using SQL profiler to fix the issues.

As expected one of my stored procedure in SQL Express LocalDB was failing and I tried to debug it using SQL Profiler. You can open the SQL profiler in SQL Server Management Studio from “Tools” menu.

The login window appears where in you will need to put the SQL Express LocalDB server instance name. As a usual practice you may put the server name like for example, (localDB)\MyDB with connection option as Windows Authentication or with credentials for SQL Server authentication. However with this approach the SQL profiler may not open.

To overcome this problem we need to use SQLLocalDB utility. SQLLocalDB utility is command line tool which helps user to manage and perform administrative operations on SQL Express LocalDB instance. Here to connect SQL profiler to LocalDB instance we need to retrieve the correct instance name using SQLLocalDB utility. Open the command prompt and type following line in command line window.
Sqllocaldb info “InstanceName”
InstanceName in above command will be replaced by the instance name of your LocalDB server instance. The “info” command argument return you name, version, and state, last start time and most important “Local Pipe Name” of the specified LocalDB instance. The information is as shown below –
 
The local pipe name selected and reported in above command output need to be used for making the connection in SQL Server Profiler for SQL Express LocalDB as shown below –

Friday, July 5, 2013

The function import cannot be executed because it is not mapped to a store function



This is very typical error you receive when your underlying database store is changed and there is no update made to EDMX file.
For example, I imported a stored procedure in edmx and saved it. After that I change the stored procedure and do not update edmx. I run the application and at runtime the error is encountered as - “the function import cannot be executed because it is not mapped to a store function”.
This error can be resolved easily by updating the edmx. Following is procedure to resolve the error –
Open the edmx and open Model Browser. Model browser can be opened as shown below.
 
Find the required stored procedure in model browser. The right click and select option – “Delete from Model” as shown below –
 
Now right click on any area on edmx file and select the option “Update Model from Database” option. The popup containing the list of Tables, View and stored procedure will appear. Select the earlier deleted stored procedure and click “Finish” on the pop up.
Now again open the model browser and find the added stored procedure. Right click on it and select the “Edit” option as shown below -

Tuesday, June 25, 2013

Yamaha Ray – A New Step into Indian Two Wheeler Industry by Yamaha – Review and general information



The old runners of Indian roads are about to vanish now. Very popular two wheelers in scooter category like Vespa, Lambretta etc are hard to find these days on Indian roads. The all new, trendy Sports bike has replaced them in recent years. Still, an Indian mentality believes on proverb – OLD IS GOLD. The result is, people try to give new look to old bikes and try to conserve them. YAMAHA’s old bikes like RX100 are still seen on the roads.
YAMAHA bikes are of 2 strokes. That simply means the mileage of Yamaha bikes is way lower as compared to today’s leading two wheeler manufactures in India. Again Indian mentality – “old is gold”; you will find these noise making and heavy fuel drinking Yamaha bikes. The important point to note here is Yamaha never introduced and advertised their bikes as “fuel saver bikes”. In India, Yamaha is more identified for better pick-ups, speedy two wheeler bikes.
 
Yamaha’s position in Indian Market
Yamaha, originally from Japan is spread across all over the world. Two wheeler manufacturing is a small part of Yamaha organization. However, today Yamaha have made presence in whole world. Yamaha is manufacturing two wheelers since 1955. Also Yamaha is well established in Ship engines, helicopters, robots manufacturing. Since start of the company, Yamaha introduced bikes for daily use, bikes for racing and today hundreds of models are present in market.
There was huge demand for Yamaha’s two stroke bikes in India. However, Yamaha’s bikes were popular in a particular class of people. Youth with above average financial condition and who were fond of speed used to think about Yamaha bikes. With the inventions of 4-Stroke engine, fuel saving bikes came to Indian market. The Indian mentality is more leaned towards savings when it comes to money matter. The introduction of 4-stroke based fuel saving bikes changed the focus of Indian people choice for two wheeler bikes. Yamaha quickly spotted this trend and introduced 4-stroke based bikes like Spark, G5, and FZ.  However, the Yamaha still haven’t got the firm base in Indian Market. FZ caught attention, but other Yamaha bikes got very poor response.
 
Yamaha Ray
Based on previous experience Yamaha has stepped in Indian two-wheeler gearless market by introducing Ray. Yamaha Ray was launched in India in September 2012. Yamaha Ray is manufactured and is targeted for Ladies in India. The advertisement of Yamaha Ray was also broad casted to target Indian Ladies. As part of promotion Yamaha launched two wheeler driving sessions for Women. Also Yamaha Ray was manufactured in the plant which was fully operated by Women employees. After this innovative promotion also, Yamaha Ray got poor response from Indian customers. I think Yamaha follows the principle – “try try but never cry”. Yamaha launched again new Gearless two wheeler –

Friday, June 21, 2013

ListBox Data template in WPF MVVM sample



This post talks about using Data Template in WPF – MVVM. As an example I am using ListBox control. The items will be added to listbox based on data template bindings. As basic configuration create a WPF proect. Add View Models folder. I have added another project in the same solution – BusinessLayer. This actually returns list of Tasks that need to be displayed in ListBox. The final solution structure is as follows –
 

Business Layer has a class Task and TaskManager. The TaskManager class is used to create a list of Tasks which will be displayed in ListBox. The Task.cs is as follows –
public class Task
    {
        public string Name { get; set; }
 
        public string Description { get; set; } 

        public int Priority { get; set; }
    }
The TaskManager.cs contains the method to get the list of tasks. As it is very simple; I am skipping it. As part of this sample I have created a ViewModelBase class which contains the implementation of INotifyPropertyChanged  and my specific view model inherits from this base class. The code of my view model class is as follows -  
public class ViewModelBase : INotifyPropertyChanged
    {
       #region INotifyPropertyChanged implementation
        public event PropertyChangedEventHandler PropertyChanged;

        public void NotifyPropertyChanged(string propertyName)

Thursday, June 13, 2013

InkCanvas in WPF – MVVM – StrokeCollection binding


 
After long time, I got some good quality work in this project. Today I used InkCanvas in WPF-MVVM. Then I saved the shapes or drawing drawn within, to database.
Saving anything to database is OK, but the issues is – how do you get the byte array from InkCanvas Strokes? Een the major issue is how do get Strokes from InkCanvas?
Below article explains InkCanvas binding in WPF – MVVM. Alright then, to start with create a WPF project. Have ViewModel folder added in it; to have logic separation from Views. So final Structure of you application will be as follows –

 

Add InkCanvas in your XAML file and Ellipse in it to have drawing within it as written below –
<Window x:Class="StokesCollectionInMVVM.MainWindow"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <InkCanvas Background="Aqua" Strokes="{Binding StrokesEllipse}">
        <Ellipse Height="100" HorizontalAlignment="Left" Margin="116,100,0,0" Name="ellipse1" Stroke="Black" VerticalAlignment="Top" Width="200" />   
        </InkCanvas>
    </Grid>
</Window>

The view model code will be as follows –
Class variables and View model class definition is as follows –
public class MainWindowsViewModel : INotifyPropertyChanged
    {
        #region INotifyPropertyChanged implementation
        public event PropertyChangedEventHandler PropertyChanged; 

        private void RaisePropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
        #endregion 

        #region Class variables       

        private StrokeCollection _strokesEllipse = null;

        #endregion

In constructor – [Note – Code to save byte array in database and retrieve it from database is skipped]
public MainWindowsViewModel()
        {
            //to autopopulate saved drawing on UI -
            //read byte array from say - database and store in EllipseDrawing property
            if (EllipseDrawing != null)
            {
                using (var memoryStream = new MemoryStream(EllipseDrawing))
                {
                    _strokesEllipse = new StrokeCollection(memoryStream);
                }
            }
            else
            {
                _strokesEllipse = new StrokeCollection();
            } 

            (_strokesEllipse as INotifyCollectionChanged).CollectionChanged += new NotifyCollectionChangedEventHandler(MainWindowsViewModel_CollectionChanged);
        }
The handler method of this event is as follows – [Note – Code to save byte array in database and retrieve it from database is skipped]