Featured Post

Organize and rename photos by EXIF data with PowerShell

This PowerShell script organizes and renames all photos in a selected folder using EXIF data. It will also create thumbnails of the images i...

Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Sunday, March 3, 2024

How to fix intellisense in Visual Studio Code

I just added a new project and started making changes but there is no intellisense or syntax highlighting, what is going on?
The solution is simple, you must add the new project to the Solution File (.SLN) for Visual Studio Code to recognize it!
dotnet sln add .\Scraper.UI\
Project `Scraper.UI\Scraper.UI.csproj` added to the solution.
Now, intellisense is working:

Saturday, November 26, 2016

Installing Mono and ASP.NET on Raspberry Pi

sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys 3FA7E0328081BFF6A14DA29AA6A19B38D3D831EF
echo "deb http://download.mono-project.com/repo/debian wheezy main" | sudo tee /etc/apt/sources.list.d/mono-xamarin.list
sudo apt-get update
sudo apt-get upgrade
sudo apt-get install mono-complete
mono --version
To install Mono Develop:
sudo apt-get install monodevelop
sudo apt-get install mono-xsp4

Friday, May 2, 2014

Configure SQL Server IPAll Static Port using C#

Note: You will need to add references for a few Microsoft.SqlServer dll's
        // using Microsoft.SqlServer.Management.Smo.Wmi;
        public static void SetStaticPort(string ServiceName = "MSSQL$SQLEXPRESS", string InstanceName = "SQLEXPRESS", int PortNumber = 2433)
        {
            try
            {
                ManagedComputer c = new ManagedComputer();
                c.ConnectionSettings.ProviderArchitecture = ProviderArchitecture.Use32bit;

                int count = 0;
                foreach (ServerInstance si in c.ServerInstances) { count++; }

                if (count == 0)
                {
                    c = new ManagedComputer();
                    c.ConnectionSettings.ProviderArchitecture = ProviderArchitecture.Use64bit;
                    foreach (ServerInstance si in c.ServerInstances) { count++; }
                }

                if (count == 0) throw new Exception("Unable to locate SQL Instances, Please contact support.");

                Service svc = c.Services[ServiceName];
                var state = svc.ServiceState;
                if (state == ServiceState.Running) svc.Stop();
                ServerInstance s = c.ServerInstances[InstanceName];

                if (null == s) throw new Exception("Unable to locate SQL Service, Please contact support.");

                ServerProtocol prot = s.ServerProtocols["Tcp"];

                foreach (ServerIPAddress ip in prot.IPAddresses)
                {
                    if (ip.Name == "IPAll")
                    {
                        ip.IPAddressProperties["TcpPort"].Value = PortNumber.ToString();
                        ip.IPAddressProperties["TcpDynamicPorts"].Value = String.Empty;
                    }
                }

                prot.Alter();

                svc.Start();
            }
            catch (Exception ex)
            {
                throw;
            }
        }

Thursday, March 13, 2014

Row not found or changed... meet ChangeConflictException handler!

Row not found or changed exceptions are frustrating... until now!

catch (ChangeConflictException cce)
{
    // Where DB is your database context
    foreach (ObjectChangeConflict occ in DB.ChangeConflicts)
    {
        MetaTable metatable = DB.Mapping.GetTable(occ.Object.GetType());
        Debug.WriteLine("\nTable name: " + metatable.TableName);
        foreach (MemberChangeConflict mcc in occ.MemberConflicts)
        {
            Debug.WriteLine("Member: " + mcc.Member);
            Debug.WriteLine("\tCurrent  value: " + mcc.CurrentValue);
            Debug.WriteLine("\tOriginal value: " + mcc.OriginalValue);
            Debug.WriteLine("\tDatabase value: " + mcc.DatabaseValue);
        }
    }
    throw;
}

Friday, December 27, 2013

Change TabControl SelectedTabItem in your ViewModel by TabItem Name or Header Value

Using these simple methods you can change your active tab in your ViewModel via commands or methods. If you want to change to a tab but don't want to have to track the tab index, you simply use the method that accepts the Tab Name or Header string name to change to that tab.

XAML:
<TabControl x:name="MyTabControl">...</TabControl>

Code Behind:
public MyUserControlorViewConstructor()
{
    InitializeComponent();
    
    MyViewModel mvm = new MyViewModel();
    DataContext = mvm;
    
    mvm.MyTabControl = MyTabControl;    
}

ViewModel:
public TabControl MyTabControl { get; set; }

public static void SetSelectedTab(string tabName)
{
    for (int i = 0; i < MyTabControl.Items.Count; i++)
    {
        TabItem item = MyTabControl.Items.GetItemAt(i) as TabItem;
        if (null == item || (item.Name != tabName && item.Header.ToString() != tabName)) continue;  
        MyTabControl.SelectedIndex = i;
        item.IsSelected = true;
        return;
    }
}

public static void SetSelectedTab(int tabIndex)
{
    TabItem item = MyTabControl.Items.GetItemAt(tabIndex) as TabItem;
    if (item == null) return;
    item.IsSelected = true;
    MyTabControl.SelectedIndex = tabIndex;
}

Monday, November 4, 2013

(C#) Friendly names for enums

Enums are quick and easy. Here is how to have a friendly name for your enum value to display on the UI.

public enum CustomEnum
{
    [System.ComponentModel.Description("I am Alpha")]
    Alpha,
    [System.ComponentModel.Description("Beta Friendly Label")]
    Beta
}

public static class EnumHelper
{
    public static string GetEnumDescription(Enum value)
    {
        System.Reflection.FieldInfo fi = value.GetType().GetField(value.ToString());

        System.ComponentModel.DescriptionAttribute[] attributes =
            (System.ComponentModel.DescriptionAttribute[])fi.GetCustomAttributes(
            typeof(System.ComponentModel.DescriptionAttribute),
            false);

        if (attributes != null &&
            attributes.Length > 0)
        {
            return attributes[0].Description;
        }
        else
        {
            return value.ToString();
        }
    }
}

Usage:
MessageBox.Show(EnumHelper.GetEnumDescription(CustomEnum.Alpha));

Tuesday, October 29, 2013

BackgroundWorker Example for C#/WPF

Here is a simple example of how to use a BackgroundWorker to execute long running tasks without freezing the UI. This allows you to use ProgressChanged event handler to change your UI with status messages making for a much friendlier user experience.

In this example I am creating and populating a database which takes a minute or so to complete. With my Simple Elegant Busy Indicator for WPF bound to the BusyIndicator property, it lets the user know the application is busy and not frozen.


private void Execute()
{
    // Set status
    BusyIndicator = true;
    Status = "Creating database, please wait. This may take several minutes...";

    // Create Database background worker
    CreateDatabaseWorker = new BackgroundWorker();
    CreateDatabaseWorker.WorkerReportsProgress = true;
    CreateDatabaseWorker.DoWork += new DoWorkEventHandler(CreateDatabase_DoWork);
    CreateDatabaseWorker.ProgressChanged += new ProgressChangedEventHandler(CreateDatabase_WorkerProgressChanged);
    CreateDatabaseWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(CreateDatabase_WorkCompleted);
    CreateDatabaseWorker.RunWorkerAsync();
}

// Note: You cannot modify any UI bound property in the _DoWork method
private void CreateDatabase_DoWork(object sender, DoWorkEventArgs e)
{
    try
    {
        // Long running methods go here
        CreateDatabaseWorker.ReportProgress(25, "Creating employees...");
        Utilities.PopulateDBModel.CreateInitialEmployees();

        CreateDatabaseWorker.ReportProgress(50, "Creating countries and regions...");
        Utilities.PopulateDBModel.CreateCountries();
    }
    catch (Exception ex)
    {
        // If anything fails we set our result to false
        CreateDatabaseWorker.ReportProgress(100, "Error...");
        e.Result = false;
        return;
    }
    e.Result = true;
}

// This will update our UI while our background worker is... working
private void CreateDatabase_WorkerProgressChanged(object sender, ProgressChangedEventArgs e)
{
    if (e.UserState != null)
    {
        ProgressBarValue = e.ProgressPercentage;
        Status = e.UserState.ToString();
    }
}

// Now we can evaluate our results
private void CreateDatabase_WorkCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    BusyIndicator = false;

    if ((bool)e.Result != true)
    {
        ShowFailure = true;
        return;
    }

    ShowSuccess = true;
    Status = "Database created successfully!";
}

Tuesday, October 8, 2013

C# WPF/Silverlight MVVM Beginners Tutorial 101 Part I

Welcome to a multi-part tutorial to help walk you through how to get started developing a WPF or Silverlight application utilizing the MVVM design pattern.

MVVM = Model, View, ViewModel

Our ViewModels primary role is to control the data displayed on our View, data pulled from our Model. The Microsoft Prism library supplies (among other things we can use later) the NotificationObject class which we will use to Notify our View when Properties Change.

Each of our ViewModels will inherit from our BaseViewModel class that we will create first.

Prerequisites

Using VisualStudio, start a New Project > Visual C# > Silverlight > Silverlight Application

Note: We use Silverlight for Web applications and WPF for Desktop applications. Most Silverlight controls are supported in WPF while there are some WPF controls that are not available in Silverlight, so it would be recommended to design your application using Silverlight to be compatible on both platforms. See Contrasting Silverlight and WPF for more information.

Using NuGet, install Prism to supply our NotifyPropertyChanged utilities:

Visual Studio > Tools > Library Package Manager > Package Manager Console

PM> Install-Package Prism

Now the Prism dll files have been added to your Project References folder and we can refer to the Prism Namespace in our code.

On to the code

Create a new Class: BaseViewModel.cs

At the top, include the Prism references, and the class inherits from Prism's NotificationObject:

BaseViewModel.cs:

using Microsoft.Practices.Prism.Commands;
using Microsoft.Practices.Prism.ViewModel;

namespace MyApp
{
    public class BaseViewModel : NotificationObject
    {
    }
}

Lets create a new Class: CarrotViewModel.cs

namespace MyApp
{
    public class CarrotViewModel : BaseViewModel
    {
    }
}

Because our CarrotViewModel inherits from our BaseViewModel, which inherits from Prism NotificationObject, any Property in our CarrotViewModel can now support RaisePropertyChanged method.

In Part II we will add some Properties and have them update our UI, after all that is the whole point of an application usually!

to be continued in Part II...