Author Archives: geoff

Binding a TabItem visibility in XAML

This is a quick demo of how to bind your TabItem visibility so that you can quickly change what’s visible using variable in your viewmodel code.

Create a Converter in a new class file  Converters:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Data;
using System.Windows;

namespace ConfigurationModule.Converters
{
    [ValueConversion(typeof(bool), typeof(Visibility))]
    public class BoolToVisibilityConverter : IValueConverter
    {

        #region IValueConverter Members
    
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (value is bool && targetType == typeof(Visibility))
            {
                bool val = (bool)value;
                if (val)
                    return Visibility.Visible;
                else
                    if (parameter != null && parameter is Visibility)
                        return parameter;
                    else
                        return Visibility.Collapsed;
            }
            throw new ArgumentException("Invalid argument/return type. Expected argument: bool and return type: Visibility");
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (value is Visibility && targetType == typeof(bool))
            {
                Visibility val = (Visibility)value;
                if (val == Visibility.Visible)
                    return true;
                else
                    return false;
            }
            throw new ArgumentException("Invalid argument/return type. Expected argument: Visibility and return type: bool");
        }
        #endregion
    }
}

 
In the XAML header page add:

xmlns:converters="clr-namespace:.Converters"

 
In the XAML Tabcontrol:


 


C# delegates to update the UI from a thread

The Following enables a thread to update the main UI using a delegate.  In this case MyTextBox.Text has an “x” added to its text property.

Application.Current.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Background, new Action(() => this.MyTextBox.Text += "x"));

Apply Changes Made to a Detached Object

This allows changes to be stored based on the original object and changed object:

See:  https://msdn.microsoft.com/en-us/library/vstudio/bb896248%28v=vs.100%29.aspx

private static void ApplyItemUpdates(SalesOrderDetail originalItem,
SalesOrderDetail updatedItem)
{
using (AdventureWorksEntities context =
new AdventureWorksEntities())
{
context.SalesOrderDetails.Attach(updatedItem);
// Check if the ID is 0, if it is the item is new.
// In this case we need to chage the state to Added.
if (updatedItem.SalesOrderDetailID == 0)
{
// Because the ID is generated by the database we do not need to
// set updatedItem.SalesOrderDetailID.
context.ObjectStateManager.ChangeObjectState(updatedItem, System.Data.EntityState.Added);
}
else
{
// If the SalesOrderDetailID is not 0, then the item is not new
// and needs to be updated. Because we already added the
// updated object to the context we need to apply the original values.
// If we attached originalItem to the context
// we would need to apply the current values:
// context.ApplyCurrentValues(“SalesOrderDetails”, updatedItem);
// Applying current or original values, changes the state
// of the attached object to Modified.
context.ApplyOriginalValues(“SalesOrderDetails”, originalItem);
}
context.SaveChanges();
}
}

Adding a PRISMPROP snippet to VS C#

This sets up visual studio to add a snippet that will put in a prism style property really quickly and easily and help set this up fast!

FOLDER:

Documents\Visual Studio xxxx\Code Snippets\Visual C#\My Code Snippets\

FILE: prismprop.snippet

XML:

<?xml version=”1.0″ encoding=”utf-8″ ?>
<CodeSnippets  xmlns=”http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet”>
<CodeSnippet Format=”1.0.0″>
<Header>
<Title>prismprop</Title>
<Shortcut>prismprop</Shortcut>
<Description>Code snippet for property and backing field</Description>
<Author>Microsoft Corporation</Author>
<SnippetTypes>
<SnippetType>Expansion</SnippetType>
</SnippetTypes>
</Header>
<Snippet>
<Declarations>
<Literal>
<ID>type</ID>
<ToolTip>Property type</ToolTip>
<Default>int</Default>
</Literal>
<Literal>
<ID>property</ID>
<ToolTip>Property name</ToolTip>
<Default>Prop</Default>
</Literal>
<Literal>
<ID>field</ID>
<ToolTip>The variable backing this property</ToolTip>
<Default>_myVar</Default>
</Literal>
</Declarations>
<Code Language=”csharp”><![CDATA[private $type$ $field$;

public $type$ $property$
{
get { return $field$;}
set { SetProperty<$type$>(ref $field$, value);}
}
$end$]]>
</Code>
</Snippet>
</CodeSnippet>
</CodeSnippets>

 

SQL Server CATCH block

Just like in Oracle SQL server allows the use of a catch block which can be very useful for debugging stored procedures!

First set up a transaction:

IF @@TRANCOUNT = 0
BEGIN TRANSACTION B4UPDATE
ELSE
SAVE TRANSACTION B4UPDATE

Then catch any errors and rollback if needed saving data about the issue.  If you also keep a variable with a step number you can also output this to an error table giving you the position where the code crunched!

BEGIN CATCH
ROLLBACK TRANSACTION B4UPDATE;
INSERT INTO ERRORS_SQL (TIMESTAMP, PROC_NAME, COMMENTS) VALUES (GETDATE(),‘BADGE_ALLOCATE_USEID’,‘errno: ‘ + ltrim(str(error_number())) + ‘ errmsg: ‘ + error_message())
COMMIT
END CATCH

SQL Server to_char conversion

When converting from oracle to SQL server you may struggle with Oracle to_char() and to_date() convertions.  SQL server handles this differently.  You have to used fixed types or you can use some clever madness.

For YYYYMMDDHH24MISS :

(SELECT REPLACE(REPLACE(REPLACE(CONVERT(VARCHAR(19), CONVERT(DATETIME, getdate(), 112), 126), ‘-‘, ”), ‘T’, ”), ‘:’, ”))

For DD/MM/YYYY HH24:MI:SS :

(select CONVERT(VARCHAR(10), GETDATE(), 103) + ‘ ‘ + convert(VARCHAR(8), GETDATE(), 14))

XAML relative size

How to size components to fit relative to parents in the tree:

Width=”{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Grid}},Path=ActualWidth}”

Height=”{Binding RelativeSource={RelativeSource FindAncestor,AncestorType={x:Type Grid}},Path=ActualHeight}”