Random programming things I'd want to remember
Friday, February 14, 2014
Monday, January 20, 2014
System.Windows.Control.ListBox does not scroll
<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 committedAnd 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
Methods marked as [TestInitialize] and [TestCleanup] not executed, Microsoft.VisualStudio.TestTools.UnitTesting
Monday, January 6, 2014
Karma, Angular.JS "Module is not available!" error
C# display integer in binary format
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
Note to self: Change Foreground in WPF using C#
myTextBox.Foreground = new SolidColorBrush(Colors.White);
Wednesday, December 11, 2013
MVVM Controls inside ListBox (ItemsControl) not firing
//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
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:
- In your App.xaml.cs "Application_UnhandledException" method, check out the error contained in the e argument
- Mine mentioned the error in MeasureOverride method, so more than likely something was wrong with XAML
- 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
IsolatedStorageSettings class
Today I found out that there is an IsolatedStorageSettings class that can simplify storing settings.
Sunday, October 20, 2013
Joining multiple tables in MS Access
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
<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.
<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
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...
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:
- Your class contains the corresponding property, and
- The datatype is one of these (MSDN article) primitive types.
Sunday, September 8, 2013
Separator array in place for string.Split function
.Split(new char[]{';'}, StringSplitOptions.RemoveEmptyEntries)
Thursday, May 9, 2013
Get the info on when user last set his/her password
Anyway, I found a simple solution:
net user USERNAME | find "last set"
And that did the trick.