Tech Talk A software developer on all things tech, and then some

7Jan/130

Invert a Color in C#

A very quick code snippet for you all today. I had encountered an issue where I needed to invert the text color from the background (color was changing consistently from the user). So after some googling and playing around, I created something to do just that for me.

First we needed a method to take convert our color to a hex string :

//Modified from http://snipplr.com/view/13358/
private static Color HexToColor(string hexColor)
{
	//Remove # if present
	if (hexColor.IndexOf('#') != -1)
		hexColor = hexColor.Replace("#", "");

	byte red = 0;
	byte green = 0;
	byte blue = 0;

	if (hexColor.Length == 8)
	{
		//We need to remove the preceding FF
		hexColor = hexColor.Substring(2);
	}

	if (hexColor.Length == 6)
	{
		//#RRGGBB
		red = byte.Parse(hexColor.Substring(0, 2), NumberStyles.AllowHexSpecifier);
		green = byte.Parse(hexColor.Substring(2, 2), NumberStyles.AllowHexSpecifier);
		blue = byte.Parse(hexColor.Substring(4, 2), NumberStyles.AllowHexSpecifier);
	}
	else if (hexColor.Length == 3)
	{
		//#RGB
		red = byte.Parse(hexColor[0].ToString() + hexColor[0].ToString(), NumberStyles.AllowHexSpecifier);
		green = byte.Parse(hexColor[1].ToString() + hexColor[1].ToString(), NumberStyles.AllowHexSpecifier);
		blue = byte.Parse(hexColor[2].ToString() + hexColor[2].ToString(), NumberStyles.AllowHexSpecifier);
	}

	return Color.FromRgb(red, green, blue);
}

Then we can do the inversion :

private Brush invertColor(string value)
{
	if (value != null)
	{                
		Color ColorToConvert = HexToColor(value);
		Color invertedColor = Color.FromRgb((byte)~ColorToConvert.R, (byte)~ColorToConvert.G, (byte)~ColorToConvert.B);
		return new SolidColorBrush(invertedColor);
	}
	else
	{
		return new SolidColorBrush(Color.FromRgb(0,0,0));
	}
}

Finally for the example of use, we can just set the foreground from the background (or whatever you need done)

//TestLabel is just a label on the wpf form
//mainGrid is the main grid on the wpf form
TestLabel.Foreground = invertColor(mainGrid.Background.ToString());

There you go, an inverted color. Happy coding and HTH!

Tagged as: , , , No Comments
25Jun/123

The image cannot be decoded. The image header might be corrupted

I was recently trying to send to Telerik's image editing control a jpeg image in a stream format. I was checking for the other types and using the appropriate format providers, but I kept getting an exception when working with JPEGs :

The image cannot be decoded. The image header might be corrupted

With the following code :

else if (extension == "jpg" || extension == "jpeg")
{
	provider = new JpegFormatProvider();
	imageEditorUI.Image = provider.Import(file);
}

So, I had looked through their documentation and a few examples, but found nothing. I then moved on to searching the C# forums on the MSDN, and came across a post where somebody was having the same message, similar issue (not using Telerik's JpegFormatProvider). Then it hit me, the reader was starting at the last position. So, I set the position to the beginning, and everything worked as expected

else if (extension == "jpg" || extension == "jpeg")
{
	provider = new JpegFormatProvider();
        stream.Position = 0; //Setting the stream to zero.
	imageEditorUI.Image = provider.Import(file);
}

Hope this helps for anybody else with the same issue.

1Jun/126

Filter an ObservableCollection with a CollectionView in C#

Using an ObservableCollection and need to filter its contents? A quick and easy way I found was to create and bind to a CollectionView to perform the filtering for you.

Step 1 : Create the Observable Collection

The first step is to create the observable collection. This will work for objects or system type lists, so feel free to use what you like.

private ObservableCollection<Car> _CarList;
public ObservableCollection<Car> CarList
{
	get
	{
		if (_CarList == null)
		{
			//Code to build the list
		}
		return _CarList;
	}
}

Step 2 : Create the Filter

The next step is to create the filter. Simple enough, create a method that returns a boolean and takes an object as a parameter, a predicate. Perform what checks are needed within the filter and return whether it should be shown or not. Here in this example I'm checking to see if another property, FilterText (Just a property that contains the text you want to filter with), and seeing if the name of the model of the car matches.

private bool CarFilter(object item)
{
	Car car = item as Car;

	if(car.Name.Contains(FilterText))
	{
		return true;
	}
	else
	{
		return false;
	}
}

Step 3 : Bind and Create the CollectionView

The final step is to set up the adding and binding to the CollectionView, then adding the filter. Let's first create the CollectionView :

private ICollectionView _CarListView { get; set; }

Next lets set up the binding. Add this at the bottom of the null check in your ObservableCollection set. This will hook up your collection to your view, then add the filter afterwards.

//For the car filtering
this._CarListView = CollectionViewSource.GetDefaultView(_CarList);
this._CarListView.Filter = CarFilter;

Now let's see what it looks like all together :

private ICollectionView _CarListView { get; set; }
private ObservableCollection<Car> _CarList;
public ObservableCollection CarList
{
	get
	{
		if (_CarList == null)
		{
			//Code to build the list

			//For the car filtering
			this._CarListView = CollectionViewSource.GetDefaultView(_CarList);
			this._CarListView.Filter = CarFilter;
		}
		return _CarList;
	}
}

private bool CarFilter(object item)
{
	Car car = item as Car;

	if(car.Name.Contains(FilterText))
	{
		return true;
	}
	else
	{
		return false;
	}
}

Well, I hope this helps trying to add filtering to an observable collection. Good luck and happy coding!

7May/121

Saving and Loading a Byte Array To File in C#

Need a quick way to save a byte array to file and read back? So did I, and thought I'd include this simple code snippet for anybody who needed it as well.

Includes

using system.IO;

Code : Saving to File

Note below, there are two additional options (besides the name) you can include in the FileStream, FileMode and FileAccess. FileMode lets you select the way you want to handle the file. Here we are going to select Create, to tell the program to either create the file or overwrite an existing one. Next, FileAccess lets you select the way the data is inserted. We are going to do a simple write since there won't be anything to append.

private void SaveByteArrayToFile(byte[] _ByteArray, string _FileName)
{
	try
	{
		//Open the stream for the file.
		using (FileStream _File = new FileStream(_FileName, FileMode.Create, FileAccess.Write))
		{
			//Write to file. The 0 included is for the offset (where to start reading from)
			_File.Write(_ByteArray, 0, _ByteArray.Count());
		}
	}
	catch (FileNotFoundException)
	{
		MessageBox.Show("Can not find the file " + _FileName);
	}
	catch (Exception ex)
	{
		//Do what you want here, I'm just going to display the error for simplicity
		MessageBox.Show(ex.Message);
	}
}

Code : Loading From File

Next let's load a byte array from file.

private byte[] LoadByteArrayFromFile(string _FileName)
{
	try
	{
		using (FileStream _File = new FileStream(_FileName, FileMode.Open, FileAccess.Read))
		{
			byte[] _ByteArray = new byte[_File.Length];
			int bytesRead = 0;
			int BytesToRead = (int)_File.Length;

			while (BytesToRead > 0)
			{
				int read = _File.Read(_ByteArray, bytesRead, BytesToRead);
				if (read == 0)
					break;
				BytesToRead -= read;
				bytesRead += read;
			}

			return _ByteArray;
		}
	}
	catch (FileNotFoundException)
	{
		MessageBox.Show("Can not find the file " + _FileName);
		return null;
	}
	catch (Exception ex)
	{
		MessageBox.Show(ex.Message);
		return null;
	}
}

Additional Resources

MSDN FileStream.Write

MSDN FileStream.Read

Related Posts

Create an Image or Bitmap Image from a Byte[], and a Byte[] from an image

Open Documents and Media in WPF's Web Browser Control in C#

9Mar/120

The ObjectContext instance has been disposed and can no longer be used for operations that require a connection.

Have you ever assigned a value to an IEnumerable from a database, then try to access in a foreach or something similar and get the following?

"ObjectDisposedException was unhandled by user code : The ObjectContext instance has been disposed and can no longer be used for operations that require a connection."

If you are using a using statement with your entity context, then most likely you are returning an IEnumerable, which builds a list on the fly from the database, versus a List which will return the whole entire set at once. So you will be able to get a single item from the database before the connection closes vs obtaining a collection/list of the data required. To do this, add a ToList() to the end of your enumeration when returning in your using statement. For example :

            using (CarEntities dbContext = new CarEntities ())
            {
                return dbContext.CarModels;
            }

Would change to the following... Really as simple as adding the .ToList()

            using (CarEntities dbContext = new CarEntities ())
            {
                return dbContext.CarModels.ToList();
            }
16Feb/123

Binding a Combobox to an Enum in C# and WPF using XAML and MVVM

I saw a lot of posts on how to bind an enum to a combobox using code behind and C#, but since I was using MVVM, I needed a different solution. I basically wanted to bind a list of the enums in a maintenance view model, and have the the xaml handle the binding of the item list. To help remember what I did and help whomever along the way with the same issue, I thought I would write about it.

26Aug/110

Quick Formatting Tips in Visual Studio 2010

Unformatted C# code

Formatting code not only keeps OCD programmers like me sane being organized, it also helps with the readability of your code when ever you or somebody else views it for maintenance. However sometimes formatting the code quickly in Visual Studio 2010 is not exactly straight forward so I thought I'd give a few tips from what I learned so far, and will post more down the road when I see them.

5May/115

Open Documents and Media in WPF’s Web Browser Control in C#

Ever need to display a word document in the same application and didn't want to shell execute word? Ever need to display text from a rich text file or regular text file? How about quickly displaying an image file? All of these could use there own controls in WPF (Document Viewer, Image control, etc..), however if you use the web browser control, you can display all of these dynamically.  There might be a better solution for one, or all of these. I just thought I would include a quick tutorial on how to do it for those who need it done quickly and it works. This was done in WPF, using C# and the 4.0 Framework.

11Mar/110

Do a Like Statement in LINQ in C#

There has been a few times I needed to do a like statement in LINQ, but didn't know exactly how to go about it. Just in case there are you out there looking for the same, I thought I would post what I did. For example, say you had this SQL statement :

SELECT * FROM Autos WHERE Manufacturer LIKE '%Fo%'

This would translate to LINQ code in C# like the following

dbContext.Autos.Where(a=> a.Manufacturer.Contains("Fo")).AsEnumerable();
Tagged as: , , , No Comments
12Jan/110

Replacing Names Quickly in Visual ‘s Find and Replace

Part of the perks of moving your application to MvvM, you dont have to name your controls since you are binding everything. This frees up resources when running your application. Since my application was fairly large, I decided to dabble in Visual 's regular expression to replace all the names. I ended up putting :

Name="[a-z]*[0-9]*"

 

6Dec/100

Constraining the Mouse to a Graphical Element

 

I was creating a dashboard application which I needed to give the ability to drag and move a widget around a tab control item. The user is able to do this on the fly so I needed to do all the code in the code behind dynamically. I set up the code to handle the mouse down, move, and up first (This code will most likely make it in a future blog post, but wanted to keep focused for now). I then added a reference to the Microsoft Expressions and added the following line to my using statements.


using Microsoft.Expression.Interactivity.Layout;

Add the following to the widget creation.


//...Code to handle widget creation
MouseDragElementBehavior mouseBehavior = new MouseDragElementBehavior();
mouseBehavior.ConstrainToParentBounds = true;
//Here you can attach whichever dependency object you need,
//my widget is a chart, thus why I have chart there
mouseBehavior.Attach(chart);
//..more code to handle widget creation

This will work even if the horizontal and vertical alignment is equal to stretch.
I hope this helps... Happy Coding!

20Feb/103

WPF Filtering a Combobox

Setting Up the ComboBox

So in WPF, I wanted to filter a combobox to treat it as an autocompletebox.

Note : This tutorial expects you understand how to populate the combobox to have the data to filter.

I started off enabling two items on the properties tab of the combobox.

isEditable

Allows the user to be able to type in the combobox.

isTextSearchEnabled

Tells the combobox to suggest text and finishes your text with the closest word possible.
*Update (1/31/2013)- It looks like since posting this, you might be better off disabling this to filter the items properly.

Creating the Filter

That was the easy part. Now we have to create and code the filter. The first part is creating a predicate.

private bool FilterPredicate(object obj)
{
    string text = obj as string;
    if (text != null)
    {
         if (text.contains(combobox.Text))
        {
               return true;
        }
        return false
    }
    else
    {
          //if the string is null, return false
          return false;
    }

}

Next we assign the predicate to the combobox filter event. This will tell what filter to run on the combobox.

combobox.Items.Filter += this.FilterPredicate;

Finally we need to set up some of the functionality of the combobox. We can do this in an OnClick event.

private void combobox_KeyDown(object sender, KeyEventArgs e)
{
	if ((e.Key == Key.Enter) || (e.Key == Key.Tab) || (e.Key == Key.Return))
	{
		//Formatting options
		combobox.Items.Filter = null;
	}
	else if ((e.Key == Key.Down) || (e.Key == Key.Up))
	{
		combobox.IsDropDownOpen = true;
	}
	else
	{
		combobox.IsDropDownOpen = true;
		combobox.Items.Filter += this.FilterPredicate;
	}
}

There you have it, an autocompletebox. A few things to note. There may be better ways to do this (esp with the key down events, this was done as a uber quick example), but I wanted to give the beginning user an introduction on how to program this. If you have any questions please post a comment.

   
%d bloggers like this: