Time limit on suspending a WinRT app

by Michael R. Albertin 17. May 2012 07:29

When a WinRT Metro Style app gets suspended, you have to save your user state for the case that the app will be terminated later. 

You have a maximum time limit of 5 seconds to finish your work. After this time the app is closed without any further actions.
First tell the system, that you want to do something with the SuspendingOperation GetDeferral-Method. After your save actions, finish your work with Complete.

/// <summary>
/// Invoked when application execution is being suspended.  Application state is saved
/// without knowing whether the application will be terminated or resumed with the contents
/// of memory still intact.
/// </summary>
/// <param name="sender">The source of the suspend request.</param>
/// <param name="e">Details about the suspend request.</param>
async void OnSuspending(object sender, SuspendingEventArgs e)
{
            var waitState = e.SuspendingOperation.GetDeferral();

            Debug.WriteLine("<------------ Persist Data");
            await DoMyPersistLocalSettings(); 
            await DoMyPersistLocalCache<DataModel>();
            Debug.WriteLine("Persist Data ------------>");

            waitState.Complete();
}

 

Warning: Even on debugging the 5 second time limit is enabled. Don't wait here or step manually through your lines of code.

"Payload file does not exist" compile error

by Michael R. Albertin 8. April 2012 18:36

If you write a Windows Metro Style App in Visual Studio 11 Beta and references directly a self written UserControl-DLL you may get the following error:

"Payload file [xyz] does not exist" compile error

 

--> This is a bug.

 

To workaround this, go to the DLL output folder (e.g. bin\Release), create a new folder named like your DLL-Name (e.g. MyUserControlLibrary) and move the XAML files down to this folder.

bin\Release

  MyUserControlLibrary.dll

  MyUserControlLibrary.pri

  \MyUserControlLibrary [folder] <-- create

       UserControl1.xaml <-- move here

       UserControl2.xaml <-- move here

  

Sources:

http://social.msdn.microsoft.com/Forums/en-US/winappswithcsharp/thread/51111470-8a86-44d4-acb8-e268afa7564e

http://social.msdn.microsoft.com/Forums/en-US/winappswithcsharp/thread/b20ca4a5-8293-4da7-859e-6759a2a76f9d

String-Resources in WinRT (.RESW)

by Michael R. Albertin 11. March 2012 16:51

1) Create a Resource file (Resources.resw) in your project.


2) Add Keys and Values
key1 => Value for Key Nr. 1
key2.Text => Value for Key Nr. 2 and Property Text

 

3) Access the resources 

Use String-Resources from Code

var rl = new ResourceLoader();
var value1 = rl.GetString("key1");

 

Use String-Resources in XAML

<TextBlock x:Uid="key2" Text="Default Text" />

 

4) Support for different languages

Add a Resource-Folder (e.g. "strings")

Add Folders for each language (e.g. "en", "de", "it")

Add a Resources.resw-File into this folders

 

5) Multiple Files

To access strings from the file Errors.resw use this

new ResourceLoader("Errors")

and

<TextBlock x:Uid="/Errors/key2" Text="Default Text" />

 

6) Resources in DLL-Projects

If you want to use a DLL project specific Resources.resw you must specify this

var rl = new ResourceLoader("Dll.Project.Namespace/Resources);

"Dll.Project.Namespace" must be replaced with the real DLL namespace.

 

 

 

MessageBox for WinRT

by Michael R. Albertin 8. March 2012 20:25
Simple Messagebox ....
public async void ShowMessage(string message)
{
   MessageDialog msg= new MessageDialog(message);
   await msg.ShowAsync();
}
A more complex example from Corrado's BLogs  
private  async void OnMessage(object sender, RoutedEventArgs e)
{
   MessageDialog dialog = new MessageDialog("Hello WinRT");
   UICommandInvokedHandler cmdHandler = new UICommandInvokedHandler(cmd =>
   {
      Debug.WriteLine("id:{0} label:{1}", cmd.Id, cmd.Label);
   });

   UICommand cmd1 = new UICommand("Cmd1", cmdHandler, 1);
   UICommand cmd2 = new UICommand("Cmd2", cmdHandler, 2);
   UICommand cmd3 = new UICommand("Cmd3", (cmd) =>
   {
      Debug.WriteLine("Command3 done!");
   }, 3);

   dialog.Commands.Add(cmd1);
   dialog.Commands.Add(cmd2);
   dialog.Commands.Add(cmd3);
   dialog.DefaultCommandIndex = 1;

   await dialog.ShowAsync();
   Debug.WriteLine("Dialog closed");
}

Free WYSIWYG rich text editor including printing, print preview and full table support for Visual Studio

by Michael R. Albertin 11. January 2012 22:11

TX Text Control Express - free, professional rich text editing

Upgrade your Microsoft Visual Studio toolbox with a true WYSIWYG rich text editor including printing, print preview and full table support.

Available for Windows Forms, TX Text Control Express is the free edition of TX Text Control - the market leading word processing component.

  • Integrate a professional WYSIWYG rich text editor into your applications.
  • Replace the standard .NET Framework RichTextBox.
  • Add ready-to-use toolbars and dialogs out of the box.
  • Load, save and print RTF and HTML documents.
  • Developed in sync with the Professional and Enterprise editions.
  • Completely free of charge (no royalties, no expiry date).

http://www.textcontrol.com/en_US/sites/tx-text-control-express/

Scrollable TextBox for Windows Phone

by Michael R. Albertin 2. January 2012 18:52

The TextBox control does not support scrolling in the non-edit mode.

If needed, there is the simple way:
http://forums.create.msdn.com/forums/p/69286/430208.aspx

Or you can create your own ControlTemplate and do something like this:

 

<ControlTemplate x:Key="ScrollableTextBox" TargetType="TextBox">
	<Grid Background="Transparent">
		<VisualStateManager.VisualStateGroups>
[...]
			<VisualStateGroup x:Name="FocusStates">
				<VisualState x:Name="Focused">
					<Storyboard>
[...]
						<ObjectAnimationUsingKeyFrames Storyboard.TargetName="EnabledBorderScroll" Storyboard.TargetProperty="VerticalScrollBarVisibility">
							<DiscreteObjectKeyFrame KeyTime="0">
								<DiscreteObjectKeyFrame.Value>
									<ScrollBarVisibility>Disabled</ScrollBarVisibility>
								</DiscreteObjectKeyFrame.Value>
							</DiscreteObjectKeyFrame>
						</ObjectAnimationUsingKeyFrames>
					</Storyboard>
				</VisualState>
			</VisualStateGroup>
		</VisualStateManager.VisualStateGroups>
		<Border x:Name="EnabledBorder" Background="{TemplateBinding Background}" BorderThickness="{TemplateBinding BorderThickness}" BorderBrush="{TemplateBinding BorderBrush}" Margin="{StaticResource PhoneTouchTargetOverhang}">
			<ScrollViewer x:Name="EnabledBorderScroll" HorizontalScrollBarVisibility="Disabled" VerticalScrollBarVisibility="Auto">
				<ContentControl x:Name="ContentElement" BorderThickness="0" Padding="{TemplateBinding Padding}" 
				HorizontalContentAlignment="Stretch" VerticalContentAlignment="Stretch" Margin="{StaticResource PhoneTextBoxInnerMargin}"/>
			</ScrollViewer>
		</Border>
		<Border x:Name="DisabledOrReadonlyBorder" Visibility="Collapsed" Background="Transparent" BorderBrush="{StaticResource PhoneDisabledBrush}" BorderThickness="{TemplateBinding BorderThickness}" Margin="{StaticResource PhoneTouchTargetOverhang}" >
			<TextBox x:Name="DisabledOrReadonlyContent" Text="{TemplateBinding Text}" Foreground="{StaticResource PhoneDisabledBrush}" Background="Transparent"
				SelectionBackground="{TemplateBinding SelectionBackground}" SelectionForeground="{TemplateBinding SelectionForeground}"
				TextWrapping="{TemplateBinding TextWrapping}" TextAlignment="{TemplateBinding TextAlignment}" IsReadOnly="True" Template="{StaticResource PhoneDisabledTextBoxTemplate}"
				FontFamily="{TemplateBinding FontFamily}" FontSize="{TemplateBinding FontSize}" FontWeight="{TemplateBinding FontWeight}" FontStyle="{TemplateBinding FontStyle}" />
		</Border>
	</Grid>
</ControlTemplate>

Free Photo Libraries

by Michael R. Albertin 16. November 2011 21:18

Mouse without Borders

by Michael R. Albertin 16. November 2011 20:38

Mouse Without Borders is a project I’ve been familiar with for the last 6 months or so and it’s a wonderfully useful tool. In a nutshell, it allows you to reach across your PC's as if they were part of one single desktop. I have two PCs on my desk at work connected to 3 LCD screens and using Mouse Without Borders I can move my mouse between the 3 screens, even though one of them is attached to a different PC from the other two. What’s more, I can move files between the 2 computers simply by dragging them from one desktop to another. In fact you can control up to four computers from a single mouse and keyboard with no extra hardware needed – it’s all software magic, developed by Truong Do who by day is a developed for Microsoft Dynamics. The software is easy to setup and in addition to enabling drag and drop of files, you can lock or log in to all PCs from one PC, and as a whimsical bonus is it allows you to customize your Windows logo screen with the daily image from Bing or a local collection of pictures :) I regularly use it to have one PC dedicated to social media streams while I work away on my other PC connected to two screens.

Read the full blog at blogs.technet.com

 

 

Tags:

Tools

Visual Studio Project Linker

by Michael R. Albertin 14. November 2011 19:22

This tool helps to automatically create and maintain links from a source project to a target project to share code that is common to Silverlight and WPF. Therefore, shared code can be written once and built for the target environment.

http://visualstudiogallery.msdn.microsoft.com/en-us/5e730577-d11c-4f2e-8e2b-cbb87f76c044

‘Cannot register duplicate name ‘XXX’ in this scope’ in VS 2010

by Michael R. Albertin 22. October 2011 19:52

If you have the problem, that Visual Studio 2010 complains ‘Cannot register duplicate name ‘XXX’ in this scope’, check if you have Resources with a x:Name insted of x:Key-Name:

<SolidColorBrush x:Name="NonWorkingResourceName" Color="Red" />
<SolidColorBrush x:Key="WorkingResourceName" Color="Blue" />

Replace x:Name with x:Key and everything is ok.

Read the full post here ...

Shop für Workshop-Material

by Michael R. Albertin 13. October 2011 07:42

Produkte für lebendiges Lernen, Material für Workshops etc.

http://www.neuland.ch/?$countryItem=ox6dx4fra2a

Windows Phone Application Bar Icons

by Michael R. Albertin 14. September 2011 19:17

Caliburn.Micro – Introduction

by Michael R. Albertin 9. September 2011 08:14

Caliburn.Micro – Introduction

Caliburn.Micro is a lightweight and small, yet powerful framework for developing rich WPF, Silverlight or Windows Phone applications. Caliburn.Micro has only a single dependency to the System.Windows.Interactivity library. Due to its small footprint of only 75 k and approximately 2700 lines of code it is not only lightning fast in startup and execution time but also easy to understand. The framework offers pattern guidance for the following well established design patterns:

  • Model – View – ViewModel (MVVM)
  • Model – View – Presenter (MVP)
  • Model – View – Controller (MVC)

Rob Eisenberg (www.robeisenberg.com) and Marco Amendola (marcoamendola.wordpress.com) are actively maintaining the project and taking care of the documentation. The documentation is really thorough and offers tips and tricks how to avoid the common pitfalls. The project is released under a developer and company friendly license namely the MIT License.

http://www.bbv.ch/?p=450&option=com_wordpress&Itemid=173

Favicon-Generator with many Options

by Michael R. Albertin 3. August 2011 10:01

This Website provides a very nice Favicon-Generator with many Options like adding different Image-Sizes.

http://favicon.htmlkit.com/favicon/

Change Database-Table Collations

by Michael R. Albertin 24. June 2011 09:57

To change the Database Table Collations dynamically, you can generate update scripts with the following snippet

declare  @toCollation sysname 
      
SET    @toCollation = 'Latin1_General_100_CI_AS' --  << insert your destination collation name

SELECT 'ALTER TABLE ' + INFORMATION_SCHEMA.COLUMNS.TABLE_NAME +
       '   ALTER COLUMN ' + COLUMN_NAME + ' ' + DATA_TYPE +
       CASE WHEN CHARACTER_MAXIMUM_LENGTH = -1 then '(max)'
            WHEN DATA_TYPE in ('text','ntext') then ''
            WHEN CHARACTER_MAXIMUM_LENGTH IS NOT NULL 
             THEN '('+(CONVERT(VARCHAR,CHARACTER_MAXIMUM_LENGTH)+')' )
            ELSE isnull(CONVERT(VARCHAR,CHARACTER_MAXIMUM_LENGTH),' ') END
       +' COLLATE ' + @toCollation+ ' ' + CASE IS_NULLABLE
                                           WHEN 'YES' THEN 'NULL'
                                           WHEN 'No' THEN 'NOT NULL' 

END
FROM INFORMATION_SCHEMA.COLUMNS INNER JOIN INFORMATION_SCHEMA.TABLES
ON  INFORMATION_SCHEMA.COLUMNS.TABLE_NAME = INFORMATION_SCHEMA.TABLES.TABLE_NAME
AND INFORMATION_SCHEMA.COLUMNS.TABLE_SCHEMA  = INFORMATION_SCHEMA.TABLES.TABLE_SCHEMA
WHERE DATA_TYPE IN ('varchar' ,'char','nvarchar','nchar','text','ntext')
AND TABLE_TYPE = 'BASE TABLE'
and COLLATION_NAME <> @toCollation

Tags:

SQL

Map existing SQL Server Login to an existing Database User

by Michael R. Albertin 24. June 2011 09:55

The following statement maps an existing SQL Server Login to an existing Database User

EXEC sp_change_users_login 'update_one', 'loginName', 'dbUserName'

 

Tags: ,

SQL

Solution: It takes much longer to run a stored procedure than run the code inside the stored procedure

by Michael R. Albertin 17. May 2011 10:50
If you have the problem that a stored procedure takes much longer to execute than the exactly same code direct on the MS SQL Server Management Studio, consider the possibility of side-effects from "Parameter Sniffing".
 
Example:
CREATE Procedure [dbo].[SlowExcecution]
@MyParam NVARCHAR(50)
AS

SELECT * FROM XYZ WHERE A = @MyParam
GO
 
If this code runs fast without SP, but slow as SP, then add a new local variable and copy the parameter into this variable. Then use this variable instead of the parameter.
CREATE Procedure [dbo].[FastExcecution]
@MyParam NVARCHAR(50)
AS

DECLARE @MyLocalVariable NVARCHAR(50)
@MyLocalVariable = @MyParam

SELECT * FROM XYZ WHERE A = @MyLocalVariable
GO
 
For details and background informations take a look at this great blog ....

Shake Gestures Library – A Windows Phone Recipe

by Michael R. Albertin 15. May 2011 01:06

Windows Phone 7 Gestures Cheat Sheet

by Michael R. Albertin 5. May 2011 01:16

Custom Ringtone on WP7

by Michael R. Albertin 22. March 2011 23:46

With the ChevronWP7 custom ringtone manager you can upload your own ringtones to your WP7 device.
Just start the tool, select your sound files and generate a XAP-File. The deploy this to your phone and start it on the phone.
Now your ring tone is available on the settings.

http://thetechjournal.com/electronics/mobile/chevronwp7-ringtone-installer-has-releasedhow-to.xhtml

Righthand Dataset Debugger Visualizer

by Michael R. Albertin 10. March 2011 21:34

RightHand.DataSet.Visualizer is an MDI application that lets you inspect DataSet structure and its data plus tons of other useful operations on DataSet.

http://blog.rthand.com/page/Righthand-Dataset-Debugger-Visualizer.aspx

http://blog.rthand.com/post/2011/01/08/Righthand-DataSet-Visualizer-goes-10.aspx

TSQL: Create Matix from Details Table with Pivot

by Michael R. Albertin 10. March 2011 09:41

Tutorial to create a matrix in TSQL from a table containing detail values:
http://www.tsqltutorials.com/pivot.php

Tags: ,

SQL

Customizing WP7 Push Notification Tiles

by Michael R. Albertin 7. March 2011 23:22

Virtualizing Data in Windows Phone 7 Silverlight Applications

by Michael R. Albertin 7. March 2011 23:11

Advanced PhoneHyperlinkButton

by Michael R. Albertin 7. March 2011 23:09

PhoneHyperlinkButton updated: now supports web, email, text and phone call tasks

http://www.jeff.wilcox.name/2010/12/updated-phone-hyperlink-button/

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

© Copyright 2012 Syntax Error