Showing posts with label windows. Show all posts
Showing posts with label windows. Show all posts

Monday, June 4, 2012

unable to load the native components of sql server compact corresponding to the ado.net

This is a very stupid exception, which is due to SQL CE has mismatched binaries.

So, just uninstall SQL Server Compact 32 bit (64 bit as well for 64 bit machines) from Add/Remove Programs

Download sql server compact edition and install them.

Thursday, November 10, 2011

When you want to import dll

using System.Runtime.InteropServices;//DLLimport

[DllImport("winmm.dll", SetLastError = true)]

Tuesday, September 20, 2011

How special var is in C#, var can't be the type of property of class C#


var is static typed - the compiler and runtime know the type - they just save you some typing... the following are 100% identical:
var s = "abc";
Console.WriteLine(s.Length);
and
string s = "abc";
Console.WriteLine(s.Length);

Finding an ancestor and children of a WPF dependency object

Below are from : http://www.hardcodet.net/2008/02/find-wpf-parent


This is a simple snippet which helps you to find a specified parent of a given WPF dependency object somewhere in its visual tree:
(Snippet updated 2009.09.14)

/// <summary>
/// Finds a parent of a given item on the visual tree.
/// </summary>
/// <typeparam name="T">The type of the queried item.</typeparam>
/// <param name="child">A direct or indirect child of the
/// queried item.</param>
/// <returns>The first parent item that matches the submitted
/// type parameter. If not matching item can be found, a null
/// reference is being returned.</returns>
public static T TryFindParent<T>(this DependencyObject child)
    where T : DependencyObject
{

Thursday, August 25, 2011

C# Invoke particular EventHandler in InvocationList

I am trying to get particular EventHandler get fired.

Event ProjectChanged was hooked by several EventHandlers


public static event EventHandler ProjectChanged;


foreach (var eventHandler in ProjectChanged.GetInvocationList())
{
    if (eventHandler.Method.Name == "UserContext_ProjectChanged")
    {
        eventHandler.DynamicInvoke(null,null);
    }
}

String to Guid in C#


public static Guid StringToGUID(string value)
{
    // Create a new instance of the MD5CryptoServiceProvider object.
    MD5 md5Hasher = MD5.Create();
    // Convert the input string to a byte array and compute the hash.
    byte[] data = md5Hasher.ComputeHash(Encoding.Default.GetBytes(value));
    return new Guid(data);
}

Wednesday, August 17, 2011

WPF GridViewColumn Width 100 percent

<local:ListViewEx.View>
    <GridView ColumnHeaderContainerStyle="{StaticResource CustomHeaderStyle}">
        <GridViewColumn Header="xxx" 
             Width="{Binding RelativeSource={RelativeSource FindAncestor, 
             AncestorType=ListView}, Path=ActualWidth}">
             <GridViewColumn.CellTemplate>

Monday, June 27, 2011

Icon Render WPF

RenderOptions.BitmapScalingMode="NearestNeighbor"                            RenderOptions.EdgeMode="Aliased"

Sunday, June 26, 2011

Text Trimming and ToolTip bind to itself

TextTrimming="CharacterEllipsis" TextWrapping="Wrap" ToolTip="{Binding Text, RelativeSource={RelativeSource Mode=Self}}

Sunday, June 5, 2011

Friday, May 27, 2011

Cool stuff in .NET 4.0: System.Threading.Tasks.TaskScheduler

private void Save()
{
    System.Threading.Tasks.TaskScheduler uiScheduler = System.Threading.Tasks.TaskScheduler.FromCurrentSynchronizationContext();
    System.Threading.Tasks.Task<ErrorEnum>.Factory.StartNew(() =>
    {
        ErrorEnum callResult = ErrorEnum.OK;
        try
        {
            IsIdle = false;
            callResult = (ErrorEnum)DataContext.DomainRepository.SaveDomain(_domain);
            if (callResult != ErrorEnum.OK)
            {
                // If remote saving fails, rollback all the changes
                Rollback();
            }
            else
            {
                // If remote saving succeeds, save changes to local db
                SaveChangesToLocalDB();
            }
            return callResult;
        }
        catch (Exception ex)
        {
            LogManager.AddCMEventLog("DomainSettingsViewModel.Save", ex);
            // If anything goes wrong, rollback all the changes
            return ErrorEnum.LocalFatalAnonymousError;
        }
        finally
        {
            IsIdle = true;
        }
    }).ContinueWith(task => ShowResult(task.Result), uiScheduler);
}




This running tasks in background thread, then call UI thread to execute the ShowResult() function, Just like UIDispatcher

Thursday, April 14, 2011

Set Window on top of others

The correct way to implement a modal window is by setting  this.Owner = Application.Current.MainWindow; in the XAML, and show the dialog by using DialogName.ShowDialog();

Sunday, March 27, 2011

TextTrimming ToolTip in WPF

<TextBlock Text="{Binding State}" TextTrimming="CharacterEllipsis" Foreground="#6D6D6D"
                                                           ToolTip="{Binding Text, RelativeSource={RelativeSource Mode=Self}}"/>

Wednesday, February 23, 2011

C# Write Access Check

        /// <summary> Checks for write access for the given file.
        /// </summary>
        /// <param name="fileName">The filename.</param>
        /// <returns>true, if write access is allowed, otherwise false</returns>
        public static bool WriteAccess(string dire)
        {

            // Get the access rules of the specified files (user groups and user names that have access to the file)
            var rules = Directory.GetAccessControl(dire).GetAccessRules(true, true, typeof(System.Security.Principal.SecurityIdentifier));

            // Get the identity of the current user and the groups that the user is in.
            var groups = WindowsIdentity.GetCurrent().Groups;
            string sidCurrentUser = WindowsIdentity.GetCurrent().User.Value;

            // Check if writing to the file is explicitly denied for this user or a group the user is in.
            if (rules.OfType<FileSystemAccessRule>().Any(r => (groups.Contains(r.IdentityReference) || r.IdentityReference.Value == sidCurrentUser) && r.AccessControlType == AccessControlType.Deny && (r.FileSystemRights & FileSystemRights.WriteData) == FileSystemRights.WriteData))
                return false;

            // Check if writing is allowed
            return rules.OfType<FileSystemAccessRule>().Any(r => (groups.Contains(r.IdentityReference) || r.IdentityReference.Value == sidCurrentUser) && r.AccessControlType == AccessControlType.Allow && (r.FileSystemRights & FileSystemRights.WriteData) == FileSystemRights.WriteData);
        }

WPF Mouse Cursors busy

Mouse.OverrideCursor = Cursors.Wait;
Mouse.OverrideCursor = null;

Thursday, January 13, 2011

Use the "using" C# key word to build sql connection

While reviewing some C# code written by a newbie programmer and buddy of mine, I noticed a lack of calling Dispose() on SqlConnection and SqlCommand objects. And in all cases, the database code was not placed in try / finally blocks. This is typical newbie style of development that everyone, including myself, attempted in the very beginning.

SqlConnection cn = new SqlConnection(connectionString);
SqlCommand cm = new SqlCommand(commandString, cn);

Thursday, December 30, 2010

Set "Auto" to GridView Colum Width when re-binding data to the GridView

The GridView Colum Width is a headache.

detailView.Columns.OfType<System.Windows.Controls.GridViewColumn>().ToList().ForEach(c => c.Width = c.ActualWidth);
detailView.Columns.OfType<System.Windows.Controls.GridViewColumn>().ToList().ForEach(c => c.Width = Double.NaN);


http://msdn.microsoft.com/en-us/library/system.windows.controls.gridviewcolumn.width.aspx
Double.NaN means auto-size

Wednesday, December 29, 2010

WPF Make a Button invoked by Enter Key, set it as IsDefault=true

In the window, I try to use focus manager to set the button focused to invoke Enter Key, but the focus may lost.

By setting the IsDefault property, problem solved.


public void EnableFinish()
{
    btnNext.Visibility = Visibility.Hidden;
    btnFinish.Visibility = Visibility.Visible;
    btnFinish.IsDefault = true;
}