Friday, February 10, 2012

C# how to check that ListBox has no selected items

If you want to perform some activity only when the ListBox has selected item/s, do the following:


If MultiColumn == false

if (list_box.SelectedItems.Count == 1)
{
    my_function(some_parameter);
}

If MultiColumn == true


if (list_box.SelectedItems.Count > 0)
{
    my_function(some_parameter);
}

C# using the TimeSpan structure to calculate remaining time

If you want to calculate the time left from now to some future date, this is what I used in my Reminder Winform/C# application:


The function gets DateTime parameter with a future date:


void remained_time(DateTime date_time_reminder)
{
    DateTime date_time_now = DateTime.Now;
    TimeSpan time_span = date_time_reminder - date_time_now;

    string time = string.Format("{0:00}:{1:00}:{2:00}", time_span.Hours, time_span.Minutes, time_span.Seconds);
    tb_time.Text = "Left: " + time_span.Days.ToString() + " days, " + time;
}


The output is: Left: 42 days, 21:13:07

Note:
It's better to use string.Format in a way stated above because the plain TimeSpan.Hours/Minutes/Seconds displays only one digit when the TimeSpan value is a single digit, i.e. 12:3:3 instead of 12:03:03

C# convert string to DateTime structure

So, you need to convert a string do DateTime structure, i.e. string from Database. The key is to save the string in an extensive format which includes years, months, days, hours, minutes and seconds, for example: "dddd, MMMM d, yyyy hh:mm:ss" which displays as "Friday, February 10, 2012, 12:04:14"
This way the DateTime structure will contain the commonly used time parameters for further processing.



using System;

string my_time = "Friday, February 10, 2012, 12:04:14"
DateTime reminder_date_time = DateTime.Parse(my_time);

Thursday, February 9, 2012

C# strip string from special characters using Regex

Stripping strings from special characters is pretty easy.
If you want to add special characters to keep, add them in the Regex square brackets, i.e. [^a-zA-Z0-9_.-]
using System.Text.RegularExpressions;
string NoSpecialCharacters(string your_string)
{
    return Regex.Replace(your_string, "[^a-zA-Z0-9]+", "");
}

C# LINQ to XML select by value

Here's my way to filter values in XML and bind to new XML:

The explanation is based on a "Reminder" application I wrote using VS2010 WPF/C#.

1. The structure of the XML I used:

<Reminders>
  <Reminder Title="Wash dishes" Time="3/24/2012 12:00:00" Status="Active"/>
  <Reminder Title="Feed the fish" Time="4/24/2012 12:00:00" Status="Closed"/>
  <Reminder Title="Walk the dog" Time="5/24/2012 12:00:00" Status="Active"/>
  <Reminder Title="Watch LOTR" Time="5/14/2012 12:00:00" Status="Closed"/>
</Reminders>

2. Select all the "Reminder" nodes with Status="Active"

private void my_xml()
{
    XElement new_xml = new XElement("Reminders");
    
    try
    {
        XElement data = XElement.Load(@"C:\your_path\reminder_data.xml");

        var reminders = from reminder in data.Descendants("Reminder")
                        where reminder.Attribute("Status").Value == "Active"
                        select reminder;

        foreach (var reminder in reminders)
        {
           new_xml.Add(reminder);
        }
    }
    catch (Exception ex)
    {
        throw ex;
    }
}



WPF/C# binding XML to DataGrid

The explanation is based on a "Reminder" application I wrote using VS2010 WPF/C#.
Irrelevant lines of code along with some control attributes such as Width, Height etc are dropped in order to keep the lines shorter.

1. The structure of the XML I used:




<?xml version="1.0" encoding="utf-8" ?>
<Reminders>
  <Reminder Title="Wash dishes" Time="3/24/2012 12:00:00" />
  <Reminder Title="Feed the fish" Time="4/24/2012 12:00:00" />
  <Reminder Title="Walk the dog" Time="5/24/2012 12:00:00" />
  <Reminder Title="Watch LOTR" Time="5/14/2012 12:00:00" />
</Reminders>


2. The DataGrid XAML:


<DataGrid ItemsSource="{Binding Path=Elements[Reminder]}" Name="gv_reminder">
    <DataGrid.Columns>
        <DataGridTextColumn Header="Title" Binding="{Binding Path=Attribute[Title].Value}"/>
        <DataGridTextColumn Header="Time" Binding="{Binding Path=Attribute[Time].Value}" />
</DataGrid>

3. The code behind:

protected void Window_Loaded(object sender, RoutedEventArgs e)
{
    gv_reminder.DataContext = bind_my_datagrid();
}

private XElement bind_my_datagrid()
{
    XElement bind_me = new XElement("Reminders");

    try
        {
            XElement data = XElement.Load(@"C:\your_path\reminder_data.xml");
        }
    catch (Exception ex)
        {
            throw ex;
        }

    return bind_me;
}


Wednesday, February 8, 2012

WPF setting background in C# code

Several ways to do it:

A. Regular brush
your_control.Background = Brushes.Red;


B. New solid brush
your_control.Background = new SolidColorBrush(Colors.Red);


C. HEX color
var bc = new BrushConverter();
your_control.Background = (Brush)bc.ConvertFrom("#FFXX55XX");

Tuesday, February 7, 2012

WPF DateTime control

WPF 4.0 has no default DateTime control, (only DatePicker) which means we need to add it on our own.


I found a very cozy way to do it.
1. Navigate here, download the provided dll and add it to the project (add reference of course).
2. Add to the Window XAML: xmlns:wpfx="http://schemas.microsoft.com/winfx/2006/xaml/presentation/toolkit/extended"
3. Add  <wpfx:DateTimePicker/> where you want your DateTime control to be, modify it with desired preferences.


Wednesday, February 1, 2012

Laptop battery charging problem solved

Had this annoying thing with the power icon on my old Dell Vostro 1500 that showed "12%, plugged in, not charging". Googling the issue didn't have much of help, neither removing the battery - yet I've found a temporary solution.


Seems that your charger is about to die. Meanwhile you can restart the machine and enter the basic menu (F2). In the menu go to the "battery" section, you will see the battery image with percentage and text line "AC adapter is not recognizable". Unplug the power cord and plug back in several time until you'll see the text changed to "AC adapter 90W". If there's still no effect try to flip the power cord it as in a picture below and repeat the plug/unplug procedure - may be some chargers are sensitive to electrical polarity.