Saturday, December 5, 2009

Code4Food #3: Text Editor in 5 minutes – Part II. FileSystemWatcher class.

By the way I installed a rating widget on my blog. So now you can rate my posts if you like them, or if you dislike them you can put a 1 star rate too.

Hi,

Finally I found time to continue my little experiment with the text editor. Here you can read the previous post on text editor.

Today we’re going to talk about:

So here is the to download it :

ViewFile_0.2 sourcecode

 

SaVE FilE

This part actually was relatively easy to do. It was very similar to reading. Using TextWriter was enough to save the file. I still like looking fancy that’s why I used a SaveFileDialog for saving a file.

I indicated that saving would be possible by default in 2 formats without indicating extension (see saveFileDialog.Filter property), text files and C# class files.

private void btnSaveFile_Click(object sender, EventArgs e)
{
	SaveFileDialog saveFileDialog = new SaveFileDialog();
	saveFileDialog.Filter = "Text Files (*.txt)|*.txt|C# files (*.cs)|*.cs|All files (*.*)|*.*";

	saveFileDialog.SupportMultiDottedExtensions = true;

	DialogResult result = saveFileDialog.ShowDialog();

	if (result == DialogResult.OK)
	{
		_fileName = saveFileDialog.FileName;
		
		if (!string.IsNullOrEmpty(_fileName))
			SaveFileContent();
	}
}

private void SaveFileContent()
{
	lblFileName.Text = Path.GetFileName(_fileName);

	try
	{
		// we'll make only a textual file for instance
		TextWriter tw = File.CreateText(_fileName);

		try
		{
			tw.Write(txtFileContent.Text);
		}
		catch (Exception ex)
		{ MessageBox.Show(ex.Message); }
		finally
		{
			tw.Close();

			StartMonitorization();
		}
	}
	catch (UnauthorizedAccessException ex)
	{ MessageBox.Show("Sorry, you lack sufficient privileges."); }
	catch (Exception ex)
	{ MessageBox.Show(ex.Message); }
}
Notifications Sending when Your file is changed

I didn’t actually planned to implement this but I saw a great opportunity. It was already a class there that could permit me to do this in a very easy way.

So here it is:

FileSystemWatcher class – this class is particularly used to “watch” the changes that occur on a particular map or folder or a group of files (for example: textual files).

The most important things in this class are:

Properties

  • string Filter  -  Gets or sets the filter string used to determine what files are monitored in a directory.
  • string Path  -  Gets or sets the path of the directory to watch.

Both of these properties are indicated in constructor: FileSystemWatcher(String path, String filter)
Initializes a new instance of the FileSystemWatcher class, given the specified directory and type of files to monitor.

  • NotifyFilters NotifyFilter – Here you specify what kind of events do you want to watch:
    • FileName - The name of the file.
    • DirectoryName - The name of the directory.
    • Attributes - The attributes of the file or folder.
    • Size - The size of the file or folder.
    • LastWrite - The date the file or folder last had anything written to it.
    • LastAccess - The date the file or folder was last opened.
    • CreationTime - The time the file or folder was created.
    • Security - The security settings of the file or folder.
  • bool IncludeSubdirectories - Gets or sets a value indicating whether subdirectories within the specified path should be monitored.
  • bool EnableRaisingEvents - Gets or sets a value indicating whether the component is enabled.

Events

  • Created  -  Occurs when a file or directory in the specified Path is created.
  • Changed  -  Occurs when a file or directory in the specified Path is changed.
  • Renamed  -  Occurs when a file or directory in the specified Path is renamed.
  • Deleted  -  Occurs when a file or directory in the specified Path is deleted.
  • Error -  Occurs when the internal buffer overflows.

For more information consult MSDN on FileSystemWatcher.

So here is the code I implemented for support of notifications.

First I implemented StartMonitorization method where i initialized my FileSystemWatcher, and wired the events to it. I also specified the name of the file to monitor (it is always the file i load or save), and set the events I want to catch. This was done by setting NotifyFilter = NotifyFilters.FileName | NotifyFilters.LastWrite. This means that I would like to catch the events then the filename is changed or when the file is saved. Then i set EnableRaisingEvents = true for my _fileMonitor. If this property is set to false, events are not generated.

Then I implemented the event handlers. First of all I got to say that I made a single handler for Created and Changed event, and another two for Deleted and Renamed events.

The workflow was easy: when an event occurs I display a message box and ask if user wants to reload the file in case of Created, Renamed, Changed events, or remove the file from text editor if i get the Deleted event. If user answers OK, then I execute the needed method.

 

Problems I’ve met

  1. Now the first problem I saw was that my methods were not executed because I try to modify the UI thread from watcher thread. That is not working that way. We need to use BeginInvoke method and to create a delegate in UI thread, and to pass him the names of the methods to execute. The difference is that this delegate is on UI thread, and he is allowed to execute the methods from the same thread. So I created LoadContentCallback delegate.
  2. Second problem that I had was that the events were generated twice. To solve this problem I created 3 boolean fields to match the events. When the event is generated I set this boolean to true. Second time I set it to false, without actually executing the logic. With the Deleted event I had no problems because i dispose the _fileMonitor once user deletes file from text editor.
  3. Changed event handler handled 2 events Created and Changed, so I was wondering how am I gonna determine which event is actually handled. But the arguments of the event FileSystemEventArgs helped me because there is a property WatcherChangeTypes e.ChangeType which indicate what kind of change was made. From here it was easy because I knew what boolean to reset.
  4. To determine the new file name when Renamed event occurs was super easy thanks to RenamedEventArgs class which contains the following info, that did helped me:
    • FullPath - Gets the new fully qualifed path of the affected file or directory.
    • Name  -  Gets the new name of the affected file or directory.
    • OldName  -  Gets the old name of the affected file or directory.
    • OldFullPath - Gets the previous fully qualified path of the affected file or directory.

 

private FileSystemWatcher _fileMonitor;

private bool _wasChanged;
private bool _wasRenamed;
private bool _wasCreated;

public delegate void LoadContentCallback();

private void StartMonitorization()
{
	_fileMonitor = new FileSystemWatcher(Path.GetDirectoryName(_fileName), Path.GetFileName(_fileName))
		{
			NotifyFilter = NotifyFilters.FileName | NotifyFilters.LastWrite,
			IncludeSubdirectories = false
		};

	_fileMonitor.Changed += FileMonitor_OnChanged;
	_fileMonitor.Created += FileMonitor_OnChanged;
	_fileMonitor.Deleted += FileMonitor_OnDeleted;
	_fileMonitor.Renamed += FileMonitor_OnRenamed;

	_fileMonitor.EnableRaisingEvents = true;
}

private void FileMonitor_OnRenamed(object sender, RenamedEventArgs e)
{
	if (!_wasRenamed)
	{
		DialogResult result = MessageBox.Show("The file " + e.OldName + " was renamed. \r\n" +
											"Do you want to load the new file ?", "File was renamed", MessageBoxButtons.OKCancel);

		_wasRenamed = true;

		if (result == DialogResult.OK)
		{
			_fileName = e.FullPath;
			this.BeginInvoke(new LoadContentCallback(LoadFileContent));
		}
	}
	else
	{
		_wasRenamed = false;
	}
}

private void FileMonitor_OnDeleted(object sender, FileSystemEventArgs e)
{
	DialogResult result = MessageBox.Show("The file " + e.Name + " was deleted. \r\n" + "Do you want to remove it from text editor ?", "File was deleted",
MessageBoxButtons.YesNo);

	if (result == DialogResult.Yes)
	{
		_fileMonitor.Dispose();

		this.BeginInvoke(new LoadContentCallback(ResetUiContent));
	}

}

private void FileMonitor_OnChanged(object sender, FileSystemEventArgs e)
{
	if ((!_wasCreated && e.ChangeType == WatcherChangeTypes.Created) ||
		(!_wasChanged && e.ChangeType == WatcherChangeTypes.Changed))
	{
		DialogResult result = MessageBox.Show("The content of the file " + e.Name + " was changed. \r\n" + "Do you want to reload it ?", "File was changed",
MessageBoxButtons.OKCancel);

		if (e.ChangeType == WatcherChangeTypes.Changed)
		{
			_wasChanged = true;
		}
		else
		{
			_wasCreated = true;
		}

		if (result == DialogResult.OK)
		{
			this.BeginInvoke(new LoadContentCallback(LoadFileContent));
		}
	}
	else
	{
		if (e.ChangeType == WatcherChangeTypes.Changed && _wasChanged)
		{
			_wasChanged = false;
		}
		else if (e.ChangeType == WatcherChangeTypes.Created && _wasCreated)
		{
			_wasCreated = false;
		}
	}
}

private void ResetUiContent()
{
	txtFileContent.Text = string.Empty;
	lblFileName.Text = string.Empty;
	_fileName = string.Empty;
}
PUTTING Keyboard shortcuts on your buttons

This is I think really the easiest part. First you wire up your form with KeyDown event, make a event handler (in my case it was ViewFile_KeyDown handler). Then you need to set your form KeyPreview property on true, because otherwise it would not be able to catch keyboard events.

Than you just indicate what kind of combination will execute your action. For example I wanted my app to react at       Ctrl + S as a save action shortcut. In event handler I just indicate that I want it to react on Control + S for saving and Control + O for loading/opening the file.

this.KeyDown += new System.Windows.Forms.KeyEventHandler(this.ViewFile_KeyDown);
this.KeyPreview = true;

private void ViewFile_KeyDown(object sender, KeyEventArgs e)
{
	if (e.Modifiers == Keys.Control)
	{
		switch (e.KeyCode)
		{
			case Keys.S:
				btnSaveFile_Click(btnSaveFile, null);
				break;
			case Keys.O:
				btnLoadFile_Click(btnSaveFile, null);
				break;
		}
	}
}
New Features coming…

Now I think about new features that could be done on top of what already exists:

I also think about migrating this app on WPF to provide better visual experience. I think I will do it in the next 2 releases.

The Entire Sourcecode

Here you can see entire sourcecode file in collapsed way.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;

// Author : Poperecinii Timur
namespace ViewFile
{
    public partial class ViewFile : Form
    {
        private string _fileName;
        private FileSystemWatcher _fileMonitor;

        private bool _wasChanged;
        private bool _wasRenamed;
        private bool _wasCreated;

        public delegate void LoadContentCallback();

        public ViewFile()
        {
            InitObjects();

            InitializeComponent();
        }

        private void InitObjects()
        {
            _fileName = string.Empty;
        }

        private void btnLoadFile_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();

            ofd.CheckFileExists = true;
            ofd.Multiselect = false;

            DialogResult result = ofd.ShowDialog();

            if (result == DialogResult.OK)
            {
                _fileName = ofd.FileName;

                if (_fileName != string.Empty)
                    LoadFileContent();
            }
        }

        private void LoadFileContent()
        {
            lblFileName.Text = Path.GetFileName(_fileName);

            try
            {
                TextReader tr = new StreamReader(_fileName);
                try
                { txtFileContent.Text = tr.ReadToEnd(); }
                catch (Exception ex)
                { MessageBox.Show(ex.Message); }
                finally
                {
                    tr.Close();

                    StartMonitorization();
                }
            }
            catch (FileNotFoundException ex)
            { MessageBox.Show("Sorry, the file does not exist."); }
            catch (UnauthorizedAccessException ex)
            { MessageBox.Show("Sorry, you lack sufficient privileges."); }
            catch (Exception ex)
            { MessageBox.Show(ex.Message); }
        }

        private void StartMonitorization()
        {
            _fileMonitor = new FileSystemWatcher(Path.GetDirectoryName(_fileName), Path.GetFileName(_fileName))
                               {
                                   NotifyFilter = NotifyFilters.FileName | NotifyFilters.LastWrite,
                                   IncludeSubdirectories = false
                               };

            _fileMonitor.Changed += FileMonitor_OnChanged;
            _fileMonitor.Created += FileMonitor_OnChanged;
            _fileMonitor.Deleted += FileMonitor_OnDeleted;
            _fileMonitor.Renamed += FileMonitor_OnRenamed;

            _fileMonitor.EnableRaisingEvents = true;
        }

        private void FileMonitor_OnRenamed(object sender, RenamedEventArgs e)
        {
            if (!_wasRenamed)
            {
                DialogResult result = MessageBox.Show("The file " + e.OldName + " was renamed. \r\n" +
                                                    "Do you want to load the new file ?", "File was renamed", MessageBoxButtons.OKCancel);

                _wasRenamed = true;

                if (result == DialogResult.OK)
                {
                    _fileName = e.FullPath;
                    this.BeginInvoke(new LoadContentCallback(LoadFileContent));
                }
            }
            else
            {
                _wasRenamed = false;
            }

        }

        private void FileMonitor_OnDeleted(object sender, FileSystemEventArgs e)
        {
            DialogResult result = MessageBox.Show("The file " + e.Name + " was deleted. \r\n" +
                                                  "Do you want to remove it from text editor ?", "File was deleted",
                                                  MessageBoxButtons.YesNo);

            if (result == DialogResult.Yes)
            {
                _fileMonitor.Dispose();

                this.BeginInvoke(new LoadContentCallback(ResetUiContent));
            }

        }

        private void FileMonitor_OnChanged(object sender, FileSystemEventArgs e)
        {
            if ((!_wasCreated && e.ChangeType == WatcherChangeTypes.Created) ||
                (!_wasChanged && e.ChangeType == WatcherChangeTypes.Changed))
            {
                DialogResult result = MessageBox.Show("The content of the file " + e.Name + " was changed. \r\n" +
                                                      "Do you want to reload it ?", "File was changed",
                                                      MessageBoxButtons.OKCancel);

                if (e.ChangeType == WatcherChangeTypes.Changed)
                {
                    _wasChanged = true;
                }
                else
                {
                    _wasCreated = true;
                }

                if (result == DialogResult.OK)
                {
                    this.BeginInvoke(new LoadContentCallback(LoadFileContent));
                }
            }
            else
            {
                if (e.ChangeType == WatcherChangeTypes.Changed && _wasChanged)
                {
                    _wasChanged = false;
                }
                else if (e.ChangeType == WatcherChangeTypes.Created && _wasCreated)
                {
                    _wasCreated = false;
                }
            }
        }

        private void ResetUiContent()
        {
            txtFileContent.Text = string.Empty;
            lblFileName.Text = string.Empty;
            _fileName = string.Empty;
        }



        private void btnSaveFile_Click(object sender, EventArgs e)
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.Filter = "Text Files (*.txt)|*.txt|C# files (*.cs)|*.cs|All files (*.*)|*.*";

            saveFileDialog.SupportMultiDottedExtensions = true;

            DialogResult result = saveFileDialog.ShowDialog();

            if (result == DialogResult.OK)
            {
                _fileName = saveFileDialog.FileName;
                
                if (!string.IsNullOrEmpty(_fileName))
                    SaveFileContent();
            }
        }

        private void SaveFileContent()
        {
            lblFileName.Text = Path.GetFileName(_fileName);

            try
            {
                // we'll make only a textual file for instance
                TextWriter tw = File.CreateText(_fileName);

                try
                {
                    tw.Write(txtFileContent.Text);
                }
                catch (Exception ex)
                { MessageBox.Show(ex.Message); }
                finally
                {
                    tw.Close();

                    StartMonitorization();
                }
            }
            catch (UnauthorizedAccessException ex)
            { MessageBox.Show("Sorry, you lack sufficient privileges."); }
            catch (Exception ex)
            { MessageBox.Show(ex.Message); }
        }

        private void ViewFile_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Modifiers == Keys.Control)
            {
                switch (e.KeyCode)
                {
                    case Keys.S:
                        btnSaveFile_Click(btnSaveFile, null);
                        break;
                    case Keys.O:
                        btnLoadFile_Click(btnSaveFile, null);
                        break;
                }
            }
        }
    }
}

Friday, October 23, 2009

Windows 7 officially released today + Visual Studio 2010 Beta 2 is available

 

Windows 7

 

Hi,

since the Vista “nightmare” begun, the end-users, Microsoft customers and general client in software development had fear passing multimillion companies to Vista, and after all why XP is bad? What made Vista so bug full ?

The answer is evident. In windows Vista Microsoft tried to do something very different that they were doing before. With the power of WPF, and a lot of other new features for Windows, as Sidebar for example with all those gadgets, came the possibility to make bugs, because then people try something new, at first it is not really an ideal thing.

That is why most costumers continued to stay on XP and Microsoft was obliged in a way to make the SP3 for Windows XP. At the same time another team was working on Windows Vista SP1, which eliminated most problems. But these people seem to forget that we had 3 Service packs for XP and the original version was far from ideal too.

But as clients were already disappointed they were actively refusing to accept Vista as a default OS on their computers, and Microsoft in a year started to develop the new brand Windows 7, which was labeled lately Windows Heaven. :)

Windows 7 in comparison with Vista and even XP SP3 is:

Faster loading, more responsive, more intuitive and much more compatible + ideal on 64 bits machines. You will fall in love with this OS, and I think it is the release which will make people forget about Vista, and try to create with it better quality software. Anyway the future year will show us all the improvements that can be done on Windows 7, because nothing is really ideal. 

And it is already released today! So from now on I will also be publishing tips for Windows 7. Hope that you will grab your copy in next months. And by the way here is the link for the requirements for Windows 7.

Visual Studio 2010 Beta 2

While a lot of us, .NET developers still try to learn all the features from the framework and .NET 3.5 in general, because as one man said

Framework big, brain small :)

.NET 4.0 is coming out, which a whole new bunch of features and possibilities and a new IDE: Visual Studio 2010 is coming out and bringing with it a lot of goodies. And first what I appreciated was the new look of Visual Studio

The new design plus a lot of different new features of Visual Studio 2010, I won’t describe them but I will give you the starting points

So go and check Visual Studio 2010 Beta 2 right now, because the RTM is announced on March 22, 2010. And we’ll have some time to play with Beta 2.

Monday, October 12, 2009

Tips 003: Integrating Google Chrome with Delicious and Evernote and other cool tools

 

Hi,I use Google Chrome a lot and also I am already used with such beautiful tools which make my life easier and more structured :). One of those tools are Delicious bookmarks and Evernote notes. I use them almost everywhere.

I can talk hours about the worth of both of these tools, but I think about making a special series about useful tools in our life, I will definitely write about Evernote. So enough about that.

EVERNOTE

  • Now to test it, select something on a webpage and click on this bookmark.

  • So what do you need to do is just login into Evernote and everything selected will be saved as a note.

Delicious

 

Delicious in another cool app which will take care about your bookmarks. You can add tags, description, title to have the possibility to search through all your bookmarks using one of these attributes.

The annoying thing was that you would usually use the web site of the Delicious. What’s why I always liked the add-ons to Firefox and IE from Delicious it permitted me to use a shortcut to bookmark a website directly in Delicious system.

That’s why I missed it so much in Chrome.

  • Here you should find a very nice description how you can add 2 Delicious bookmarklets in Chrome. Just a simple drag-n-drop opperation will make it for you. Now you can see on your Chrome bookmarks bar these 2 buttons.

 

That’s the way to add some more functionality to Chrome while surfing the web with the great speed of JavaScript loading, that it’s offering. I love this browser and I think we could give it even more functionality.

If you know any other apps which can be used with Chrome as well or have any ideas, words to share, please leave a comment.

.

Monday, October 5, 2009

Code4Food #2: Create a Text Editor in 5 minutes. C# - magic

Hi, guys!
It is October and it's the time for another Code4Food episode.

Today I'm gonna show you some magic. We'll make a text editor in C#.


Here is the sourcecode for Downloading:
ViewFile sourcecode


Note: This part will contain only loading certain file in a textbox.

1st minute.

a) Create a new WinForms app in Visual Studio (File -> New -> Project -> Windows Forms Application) and change the name of the project to ViewFile.


b) Delete the form Form1.cs from the solution.



c) Add a new form to the project and name it ViewFile


2nd minute

a) Open the ViewFile form in Designer mode. Add a textbox to this form and name it txtFileContent. Change it's 'Multiline' property to true, and 'ScrollBars' to 'Both'.


b) Change it's size to fit the form. After this change the 'Anchor' property to 'Top, Bottom, Left, Right'.


c) Add a button to the form and name it btnLoadFile and change it's 'Text' property to 'Load File'.
d) Add a button to the form and name it btnSaveFile and change it's 'Text' property to 'Save File'.

e) Add a label where we'll show the file name. Name it lblFileName and change it's 'Text' property to 'File Name'

f) In Program.cs change the following line so that your application runs the ViewFile form.
Application.Run(new ViewFile());

At this point you can run the User Interface of our app.


3rd minute

a) Create a private field _fileName where we'll store the name of the file we want to open. Create than a method where we'll initialize all the fields in our app and name it InitObjects. Initialize there _fileName to string.Empty. Also we'll make the filename label empty for now, because we don't have a file opened.

b) Double click the 'Load File' button and in the event generated by Visual Studio create an instance of OpenFileDialog. Set the properties of this instance: 'CheckFileExists' (verifies if the file exists) - true, 'Multiselect' (the ability to select multiple files in the dialog at once) - false. And call the method ShowDialog.

c) When the file is selected we'll show in the label only the name of the file which is stored in 'SafeFileName' property of the OpenFileDialog instance. Also save the full path to the file in _fileName field, and it is equal to 'FileName' property of the instance of the dialog.

Now our code should look like this:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace ViewFile
{
public partial class ViewFile : Form
{
private string _fileName;

public ViewFile()
{
InitializeComponent();
InitObjects();
}

private void InitObjects()
{
lblFileName.Text = string.Empty;
_fileName = string.Empty;
}

private void btnLoadFile_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();

ofd.CheckFileExists = true;
ofd.Multiselect = false;

ofd.ShowDialog();

_fileName = ofd.FileName;
lblFileName.Text = ofd.SafeFileName;
}
}
}


4th minute

Now what we need to do is read the file and show its content in our textbox.
We'll use the StreamReader class, specifically its method ReadToEnd() and nested try-catch blocks to catch all the potential exceptions while we are trying to open a file.

So the final version of our app logic is this:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace ViewFile
{
public partial class ViewFile : Form
{
private string _fileName;

public ViewFile()
{
InitializeComponent();
InitObjects();
}

private void InitObjects()
{
lblFileName.Text = string.Empty;
_fileName = string.Empty;
}

private void btnLoadFile_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();

ofd.CheckFileExists = true;
ofd.Multiselect = false;

ofd.ShowDialog();

_fileName = ofd.FileName;
lblFileName.Text = ofd.SafeFileName;

if (_fileName != string.Empty)
LoadFileContent(_fileName);
}

private void LoadFileContent(string chosenFileName)
{
try
{
TextReader tr = new StreamReader(chosenFileName);
try
{ txtFileContent.Text = tr.ReadToEnd(); }
catch (Exception ex)
{ MessageBox.Show(ex.Message); }
finally
{ tr.Close(); }
}
catch (System.IO.FileNotFoundException ex)
{ MessageBox.Show("Sorry, the file does not exist."); }
catch (System.UnauthorizedAccessException ex)
{ MessageBox.Show("Sorry, you lack sufficient privileges."); }
catch (Exception ex)
{ MessageBox.Show(ex.Message); }
}
}
}

5th minute


For now we can really open any file but I wanted to make it look like a source code file. And disable some things we don't actually use.



a) We'll make the button 'Save File' disabled. Because we don't actually use it.

b) We'll change the 'Font' property of the txtFileContent to 'Courier New; 9pt'









Sunday, September 20, 2009

Tip 002: Thumbnails not showing in Vista, Pictures folder

Hi, once in a while we all have this thing which seems to be a kinda sick problem, because nobody knows how to deal with it, and more nobody have ever seen or heard about things like that. There was this guy calling me and saying that he has this kinda crazy problem, he had a lot of photos, but the thumbnails didn't show up no matter what the poor guy was doing about it, just ordinary Vista icon for the image was shown (like mountains or something like that). First I was thinking that he has some hidden file where all the thumbnails info should be (something like Thumbnails.db in XP), which should deleted and than creating it one more time. But this wasn't the case. What it turned out to be is a simple option in Tools menu: Tools -> Folder Options -> View tab -> Advanced settings -> Files and Folders section, the check box "Always show icons, never thumbnails" should be unchecked. Because if it is checked, then you'll always see icons instead of thumbnails, and this refers not only to photos but to all kind of files like PDF or video files. So be aware of this option. See ya!

Saturday, September 19, 2009

PODCAST #2: Microsoft Online Office Tools and Twitter with voice

Hi, today me and my friend Frank discussed about latest Tech news: Microsoft Online Office Tools, Twitter with voice, FarmVille, Yahoo! Messenger 10 Beta, and improvements into Yahoo! Mail, Google Chrome 3.0, Bing search engine. So check it out! PODCAST #2: Microsoft Online Office Tools and Twitter with voice!

Thursday, September 17, 2009

Tuesday, September 15, 2009

PODCAST #1: First try on random topics

Hi,
today i've tried to configure my software properties to make it possible to record a podcast.
I've tested this posibility with my friend Rajib from India, we're talking here about lots of topics like Unix-like systems, Windows 7, best configuration for an ultimate laptop, Video players...
So this is a sample. Hope you will like it and I will be able to do this another time.
Listen or download : PODCAST #1 : First try - Rajib & I.

Wednesday, September 9, 2009

New Udevi C# courses: Udev'itRight

Hi,
I decided to start C# begginers courses online.
I'll cover 3 main branches of applications:
1. Desktop app (console, WinForms, WPF)
2. Web apps (ASP.NET MVC, Silverlight)
3. Mobile Apps (Windows Mobile)
and the course itself will consist in writting 3 different applications:
1st app - Green Application - will be a simple app, which will be made by 2 of us, me and my student. Here I'm gonna try to put the basics of real project knowledges like team work, versionning source code software, code comments, bugtracking and also try to put my student to work. I mean really... put his brain in action, get some logical stuff to do.
2nd app - Yellow Application will be more complicated so my student could progress and dive into Programming wolrd himself. But any student may need some help in DEV process, so i'm gonna just give him some advices, may be directions. The yellow level can really permit it. The application itself will have more functional stuff than green app had. Plus it will have a technique to learn as a bonus (it is just a plan for now so let it be a little secret)
3rd app - Red application - the highest level of complexity (for begginers), no chance to ask me for an advice, it will be the work of the student itself. Nice bussiness apps with clean functionality, without bugs, with commented code and a series of tests runned over this code. That's what I call the highest level of quality. I know that will be some persons who just won't make it. But that's ok... at least you've tried it and you will know your errors: what was done wrong, where you should pay more attention. Because this is really what we are doing, helping people to get experience.
So i'm gonna try to combine more persons (5-6) in a team. And work individually and in team with these persons. Aproximate period of courses duration is 4-5 months. 2 times a week for 2 hours each time.
You need to have skype and Mikogo installed.
I'll covering a wide range of subjects.
So if you want to join you should put a comment to this post and give me some details so I could contact you. Or just email me at monomachus85@yahoo.com.
P.S. I am thinking now about improvements to Frank Car System, so if you have some thoughts about that you can comment that post as well.

Wednesday, September 2, 2009

Code4Food #1: Frank Car Assistant application.

Hi! There are a lot of situations when you as a programmer need to code just for 5 bucks. Of course you don't have to put your soul in these kind of programs, if you don't want to, but remember if you will make a nice piece of code, which will satisfy all client's requirements, you will definitely be able to buy some caviar as a bonus to your butter and bread. Ladies and gents, Code4Food series is starting. Yesterday I was talking to my online friend Frank. He already studied Java programming language so I thought I should presented him C# language, writing down some simple examples. I'm gonna try to present you the same thing using the same examples. Here is the sourcecode for Downloading: FrankTestConsoleApp sourcecode FrankCarAssistant sourcecode

"Hello World"

So first program is like always HelloWorld 1. File -> New -> Project 2. Choose Project types -> Visual C# -> Windows -> In templates choose Console Application 3. Choose a name for your project. In my case I chosen the name FrankTestConsoleApp. In Program.cs file we will have the following thing:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace FrankTestConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!!!");

            Console.ReadKey();
        }
    }
}
Another thing that I was showing was some loops from C#. We first create an array of strings and than we call each string using different loops.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace FrankTestConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] names = { "Frank", "Timur", "Jessica", "Helen" };

            Console.WriteLine("=======FOR loop=========");

            for (int i = 0; i < names.Length; i++)
            {
                Console.WriteLine("Hello {0}!", names[i]);
            }

            Console.WriteLine("=======FOREACH loop=========");

            foreach (string name in names)
            {
                Console.WriteLine("Hello {0}!", name);
            }

            Console.WriteLine("=======WHILE loop=========");

            int index = 0;

            while (index < names.Length)
            {
                Console.WriteLine("Hello {0}!", names[index]);
                index++;
            }

            Console.ReadKey();
        }
    }
}
So the result is the same for each loop.

Car class

The next thing we did was creating a Class Library Project CarsModel. 1. File -> New -> Project 2. Choose Project types -> Visual C# -> Windows -> In templates choose Class Library When you create a Class Library project it means that all the classes which will be in this project will be built into a single .DLL file. A DLL file can contain multiple namespaces. In this project we created a class Car which contains 2 properties: int WheelNumber and a string Name, and a method PrintInfo, and 2 constructors. A property is a public accessor to a private field of the class. This is an analog for Java's get and set methods. For example: we have a private field _wheelsNumber which can be accessed by other classes using the WheelNumber property. A property can have 2 parts get and set. When you have in your property the get part it means that the other class can read the value of your private field. The set part of the property allows to set a value for the private field of the class. In fact when you read a property (ex.: int numberOfCars = car.WheelNumber) everything inside the get part is executed (in our case it's get { return _wheelsNumber; }). When you write a value into a property (ex.: car.WheelNumber = 3) everything inside the set part is executed. You can have properties with only get or only set part. It means that you can only read or write into this property. The PrintInfo method was only used for printing to our console the Car data (name and wheels number). By creating this method into the Car class we made it possible to call this method from the class instance (ex.: car.PrintInfo()). This way of programming is called to delegate to an object a method, usually it is used when you refactor your old code and you see that a method only uses the instance of a class, for example X. It is than logically to move this method into the class X itself, than you can simple call x.RefactoredMethod() In this class we also have 2 constuctors with and without parameters. The constructor with parameters initializes the properties of this class. The default constructor (without parameters) initializes the properties with its default values (for int it is 0, and for string it's string.Empty).
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CarsModel
{
    public class Car
    {
        private int _wheelsNumber = 0;

        public int WheelNumber
        {
            get { return _wheelsNumber; }
            set { _wheelsNumber = value; }
        }

        private string _name = string.Empty;

        public string Name
        {
            get { return _name; }
            set { _name = value; }
        }

        public Car()
        {

        }

        public Car(int wheelz, string carName)
        {
            this.WheelNumber = wheelz;
            this.Name = carName;
        }

        public void PrintInfo()
        {
            Console.WriteLine(this.Name);
            Console.WriteLine(this.WheelNumber);
            Console.WriteLine("=================");
        }
    }
}

Frank Car Assistant Console Application

Than we build the project and added its DLL file to the references of the FranksTestConsoleApp, and made a little console application which I'm gonna try to explain.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CarsModel;

namespace FrankTestConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            List<Car> listCar = new List<Car>();

            Car franksCar = new Car(2, "Honda Civic");
            Car timurCar = new Car(1, "4x4");

            listCar.Add(franksCar);
            listCar.Add(timurCar);
            listCar.Add(new Car(14, "Jessica"));

            bool iWantToLeave = false;

            while (!iWantToLeave)
            {
                Console.WriteLine(Environment.NewLine);

                PrintHelp();

                Console.WriteLine(Environment.NewLine);

                int numberEntered = int.Parse(Console.ReadLine());

                switch (numberEntered)
                {
                    case 2: RemoveCarFromList(listCar);
                        break;
                    case 3: listCar.Add(AddNewCar());
                        break;
                    case 4: iWantToLeave = true;
                        break;
                    default: ShowMeTheCars(listCar);
                        break;
                }
            }

            Console.WriteLine("Bye");

            Console.ReadKey();
        }

        /// 
        /// Prints the current list of cars.
        /// 
        /// The lists of cars.
        private static void ShowMeTheCars(List<Car> listCar)
        {
            Console.WriteLine(Environment.NewLine);

            foreach (Car carName in listCar)
            {
                carName.PrintInfo();
            }
        }

        /// 
        /// Prints the help.
        /// 
        private static void PrintHelp()
        {
            Console.WriteLine("This is the Frank car system assistant");
            Console.WriteLine("PRESS");
            Console.WriteLine("1 - To see the list of the cars");
            Console.WriteLine("2 - To remove a car from the list");
            Console.WriteLine("3 - To add a car to the list of the cars");
            Console.WriteLine("4 - To say 'Bye'");
        }

        /// 
        /// Adds the new car.
        /// 
        /// The new car object
        private static Car AddNewCar()
        {
            Console.WriteLine("Enter the name of the car: ");
            string name = Console.ReadLine();
            Console.WriteLine("Enter the number of wheels: ");
            int number = int.Parse(Console.ReadLine());

            return new Car(number, name);
        }

        /// 
        /// Removes the car from list.
        /// 
        /// The list of cars.
        private static void RemoveCarFromList(List<Car> listCar)
        {
            string nameOfTheCar = Console.ReadLine();

            Car searchedCar = listCar.Find(delegate(Car car) { return car.Name == nameOfTheCar; });

            if (searchedCar == null)
            {
                Console.WriteLine("ERROR! We don't have this car, really, don't try to find it.");
                return;
            }

            listCar.Remove(searchedCar);
        }

    }
}
So first I'm gonna explain what this application is doing. So it can print you the help menu and depending on the part you select, it can show the list of cars available with it's characteristics, add a new car or remove a car with a certain name. The PrintHelp method only prints some bunch of strings. In the beggining of our Main method what we do is initialize a List of our object Car from CarsModel namespace, and we add some custom cars in it.
List<Car> listCar = new List<Car>();

Car franksCar = new Car(2, "Honda Civic");
Car timurCar = new Car(1, "4x4");

listCar.Add(franksCar);
listCar.Add(timurCar);
listCar.Add(new Car(14, "Jessica"));
In the AddNewCar method we create a new car by entering its name and the number of the wheels for this particular car and than return this car. ShowMeTheCars method calls for each Car object from a list of cars (listCar) its method PrintInfo(). The most interesting method is RemoveCarFromList method. What I am doing there is trying to show the power of List objects in C#. Firstly we have a Find method in List object which permits us to find an object from the list which satisfy a specified condition. Car searchedCar = listCar.Find(delegate(Car car) { return car.Name == nameOfTheCar; }); In this example the condition is that the name of the car which we indicated (nameOfTheCar) should coincide with the car's name from the list (car.Name). And for formulating it we create a delegate with the list's object as an argument which should return a boolean value (true or false), according to specified condition. Than in Main method we create a boolean field iWantToLeave = false, and we will loop, while we'll want to leave. Firstly we'll call PrintHelp method, than we'll parse the introduced number, and will pass this number in a switch statement, and treat each case apart. Notice that we'll have a default case, when any other number than specified in case statements will be introduced. If the user choose the exit option I just set the field iWantToLeave = true and the while condition isn't already passed and we close the app.

Frank Car Assistant App

Now we need to translate the application logic from a console app to a windows forms app.
1. File -> New -> Project 2. Choose Project types -> Visual C# -> Windows -> In templates choose Windows Forms Application
First we draw our form. And add into references of this project the CarsModel.dll file.
Now for the Add Car and Remove Car buttons we use the same code as for our console application.
The interesting part comes to populating our listbox and refreshing it.
For populating listbox we added this code:
BindingSource bSource = new BindingSource();
...
private void Form1_Load(object sender, EventArgs e)
{
   InitListOfCars(listCar);

   bSource.DataSource = listCar;

   lstCars.DataSource = bSource;
   lstCars.DisplayMember = "Name";
}
This means we have a binding source and we put it it (as its Datasource) the list of our cars. Now we put this binding source as Datasource of the listbox. In listbox.DisplayMember we choose the property of our object which will be shown in listbox, in our case it is name that we want to show. We decided that we need to fill in the textboxes with the data of selected car. This is made by this code:
private void lstCars_SelectedIndexChanged(object sender, EventArgs e)
{
   txtCarName.Text = (lstCars.SelectedItem as Car).Name;
   txtNumberOfWheels.Text = (lstCars.SelectedItem as Car).WheelNumber.ToString();
}
And we most difficult part was to find out how to update listbox data when we add or remove a Car object. The solution s this line: bSource.ResetBindings(true); the program generates automatically a Reload event when the flag is equal to true, and the datasource for bindingSource is reloaded.
So that have been the longest post of mine so far, but we've done a lot of stuff this time. Hope you liked it! Next time we'll be thinking about possible improvements and bugs in Frank Car Assistant application, and will try to fix them.

Tuesday, August 25, 2009

Agora : Projecting the model. Part 1

The model. What is actually model? Model is the representation of all objects in our system. Having the model projected, we can easily implement that in data base. How do we project the model ? We need to create a model using all the infos we have about the application we need to do. And we need to use that data to create the main objects with their properties and methods. Today I am going to try something different. I am going to explain everything in my video. This is a new format for me and I hope you'll like it. We'll only create the first half of the model.

Monday, August 17, 2009

My New Application: Agora.

Hi, It was a pretty big period of time while I wasn't posting anything, but I do have a work, and some personal problems like everyone do, I guess. I am posting here some thoughts about programming. New App: Accounting Application So now about the new application. I will be doing a new application for Accounting. It will be a simple application and I will be constantly adding some functionality to it. And may be this will become something interesting. Methodology I'll try to mix some new things in this app. From the ideological view I'll use Agile Scrum methodology. Read more about it in Wikipedia. Our idea will be dividing the future functionalities in sprints. Every sprint will have a defined number of tasks. Each task will cost points depending on its difficulty. A deadline will be established. If we can't realize everything in time, some functionalities will be moved to next sprint. THE DEADLINE CAN'T BE MOVED. Every functionality should be tested by a number of unit tests + some integration tests. This is done to achieve 2 things: granularity of my application + testability. The better number of coverage will be, the less space will be available for bugs, and the quality of the end product will be better. For tests we'll be using mocks in some places. Application Overview The codename is Agora. The application will contain some functionalities: 1. Placing some products in stock 2. Removing products from stock 3. Introducing the products sold for each day 4. Searching products - filters, sorting. 5. Viewing products in stock. 6. Calculating the sums for the month, week, day, period of time. Configuring a number of working hours for a particular day. 7. Calculating the salary of a particular seller on this period. 8. Different sellers. 9. Administration part: 2 types of Users, administrator and simple user. 10. Configuring the salary of the seller: optionally, percentage from sales, fixed salary. 11. Viewing the working days of a particular seller. 12. Setting price, changing price for a product. 13. Some options for configuration of DB. Postgres? Access? MySQL? port, host. I'll be thinking about the future architecture of the application. In the meanwhile you can add/complete some functionalities. To be continued...

Wednesday, March 25, 2009

Welcome a brand new starting series of posts: MVC Madness

Hi. A few months ago I've started to read about the ASP.NET MVC. And I loved what I saw there. I thought about comparing it to existing MVC frameworks in another languages and here we go, I've decided to make a series of posts with examples and snippets from each framework. Here what we have at the moment:
  • ASP.NET MVC 1.0 - the new released framework which allows us to have better control on page, cleaner HTML source, nice url formatting - routing, and all this is still ASP.NET
  • Symfony - a PHP framework which I will learn about, and you will obviously gonna help me with this.
  • Lift - also a new 1.0 framework which is based on Scala. Scala is a object-oriented and at the same time functionnal programming language which sits on top of Virtual Machine and lets you have a scalable application using the Scala itself and the libraries from the language which it exploits. For example Scala which sits on the top of Java VM, can use java libraries in Scala by importing them, and by that we achieve an interop language with objected-oriented and functionnal paradigm at the same time. Well some day I'll post particularily about Scala. So Lift is based on Scala and with this framework we can easy create a various range of Web 2.0 sites and by that I mean Ajax/COMET, jQuery and other technologies used in Web 2.0.
  • Spring - well, this framework is a widely known one. I wanted to present examples in Jakarta Struts, but I've decided that it will be better for me to learn something new, and particularily Spring. By the way, there are a lot of opinions on the Web that point us to idea that Struts has poorly implemented MVC. And that a better implementation is present in Spring. So I'm gonna give it a try.
May be there are languages and frameworks which I didn't cover yet, but you would like me to cover. If so let me know about it. I'll see what we can do. By the way, any examples of using MVC in desktop applications? So a little bit about the pattern itself. It is an old pattern. MVC was first described in 1979 by Trygve Reenskaug, who came from that interesting programming community of Smalltalk (we know all the other guys too, Kent Beck, Ward Cunningham, Martin Fowler, and others). It was introduced to separate different functional parts of application, and by that we achieve loused coupling of different parts of a system. So changing one part will not head to changing in all the parts. So what is it anyway?
  • Model - which is data, XML, object, whatever we handle and try visualize in our applications, web pages.
  • View - the presentation layer, window on the screen, our web page, UI elements which visualizes the Model. Note that we can have multiple views for a single model. We call it reusing the Model. That means that for having different views of the same data we don't need multiple tables/objects/XML tags/whatever. We can achieve we same effect using multiple Views.
  • Controller - as the name says, it controls the user input, events which happened on the View side and transmits these results to the Model.
How does it work together: Ok, here I'll give an example for you, let's say we have an Agenda - a web application. We have the database (which represents our Model) with the Users Table which contains the users id, user name and its password. And we also have the Events Table which contains event id, user id, the name of the event and the date. 1. User interacts with the View Now a user wants to add an event into his agenda. His view represents a table with a date column and an event column. If nothing is planned for a specific date he can select this date and plan an event on this date.
         Date                                         Event

               23th of March, 2009                   David's birthday
               24th of March, 2009                  
               25th of March, 2009                  
2. Now our Controller class obtains the user input and does the processing of the data, in our case it takes the name of the event and also the date out. 3. Our Controller transmits or notifies the Model about the results of his processing (in our case the name of the event and the date). Model reacts at this results in a way or another. In our case it inserts a new event into the events database. 4. The View reloads using indirectly(!) the updated Model. So, nor the Controller, neither the Model has the direct information about the View. In our case the page reloads with the event already set for that specific date. 5. The system waits for another user interactions which will restart this from the beginning. So this is an introductory post, there are a lot of deep things what I hope we will touch in our future examples. What's it for now. Waiting for your feedback and comments.

Monday, March 16, 2009

What is Udevi Community?

Ok, first of all what it's all about? Where from this funny name comes ? Udevi = U + dev + i = You can develop it! And the idea behind that is - we know you can do it, we know you can do a great app. And it doesn't matter the language in which you write, Python, Perl, Java, C# or Scala, and it doesn't matter the technology you are using or the application's level you are trying to build. You can develop it! You can do a simple calculator in Java or a big desktop app enabling rich user experience using JavaFX, or you can do the same thing using C# and WPF. What really matters in programming world is experience. You need to get up and realize that you can read lots of books and understand how everything underneath your code is working, but the theoretical knowledge isn't equal or doesn't compare with practical experience. While practicing, your skills become more and more sharpen, and you become more and more good at what you're supposed to be... a programmer, a developer which really can apply his vast amount of knowledge, and experience(!) to create, design, develop, produce an application/script/test/web page/etc. Ok, and what is this community about? Well, here is the most interesting point. We are trying to simulate real production environment and offer you the possibility to design an application from alpha to the release version, with all the iterations which you can see in real world: specs, conversation with clients, use cases, declaring bugs, resolving issues, trying to figure what you really want to do, talking with your team leader, creating points to discuss something specific. This is the simulation of the real world. And we do it for free, you will do it for experience, all your projects are yours, we won't use the results of these projects for our own sake. We will represent the clients, and the team leaders, you will try to make everything to match the specs. We might be able to help you, if you're:
  • a novice in programming world
  • a student which doesn't really knows how to make his first app
  • a guy trying to make something using a new technology
  • a person which has an idea, but who doesn't know how to do it
Well, and what do i need to do to apply? You need to:
  • Have a regular e-mail address (by this I mean an address where you check your mail often enough to communicate)
  • Have an IRC client (like mIRC)/ICQ/Yahoo! messenger/Skype for chating
  • Willing to achieve experience and work.
  • Have an established schedule, when you can work, when we can talk, when every kind of question could be addressed
When can I start?
  • You can start today if you want to (and I bet you want it).
  • We will be respecting your schedule and please respect ours.
I need to know more details. To find more details or to put a question contact me at monomachus85@yahoo.com or put a comment here.

Friday, March 13, 2009

Tip 001: Missing desktop icons in Windows Vista

Hi, today something happened with my Vista, and all the icons (not just Recycle Bin or My Computer ) from the desktop were missing, however they were displayed in Windows Explorer Folder, as well as the sidebar was displayed normally. I tried to google this thing and I've found a simple solution. So this are the steps you need to follow:
  1. Open Desktop item in Windows Explorer.
  2. Go to menu Tools -> Folder Options -> Tab View -> Hidden files and folders -> Select "Show hidden files and folders" -> Click "Apply" and after that "Ok" (Note: If you don't see menu Tools, press ALT tab on your keyboard)
  3. Find the file desktop.ini in your desktop folder, if there are many of these delete them all.
  4. Restart your Vista (after this step your icons should be back)
  5. Repeat step 2 to Hide hidden files and folders
That's all you got to do.