Author Archives: Vivek Mehta

ObservableCollection vs. List. DataBinding – Which one to use when?

Would it be enough to track changes to objects already in the list? Or do you need to know when objects are removed from/are added to/change positions within the list?

If a list will contain the same items for their whole lifetime, but the individual objects within that list will change, then it’s enough for just the objects to raise change notifications (typically through INotifyPropertyChanged) and List<T> is sufficient. But if the list will contain different objects from time to time, or if the order changes, then you should use ObservableCollection<T>.

Advertisements

Example on how to use static resource(xml) data in xaml and bind it with combo box

<XmlDataProvider x:Key="RuleOperators" XPath="Items">
                            <x:XData>
                                <Items xmlns="">
                                    <Item Label="-- Select --" Value=""/>
                                    <Item Label="Is Equal to" Value="="/>
                                    <Item Label="Is Not Equal to" Value="!="/>
                                    <Item Label="Is Less than" Value="&lt;"/>
                                    <Item Label="Is Less than or Equal to" Value="&lt;="/>
                                    <Item Label="Is Greater than" Value="&gt;"/>
                                    <Item Label="Is Greater than or Equal to" Value="&gt;="/>
                                </Items>
                            </x:XData>
                        </XmlDataProvider>

<ComboBox ItemsSource="{Binding Source={StaticResource RuleOperators}, XPath=*, Mode=OneTime}" SelectedValue="{Binding Value, UpdateSourceTrigger=PropertyChanged}" SelectedValuePath="@Value"  DisplayMemberPath="@Label" />

Get current time of any country

//To find out the current time in any country, factoring in Daylight saving, we can use the following code

/* We generate all the timezones so we can pick as and when necessary */
public static readonly ReadOnlyCollection<TimeZoneInfo> TimeZones = TimeZoneInfo.GetSystemTimeZones();

/* Get the timezone of the exchange currently in operation */
TimeZoneInfo info = TimeZoneInfo.FindSystemTimeZoneById(“Indian Standard Time”);

/* Get the offset */
var dto = DateTimeOffset.UtcNow;

/*Now get the current time for the exchange */
var currentTime = TimeZoneInfo.ConvertTimeBySystemTimeZoneId(dto, info.Id);

Access parent object data context

Say if i have a Textbox inside a canvas control and canvas datacontext is set to address object on view model. Now this textbox will by default inherit and correspond to the attributes of this address object in view model. So if this address object has properties like AddressLine1, Street, City etc then i can use any of these to set my textbox text.

But what If i need to go one level up to parent data context and get the name of the main customer object which is bound to the window(or for any matter any parent control) then i can do this:

Binding=”{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}, Path=DataContext.FirstName}

Post via Email to a WordPress blog

We need to follow the following steps to post via email from WordPress blog:

  1. I was using a gmail account. The domain was also managed by google but this shouldn’t matter even if it’s a regular gmail account. Need to make sure that POP/IMAP access is enabled. This is done in settings page.
  2. Make sure this is a fresh new email setup exclusively for this purpose. Don’t use your regular daily email account because every mail in inbox will get picked up for posting
  3. Need to make sure that the the access to less secure app is turned on. Its available here: https://www.google.com/settings/security/lesssecureapps. This will not work if the email account is setup for 2-step verification
  4. I installed a plugin called Postie on the wordpress blog and configured this plugin for post via email on its settings page.
  5. On this settings page, Mailserver tab, I entered the new email account along with other settings like IMAP server name, port and login credentials
  6. Also on the settings page, in message tab, i set changed two settings: Filter newlines = Yes and Replace newline characters with html line breaks (<br />)  = Yes. This allows the line breaks to be preserved the way they are in the original email.
  7. I was using cpanel on my web hosting server. I had to setup a cron job. This was setup using the following command: wget –user=[username] –password='[password]’ http://%5Bmysite%5D/?postie=get-mail. I have set up username/password to access this site so i had to pass this in my wget command. I set this to work once per hour.

Handy DateTimeConverter

You can use this DateTimeConverter to bind all your string values to DateTime controls and vice-versa

 public class DateTimeConverter : IConverter<string, DateTime>
 {
            private static readonly IFormatProvider FormatProvider = 
            (IFormatProvider) CultureInfo.InvariantCulture;

     static DateTimeConverter()
     {
 
     }

     public string Convert(DateTime dateTime)
     {
         return dateTime.ToString(DateTimeConverter.FormatProvider);
     }  

     public DateTime ConvertBack(string dateTimeString)
     {
         return DateTime.Parse(dateTimeString, DateTimeConverter.FormatProvider);
     }
 }

 

Get compile time support for Property names

Hello,

Many times we need to use string values for C# properties. Although this is not a common practise, we may not have choice sometimes e.g. using RX –

Observable.FromEventPattern<PropertyChangedEventArgs>(this,"PropertyChanged")
 .Where(e => e.EventArgs.PropertyName == "SearchString")
 .Subscribe(_ => DoSomeWork());

In this case,  we have to pass the string value (name) of the property for RX Observable to work. I am interested in subscribing to this event of my property(which is in turn bound to textbox on view).

So I can either pass the string literal which provides no compile time support or I can use expression trees to pass an expression and retrieve string name literal at runtime as follows:

Observable.FromEventPattern<PropertyChangedEventArgs>(this,"PropertyChanged")
 .Where(e => e.EventArgs.PropertyName == GetPropertyName(() => SearchString))
 .Subscribe(_ => DoSomeWork());

This works because I have written a private function in my class to extract the actual string name from the propertyname. The function is as follows:

public static string GetPropertyName<T>(Expression<Func<T>> expression)
{
    MemberExpression memberExpression = (MemberExpression)expression.Body;
    return memberExpression.Member.Name;
}

Have a nice day!