Random programming things I'd want to remember

Friday, February 14, 2014

JavaScript: convert milliseconds to a date

Pretty easy, as it turns out:
  var dt = new Date(milliseconds);


And then one can use the standard Date methods available here. JSFiddle.

Monday, January 20, 2014

System.Windows.Control.ListBox does not scroll

An interesting one today. My ListBox would not scroll, and after looking into all usual suspects it still would not work. Turns out that the offender was the Grid, containing the ListBox. Here is XAML:
        <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
            <Grid.RowDefinitions>
                <RowDefinition Height="Auto" />
                <RowDefinition Height="Auto" />
            </Grid.RowDefinitions>
            <StackPanel Orientation="Horizontal">
                ...
            </StackPanel>            
           
            <ListBox ItemsSource="{Binding}" Grid.Row="1">
                <ListBox.ItemTemplate>
                    <DataTemplate>
                        <TextBlock Text="{Binding Description}" />
                    </DataTemplate>
                </ListBox.ItemTemplate>
            </ListBox>
        </Grid>

My ListBox has a bunch of items and it does not scroll, even though there is no StackPanel in the DataTemplate. But, if I change the RowDefinition on the second row to say
                <RowDefinition Height="*" />

Then it scrolls just fine.

Friday, January 10, 2014

Initial git setup for a local project

Git is a great version control system available for free for private use. It is easy and very efficient. There is a short free book that explains the basics. Here is my short take on how to set up a git project locally (assuming that Git is already installed in the system.)

Open up the command shell and navigate to the root folder of the project. Then, issue the following commands (all comments come after the "#" mark):

  git init #initialize a git repository here
  notepad .git/info/exclude #optional step, here you can exclude files or folders that need no tracking
  #notepad will open with the document where you can type in values. 
  #If nothing needs to be excluded, just close the file.
  #to exclude a folder, mark it as so: bin/
  #to exclude all files with extension "sap", type in *sap
  git add . #to add all files recursively
  git status #(optional)see the files that will be committed.
  git commit -m "initial version" #commit with message "initial version"
  git log #check what's committed



Update from Feb 28, 2014: Here is another way to set up git locally, the difference between the script above is that the excluded files will be tracked by ".gitignore" file rather than "exclude" file. For sample of .gitignore files, check out this GitHub repository: github/gitignore, there are plenty of examples there for all kinds of programming projects. Here is the script:

  git init #initialize a git repository here, make sure you have a .gitignore file in the root folder of your project
  git add .gitignore #(optional)create or add a file that specifies which file(types) and/or folders to ignore
  git commit -m "Added .gitignore" #optional if you did not add .gitignore file
  git add . #to add all files recursively
  git status #(optional) see the files that will be committed.
  git commit -m "initial version" #commit with message "initial version"
  git log #check what's committed

And the first commit is done. It's that easy. To utilize tags, branching/merging, and other features of git that make it so good, read the book. The next logical step for the local repository is to create a distributed repository online and upload your code there. Bitbucket or GitHub are a places to start looking around.


Thursday, January 9, 2014

Monday, January 6, 2014

Karma, Angular.JS "Module is not available!" error

I was troubleshooting "Module '{0}' is not available!" error while testing an Angular.js app with karma and it got me puzzled quite a bit. Worst of all -- Google was not helpful (which clearly indicated that the problem is at my end). This url: http://docs.angularjs.org/error/$injector:nomod did not help either. My problem was that I forgot to include my controller js file into the files: [] array in karma configuration. Doh!

C# display integer in binary format

I was trying to understand an algorithm in this post here and it helped to visualize integers in binary format. A bit of Googling showed exactly how to do that:
    Convert.ToString(value, 2);

Monday, December 23, 2013

Draw a dot on HTML canvas

A helpful way to debug HTML canvas while doing a lot of translations, transformations, and so on.

      context.fillRect(0, 0, 2, 2);

This line prints a tiny rectangle at the point of zero coordinates.

Tuesday, December 17, 2013

Wednesday, December 11, 2013

MVVM Controls inside ListBox (ItemsControl) not firing

Scenario: you built an app using something that more or less closely resembles the MVVM approach that I described earlier, and you have a data control with a nested control that must execute some command. Here is how it might look:

//YourViewModel.cs:
private DelegateCommand yourCommand;

public YourPageConstructor()
{
  yourCommand = new DelegateCommand(this.YourMethod);
  ...
}

private void YourMethod(object obj)
{
  ...//do something here
}

public ICommand YourCommand { get { return yourCommand; } }

//yourPage.xaml.cs:
public yourPage()
{
  InitializeComponent();
  this.DataContext = new YourViewModel();
}

//yourPage.xaml:
<ListBox x:Name="yourDataControl" ...>
  <ListBox.ItemTemplate>
    <DataTemplate>
      <StackPanel>
        <Button Command="{Binding YourCommand}" Content="YourItems" ... />
      </StackPanel>
    </DataTemplate>
  </ListBox.ItemTemplate>
</ListBox>



You go to test your page, but your command is not firing. When you set a breakpoint at the "public ICommand YourCommand ..." line, you see that it is not being hit when the page loads. What's happening?

The thing is, your command should be a part of the collection that the ListBox is bound to for the ListBox to see (and execute it). Your command lives in your ViewModel, while the ListBox is bound to a collection. What to do? Bind your command in the following way:

//yourPage.xaml, add an x:Name attribute to the content of the opening PhoneApplicationPage tag:
<phone:PhoneApplicationPage
    x:Class="YourProjectName.Views.yourPage"
    x:Name="nameYourXAMLPageName"
    ...>

//and then change the Button's binding:
<ListBox x:Name="yourDataControl" ...>
  <ListBox.ItemTemplate>
    <DataTemplate>
      <StackPanel>
        <Button Command="{Binding ElementName=nameYourXAMLPageName, Path=DataContext.YourCommand}"
                   Content="{Binding YourItems}" ... />
     </StackPanel>
    </DataTemplate>
  </ListBox.ItemTemplate>
</ListBox>
...


This way, we are not embedding the command into the collection bound to ListBox, but rather, let the ListBox know where to find the command by providing the "address" of the current page's DataContext.


As usual, leave your thoughts in comments.

Monday, December 9, 2013

Today I learned: Unit testing using Visual Studio Express for Windows Phone

Visual Studio Express 2012 for Windows Phone has built-in support for Unit Testing. Here is the article on MSDN. Here is how to set it up (quickly). VS has to have at least update 2, and all you need to do is to add another project to your solution, choose "Windows Phone Unit Test App". Then write your unit tests and run them using the "TEST" menu on the top bar.

Now if only they allowed access to visualstudio.com for Windows Phone projects or made VS 2013 for Windows Phone available for download.

Wednesday, November 27, 2013

Error HRESULT E_FAIL has been returned from a call to a COM component error on Windows Phone


Summary:

  1. In your App.xaml.cs "Application_UnhandledException" method, check out the error contained in the e argument
  2. Mine mentioned the error in MeasureOverride method, so more than likely something was wrong with XAML
  3. My error happened because I 1) misspelled converter key and 2) declared converter as a resource after the declaration for the DataTemplate that used it

Long version:

I am working on a Windows Phone app. Many developers face this: you code, everything works fine. Then you change a couple of things and boom! you get a cryptic error message. In my case, the phone app kept hitting this code without no apparent reason:

        private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
        {
            if (System.Diagnostics.Debugger.IsAttached)
            {
                // An unhandled exception has occurred; break into the debugger
                System.Diagnostics.Debugger.Break();
            }
        }

I hovered my mouse cursor over the e argument of the method, and I got the following information:

MS.Internal.WrappedException: Error HRESULT E_FAIL has been returned from a call to a COM component. ---> System.Exception: Error HRESULT E_FAIL has been returned from a call to a COM component.
   at MS.Internal.XcpImports.CheckHResult(UInt32 hr)
   at MS.Internal.XcpImports.UIElement_Measure_WithDesiredSize(UIElement element, Size availableSize)
   at System.Windows.UIElement.Measure_WithDesiredSize(Size availableSize)
   at System.Windows.Controls.VirtualizingStackPanel.MeasureChild(UIElement child, Size layoutSlotSize)
   at System.Windows.Controls.VirtualizingStackPanel.MeasureOverride(Size constraint)
   at System.Windows.FrameworkElement.MeasureOverride(IntPtr nativeTarget, Double inWidth, Double inHeight, Double& outWidth, Double& outHeight)
   --- End of inner exception stack trace ---}

After a closer look, I noticed that the code mentions MeasureOverride method. I immediately turned to my last XAML document that I edited. Lo and behold, one of the lines was highlighted blue. I added a Converter to one of the values, and I misspelled the Key parameter inside the element. I fixed the typo and voila! same error. Here is an important detail about my scenario: I have a page with resources. I use a converter within a DataTemplate resource declaration. I also declared my local converter resource after the DataTemplate (that uses it). My error kept occuring (now) because I use a resource before I declared it. I changed my page to the following (just an idea):


<phone:PhoneApplicationPage.Resources>
  <local:myConverter x:Key="...
  <DataTemplate x:Key="...
    ...
  </DataTemplate
</phone:PhoneApplicationPage.Resources>

And everything started working.

Tuesday, November 26, 2013

Sunday, October 20, 2013

Joining multiple tables in MS Access

The syntax is tricky and I do it every once in a while and look it up every time (because the SQL errors in MS Access are far from being user-friendly). This site here has the general idea. But the details are below:

SELECT a.AField, b.BField, c.CField
FROM TableA AS a INNER JOIN (TableB AS b INNER JOIN TableC AS c ON b.BKey = c.BForeignKey)
ON a.AKey = b.BForeignKey

And, by the way:

TableB AS b INNER JOIN TableC AS c ON b.BKey = c.BForeignKey AND b.BField2 = 'someValue' AND c.CField2 = 'someValue'

join condition is not supported in Access, you have to put the join by some value in the table condition into the WHERE clause:

TableB AS b INNER JOIN TableC AS c ON b.BKey = c.BForeignKey 
...
WHERE b.BField2 = 'someValue' AND c.CField2 = 'someValue'


Saturday, October 19, 2013

Implementing your own keyboard on Windows Phone using MVVM pattern

In my previous article on MVVM pattern in Windows phone, I explained the entire model. Today, I will explain the usage of same pattern on Windows Phone in simpler terms. I will show how to implement a bunch of buttons (which can be repurposed for keyboard) on Windows Phone using MVVM. Let's start with a view:

    <Grid x:Name="LayoutRoot" Background="Transparent">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
        </Grid.RowDefinitions>
        
        <TextBlock Text="{Binding MyText}" />

        <ItemsControl ItemsSource="{Binding MyButtons}" HorizontalAlignment="Center" Padding="0" Grid.Row="1"
                              Style="{StaticResource HorizontalStackPanel}" />

    </Grid>

Quite a standard phone page, the first row contains the property we will be changing through the buttons that we create. The second row contains the ItemsControl that will display the collection of newly-created buttons.

What is non-standard about it is the style definiton for ItemsControl (HorizontalStackPanel). The reason for it is that by default, ItemsControl lays out its children in vertical fashion. But if you add the following code into App.xaml file in <Application.Resources> block, your items will be laid out horizontally:

        <Style x:Key="HorizontalStackPanel" TargetType="ItemsControl">
            <Setter Property="ItemsPanel">
                <Setter.Value>
                    <ItemsPanelTemplate>
                        <StackPanel Orientation="Horizontal" />
                    </ItemsPanelTemplate>
                </Setter.Value>
            </Setter>
        </Style>

Now let's get to the code-behind page, pretty easy too:

public MainPage()
{
    InitializeComponent();
    this.DataContext = new ButtonsViewModel();
}

And now let's get to the ButtonsViewModel. First, implementing the MyText property in accordance with MVVM:

        private string _myText;
        public string MyText
        {
            get { return _myText; }
            set
            {
                if (_myText == value)
                    return;
                _myText = value;
                this.RaisePropertyChanged("MyText");
            }
        }

Then, implementing the plumbing for INotifyPropertyChanged interface:
//INotifyPropertyChanged implementation
        public event PropertyChangedEventHandler PropertyChanged;
        public void RaisePropertyChanged(string propertyName)
        {
            PropertyChangedEventHandler handler = this.PropertyChanged;
            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(propertyName));
            }
        }

And here we implement the MyButtons property by creating a list of Buttons and adding Buttons one-by-one:

//Buttons property
        public List<Button> MyButtons
        {
            get
            {
                List<Button> buttons = new List<Button>();
                buttons.Add(MakeAButton("q");
                buttons.Add(MakeAButton("w");
                buttons.Add(MakeAButton("e");
                buttons.Add(MakeAButton("r");
                buttons.Add(MakeAButton("s");
                return buttons;
            }
        }
//Button plumbing
        private Button MakeAButton(string letter)
        {
            Button b = new Button
            {
                CommandParameter = letter,
                Content =  new TextBlock { Text = letter, FontSize = 24, FontFamily = new System.Windows.Media.FontFamily("Segoe UI Mono") },
                Height=80
            };
            b.Click += b_Click; 
            return b;
        }
//The magic
        void b_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            string a = (sender as Button).CommandParameter.ToString();
            SomeText += a;
        }

This example is not a classic MVVM implementation, it uses the Button Click event to alter the value of the MyText property. The classic implementation would be to use ICommand, but I chose not to do it here because this is a quick and easy example. Hopefully it can provide the feel for MVVM for those who are trying to understand the pattern.

A word of caution: if you need to fit a lot of buttons on the same row, you will be better off adjusting Margin property on each button.

Friday, October 11, 2013

Dealing with "Nested types are not supported" message while working on WPF styles.

I am working on implementing an interface with many buttons on Windows Phone. First thing I learned (the hard way) is that the StackPanel does not support adding controls to it dynamically. Oh well, ItemsControl to the rescue. The tricky part about the ItemsControl is that it lays out its children vertically by default. I did some customizations to help that:

<ItemsControl ItemsSource="{Binding MyProperty}" HorizontalAlignment="Center" Padding="0">  
  <ItemsControl.ItemsPanel>
    <ItemsPanelTemplate>
      <StackPanel Orientation="Horizontal" />
    </ItemsPanelTemplate>
  </ItemsControl.ItemsPanel>
</ItemsControl>


All nice and pretty but my interface involves multiple rows of items. Naturally, I can use styles to help me with that! So I open up App.xaml and I start typing:

<Style x:Key="HorizontalStackPanel" TargetType="ItemsControl">
  <Setter Property="Padding" Value="0" />
    <Setter Property="ItemsPanel" Value=...


And this is where I got lost a bit, because the style does not accept nested definitions. Luckily, MSDN has a great example here. This is what I ended up writing:

<Style x:Key="HorizontalStackPanel" TargetType="ItemsControl">
  <Setter Property="ItemsPanel">
    <Setter.Value>
      <ItemsPanelTemplate>
        <StackPanel Orientation="Horizontal"
                    VerticalAlignment="Center"
                    HorizontalAlignment="Center" />
      </ItemsPanelTemplate>
    </Setter.Value>
  </Setter>
</Style>


And everything is working just fine. So this is how anyone can deal with the "Nested types are not supported" message while setting their styles in a somewhat complex way.


Wednesday, September 18, 2013

Efficient way to save lists to IsolatedStorage

I am working on a Windows 8 project and I needed a long list of strings in the isolated storage. I used this code:
for(int i=0;i<myList.Count;i++)
  await FileIO.AppendTextAsync(myFileName, myList[i]);

The method is of course marked as async, so when my debugger skipped over that line and nothing happened, I though something was wrong with Visual Studio. Then I set the debugger at my AppendTextAsync line and when it stopped, I realized that it was taking forever for the computer to append the items from my list, one-by-one (there were more than ten thousand items, and my computer is not the slowest one out there.

I recently read the book by Marijn Haverbeke called Eloquent JavaScript, which has a pretty heavy (well, in my mind) emphasis on functional programming. I remembered that there is a Join method that I could use to convert my list into a string, and I did it like so:

string result = string.Join(Environment.NewLine, myList.ToArray());
and voila! It took a split second.


Windows Powershell: two commands to rule the all! Well, almost all...

I borrowed a book on Powershell from Amazon, it was short and easy to read, but I only remember two commands from the book: Get-Command and Get-Help. Get-Command lists all available commands and Get-Help can tell everything about that command. If I know that I need to get something, but not sure about the command itself, I can type the following into my PowerShell window: "Get-Command -Verb Get". And if I forget how to use Get-Command, I can always type "Get-Help Get-Command". So I only need to remember one command, Get-Help!

Thursday, September 12, 2013

Entity Framework ignores some fields when pulling data


Let's say I have a class:
public class Bookshelf
{
    public int BookshelfID {get;set;}
    public List<string>BookNames {get;set;}
}

and it corresponds to a table named Bookshelves
CREATE TABLE [dbo].[Bookshelves] (
     BookshelfID INT IDENTITY (1,1) NOT NULL
   , BookNames varchar(MAX)...
   , PRIMARY KEY CLUSTERED ([BookshelfID] ASC)
);

in the database. Let's say we are using Entity Framework (4.0), like so:
public class EFDbContext : DbContext
{
    public DbSet<Bookshelf> Bookshelves {get;set;}
}

When Entity Framework generates the SELECT statement to pull all data from table Books, the resulting SQL will be the following:
    SELECT BookshelfID FROM Bookshelves

totally ignoring the BookNames property. But if you alter the class definition such that the BookNames property is a string, the SQL statement will include BookNames column. I guess Entity Framework only works with basic types and does not trust me with explaining it how to treat the lists. You can use LINQ to Objects to extract whatever you need from BookNames.

The bottom line is: if Entity Framework is ignoring some columns in the table, check two things:
  1. Your class contains the corresponding property, and
  2. The datatype is one of these (MSDN article) primitive types.

Sunday, September 8, 2013

Separator array in place for string.Split function

Here is how to use the .Split function without having to define an array of separator values separately.

.Split(new char[]{';'}, StringSplitOptions.RemoveEmptyEntries)

Thursday, May 9, 2013

Get the info on when user last set his/her password

I needed to find out when user changed password last time and I though I would use PowerShell. There are plenty of examples in Google, but most of them refer to cases when user accounts are controlled by Active Directory. I found some script, and modified it to the extent that I was getting the number of seconds since the last time the password was changed. I learned a lot about PowerShell, too, it is great to have a .Net environment for quick tasks like that without having to compile anything.

Anyway, I found a simple solution:

net user USERNAME | find "last set"

And that did the trick.