Jump to content


Check out our Community Blogs

ArekBulski

Member Since 14 Mar 2009
Offline Last Active Aug 10 2012 04:55 AM
-----

#559845 Public appeal: post your complete sources

Posted by ArekBulski on 18 June 2010 - 07:43 AM

I agree. If you only include some of the code you do not get the whole picture.It could have been something earlier in a previous section of code which we havent seen. The problem may arise if you write a windows forms application where some of the cod eis not included though...
Good thread ArekBulski


Our programming teacher uses a phrase "historical events", translation from polish is mine, to refer to side effects that happened before the place in code that we recognize as a proper place to modify some certain data. :)

Just another funny term to say "cannot see the whole picture from here"...
  • 1


#506204 Resizing controls with form: Anchor property

Posted by ArekBulski on 05 September 2009 - 09:49 AM

Welcome! This short tutorial will show you how to re-size controls, when you are re-sizing your form. For example, after clicking Maximize button, a form will get much bigger. If buttons and controls inside stay with same size... it may look strange. In case you want to change it, there it is:

Changing Anchor property of controls

Select the controls that you want to be resizing with your form. They may be buttons, listviews and textboxes, but not necessarily every one of them. Now go to the Properties panel, and select Anchor property. After clicking on that gray thing you can add or remove right and bottom anchor. Please add them.

http://forum.codecal...=1&d=1252172568
http://forum.codecal...=1&d=1252172568
http://forum.codecal...=1&d=1252172568

Now just resize your form and you will see the effect immediately. Here are example screenshots, after adding those anchors.

http://forum.codecal...=1&d=1252172636
http://forum.codecal...=1&d=1252172636

Thank you for comments

You can leave a comment any time. I hope this tutorial will be of some help for someone. :cool:

Attached Thumbnails

  • with default anchors.jpg
  • build after anchoring (2).jpg
  • build after anchoring.jpg
  • zoomin anchor property (3).jpg
  • zoomin anchor property (2).jpg
  • zoomin anchor property.jpg

Attached Files


  • 3


#505585 Reading and writing files using File methods

Posted by ArekBulski on 03 September 2009 - 08:32 AM

As Winged said. Scales icon is in the top-right corner of a post.
  • 1


#505484 Reading and writing files using File methods

Posted by ArekBulski on 03 September 2009 - 05:10 AM

Hello members! This tutorial is a bit nostalgic to me. Here is one of the few reasons why I am into .NET programming so much, instead of Java or C++ for example. I want to show you the File class, which is a small thing but makes my day nice. :)

We need a sample file...

For a start, we need some sample file to read it. I created a new console application. Then I selected the Program.cs file in the Solution Explorer panel, and switched to Properties panel. There is a property called Copy to Output Directory. I changed it to have a copy of this file in the Bin\Release\ folder. Viola, a sample file to read it, right up.

http://forum.codecal...=1&d=1251982051

Reading and writing with File class

Let's start with some simple code, the goal is to read a file. After writing "File" press Ctrl+. and click to import the System.IO namespace. Then you just need one line of code, which one, depends on your needs.

byte[] asBytes = File.ReadAllBytes("Program.cs");

string asString = File.ReadAllText("Program.cs");

string[] asLines = File.ReadAllLines("Program.cs");


Displaying the file contents

Here are screenshots of looking up the variables that contain what was read. Look at them, and decide which one of them is useful for you at the moment.

as lines.jpg

Writing data back to files

This is again what I like in .NET the most. All writing can be done in one line of code. Unless those files weight in gigabytes, your pc will not run out of memory. You can read for example setting files, or code (.cs) files this way without worrying that it will eat up your memory.

Depending on which variable or data type you want to write, you can pick one of the lines.

File.WriteAllBytes("Saved as bytes.cs", asBytes);

File.WriteAllText("Saved as string.cs", asString);

File.WriteAllLines("Saved as lines.cs", asLines);

Leave comments and enjoy your day

I hope this tutorial will be helpful or at least make your day a little bit less of writing code and more of enjoying your day. Comments and +rep are always appreciated. :)

Attached Thumbnails

  • control dot.jpg
  • copy to output directory.jpg
  • as string.jpg
  • as bytes.jpg

Attached Files


  • 1


#505441 Reading and writing files using FileStream class

Posted by ArekBulski on 03 September 2009 - 03:00 AM

Welcome members! This tutorial will show you how to read files into memory, and afterwards write them back to disk. I dedicate this tutorial to sp3tsnaz since he asked for explanation. Enjoy reading. :)

I am using Visual Studio 2008 Express Edition. The solution (by default) requires .NET Framework 3.5 to run.

Reading from FileStream to byte array

Before using FileStream class, I need to declare it's namespace. Since I never remember the namespaces I will write down "FileStream" and then a highlight will popup. Now, press Ctrl+. to open a menu, where you can add the namespace easily.

http://forum.codecal...=1&d=1251974364

Now to the meritum, sp3tsnaz thread is about merging two files after they are downloaded. What is first needed is to read them both. I create a new FileStream (for every file) and specify name and mode. There are several modes, for example: FileMode.Open will open a file or throw an exception otherwise, FileMode.Create will create a new file or override existing one. Here is code that reads two files into memory, into byte arrays.

FileStream readingFile = new FileStream("first half of file.jpg", FileMode.Open);
byte[] firstHalf = new byte[readingFile.Length];
readingFile.Read(firstHalf, 0, firstHalf.Length);
readingFile.Close();

readingFile = new FileStream("second half of file.jpg", FileMode.Open);
byte[] secondHalf = new byte[readingFile.Length];
readingFile.Read(secondHalf, 0, secondHalf.Length);
readingFile.Close();

Writing to FileStream from byte arrays

Now it's time to write some data back to disk. We could merge the byte arrays into one, but it will not be necessary to write them into a single file. Here is some code that merges them into a file.

FileStream writingFile = new FileStream("merged file.jpg", FileMode.Create);
writingFile.Write(firstHalf, 0, firstHalf.Length);
writingFile.Write(secondHalf, 0, secondHalf.Length);
writingFile.Close();

Afterwards, program will notify the user (using console) and open the folder where the source and merged files are. You can see for yourself. :)

Console.WriteLine("Will open the folder containing now.");
Console.WriteLine("Press ENTER to continue...");
Console.ReadLine();
Process.Start(Environment.CurrentDirectory);

http://forum.codecal...=1&d=1251975359

Post your comments and share some +rep

I thank you in advance for your comments. They are always very rewarding, you will see when you write your own tutorials. If you need some help, then go ahead and ask. We are a community after all. :)

Attached Thumbnails

  • sshot-8.jpg
  • sshot-6.jpg

Attached Files


  • 2


#505249 Tutorial: Playing video files with Managed DirectX

Posted by ArekBulski on 02 September 2009 - 07:40 AM

Welcome all! I wrote earlier a tutorial about playing audio files using mciSendString method. While it is a reasonable solution, I really prefer to use Managed DirectX. It gives much more control over what is happening. And besides, no crazy P/Invoke signatures are required. Therefore I decided to make a tutorial about it too, and let you be the judge. Enjoy reading. :)

Playing video with Microsoft.DirectX.AudioVideoPlayback namespace

Before you read further take this warning. If you are using Managed DirectX then not every computer will be able to run your program right away. The program will require both .NET Framework and DirectX installed. The problem arises when I add that DirectX has to be installed after .NET Framework, not before it. This is because it will also install Managed DirectX assemblies which are now among dependencies.

First thing to do is to add a reference. Open Solution Explorer and add the dependency. Then you are also going to need the same namespace. Just look at the screenshots below.

adding namespace.jpg

Playing video in control mode

This code starts playing the video in a Panel that I put into the form. I did not make an open dialog, though. I think just a Textbox will do.

Video video = new Video(FilenameTextbox.Text);
video.Owner = panel1;
video.Play();

[ATTACH]2063[/ATTACH]

Playing video in external window mode

This code starts playing in an external window. If you close that window then audio will still be playing. To stop playing there is the Video.Stop method.

Video video = new Video(FilenameTextbox.Text);
video.Play();

[ATTACH]2064[/ATTACH]

Playing video in fullscreen mode

The last piece of code will play in fullscreen mode. Again, pressing Alt+F4 will close the video but audio will go on.

Video video = new Video(FilenameTextbox.Text);
video.Fullscreen = true;
video.Play();

[ATTACH]2062[/ATTACH]

Author thanks you for comments

I hope you enjoyed reading my tutorial. If it was helpful or useful then even more so. Feel free to post a comment or drop me some +rep. I thank you in advance. :)

Attached Thumbnails

  • three modes (3).jpg
  • three modes.jpg
  • three modes (2).jpg
  • adding reference.jpg

Attached Files


  • 2


#505155 Tutorial: Playing MP3 files with C#

Posted by ArekBulski on 01 September 2009 - 11:19 PM

Hello to everyone! This tutorial will explain how to play MP3 files as songs, without any external assemblies or SDKs. I dedicate this tutorial to Thomas Morgan, a new but not unwelcomed member of our forum. And to all who seek the power of .NET. :)

There are several technologies available

There are multiple approaches to playing audio multimedia as it seems. I could try to embed a Windows Media Player using one of the SDKs. But that would be something completely new to me. I decided to leave it for another time.

I could use Managed DirectX, too. This one is very powerful and easy to use, using the AudioVideoPlayback namespace. I very much like Managed DirectX, but not every system will be able to run my program. You need to install both .NET Framework and DirectX in correct order to be able to run it. This becomes a problem, from wider perspective.

This tutorial will be using mciSendString WinAPI function, through P/Invoke. Therefore it won't run on Mono. Honestly I hate WinAPI functions, but if that is the easiest way then let's do it.


Playing MP3 songs using mciSendString function

http://forum.codecal...=1&d=1251875231

The whole code is just three methods long. Notice that user has to select a song to be able to press Play button. And he needs to play it to be able to stop it. It will easily prevent user from clicking buttons he should not click yet. Here is a simple file selection dialog code:

if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
    FilenameTextbox.Text = openFileDialog1.FileName;

    button3.Enabled = true; //So you dont play no file. lol
}

Then we need to add a P/Invoke declaration to main form's class. Afterwards it is just calling the method few times. If Windows Media Player is already playing a song then they will overlap. No exception but what noise heh. Here is the P/Invoke and the code playing and stopping the song:

[DllImport("winmm.dll")]
private static extern long mciSendString(string strCommand, StringBuilder strReturn, int iReturnLength, IntPtr hwndCallback);


private void button3_Click(object sender, EventArgs e)
{
    mciSendString("open \"" + FilenameTextbox.Text + "\" type mpegvideo alias MediaFile", null, 0, IntPtr.Zero);
    mciSendString("play MediaFile", null, 0, IntPtr.Zero);

    button3.Enabled = false;
    button2.Enabled = true;
}

private void button2_Click(object sender, EventArgs e)
{
    mciSendString("close MediaFile", null, 0, IntPtr.Zero);

    button2.Enabled = false;
    button3.Enabled = true;
}

If you are still not satisfied then here is an additional joke. If you select a video then a new window will pop up and display it. Now I'm laughing at myself, lol.

http://forum.codecal...=1&d=1251875810

There is nothing as worthy as comments

Thanks to everyone reading my tutorial. Any comments and +rep are welcomed. Hope you enjoyed reading. :)

Attached Thumbnails

  • playing video (2).jpg
  • running program (2).jpg

Attached Files


  • 3


#504996 Writing SQL commands in C# - Part 3 - Editing records and maintainable dedica...

Posted by ArekBulski on 01 September 2009 - 11:42 AM

Welcome all! My previous two turorials about inserting, reading and deleting records were so welcomed that I decided to write another one. If you have read them then let's assume we already have a solution with a database attached. We also got few records in a table.

Today however, I will focus on something more important than working code. I want you to see how awesome prototypes and dedicated classes are. First one will give us immediate feedback about how good the code is, second one will be a very well designed code that can be maintained over ages. :)

Editing existing records: using SQL UPDATE statement

Here is a piece of code that executes yet another SQL statment. It will modify as many records as you want, only the conditions you specify will make which records are changed. Warning: If you don't specify that WHERE clause then it will eat all your data in the table. I would rather not want to make a mistake like this and mess up my company database.

I just copied this code from the code above, and modified one line. I strongly believe that it is a very good way to make a prototype and immediately know does it work or not. That is what a prototype is for.

SqlConnection connection1 = new SqlConnection(
    Properties.Settings.Default.some_numbersConnectionString);

SqlCommand insertCommand = new SqlCommand(
    "UPDATE NumbersTable SET number = 1003, description = 'changed my mind' WHERE number = 1002",
    connection1);

connection1.Open();
insertCommand.ExecuteNonQuery();
connection1.Close();

MessageBox.Show("Records 1002s have been changed to 1003s. Please check your table data again. :)");

http://forum.codecal...=1&d=1251893547

Structure your code: dedicated class for database operations

As you see here, most of SQL operations are very schematic (even reading). They are copied again and again and I just change one line that carries the SQL statment. Look at the full code and think about is this something you would like show to your employers. My honest opinion is that this code is too redundant. Every method alone works great. But making a new connection for every query seems wrong.

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

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void InsertButton_Click(object sender, EventArgs e)
        {
            SqlConnection connection1 = new SqlConnection(
                Properties.Settings.Default.some_numbersConnectionString);

            SqlCommand insertCommand = new SqlCommand(
                "INSERT into NumbersTable values (1002, 'will delete this one')",
                connection1);

            connection1.Open();
            insertCommand.ExecuteNonQuery();
            connection1.Close();

            MessageBox.Show("Record 1002 inserted. Please check your table data. :)");
        }

        private void ReadButton_Click(object sender, EventArgs e)
        {
            SqlConnection connection1 = new SqlConnection(
                Properties.Settings.Default.some_numbersConnectionString);
            SqlCommand selectCommand = new SqlCommand(
                "SELECT * FROM NumbersTable",
                connection1);

            connection1.Open();
            SqlDataReader reader = selectCommand.ExecuteReader();
            string fetchedRecords = string.Empty;

            while (reader.Read() == true)
            {
                fetchedRecords += "Record: (number) " + reader[0] + " (descriptio) " + reader[1] + " \n";
            }

            connection1.Close();
            MessageBox.Show("Found following records: \n \n" + fetchedRecords);
        }

        private void DeleteButton_Click(object sender, EventArgs e)
        {
            SqlConnection connection1 = new SqlConnection(
                Properties.Settings.Default.some_numbersConnectionString);

            SqlCommand insertCommand = new SqlCommand(
                "DELETE NumbersTable WHERE number = 1002",
                connection1);

            connection1.Open();
            insertCommand.ExecuteNonQuery();
            connection1.Close();

            MessageBox.Show("Records 1002s deleted. Please check your table data again. :)");
        }

        private void EditButton_Click(object sender, EventArgs e)
        {
            SqlConnection connection1 = new SqlConnection(
                Properties.Settings.Default.some_numbersConnectionString);

            SqlCommand insertCommand = new SqlCommand(
                "UPDATE NumbersTable SET number = 1003, description = 'changed my mind' WHERE number = 1002",
                connection1);

            connection1.Open();
            insertCommand.ExecuteNonQuery();
            connection1.Close();

            MessageBox.Show("Records 1002s have been changed to 1003s. Please check your table data again. :)");

        }

    }
}

Now the suprising part. I really think this way of coding is very *good*. You might ask "is this a good practice? this is **". And I would agree. This code is a prototype. Making it took me less time (also because I copied and copied) so it saved me time on designing something that I would change later anyway. It also gave me a real insight into how my code should look like.

What I would like to do now, is put all our database operations into a dedicated class. We already have a *working* prototype, shall we make a second *maintainable* solution?

http://forum.codecal...=1&d=1251833741

private void button1_Click(object sender, EventArgs e)
        {
            string message = "Here are logs for all operations made: \n";

            message += "Adding a 1002 record twice. \n";
            DatabaseOperations.ExecuteSqlStatement("INSERT into NumbersTable values (1002, 'will delete this one')");
            DatabaseOperations.ExecuteSqlStatement("INSERT into NumbersTable values (1002, 'will delete this one')");


            message += "Reading all records present: \n";
            SqlDataReader reader = DatabaseOperations.ExecuteSqlReader("SELECT * FROM NumbersTable");
            while (reader.Read() == true)
                message += "  Record: (number) " + reader[0] + " (description) " + reader[1] + " \n";
            reader.Close();


            message += "Editing all 1002 records into 1003s. \n";
            DatabaseOperations.ExecuteSqlStatement("UPDATE NumbersTable SET number = 1003, description = 'changed my mind' WHERE number = 1002");


            message += "Reading all records present (again): \n";
            reader = DatabaseOperations.ExecuteSqlReader("SELECT * FROM NumbersTable");
            while (reader.Read() == true)
                message += "  Record: (number) " + reader[0] + " (description) " + reader[1] + " \n";
            reader.Close();


            MessageBox.Show(message);
        }

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

namespace WindowsFormsApplication1
{
    /// <summary>
    /// This class performs the database operations. Pass on SQL statements and 
    /// it will just return the data for you. 
    /// </summary>
    public static class DatabaseOperations
    {
        /// <summary>
        /// This connection will do everything. Better to not throw connections 
        /// on left and right.
        /// </summary>
        private static SqlConnection connectionForAllOperations;

        /// <summary>
        /// This method executes any non-reader command. Use it for INSERT, UPDATE 
        /// and DELETE. It does not work for SELECT, sorry.
        /// </summary>
        public static void ExecuteSqlStatement(string sql)
        {
            if (connectionForAllOperations == null)
            {
                /// The connection will be opened only once, just before first operation.
                connectionForAllOperations = new SqlConnection(
                    Properties.Settings.Default.some_numbersConnectionString);
                connectionForAllOperations.Open();
            }

            SqlCommand anyCommand = new SqlCommand(sql, connectionForAllOperations);
            anyCommand.ExecuteNonQuery();
        }

        /// <summary>
        /// This method executes a reader command. Use for SELECT queries. 
        /// </summary>
        public static SqlDataReader ExecuteSqlReader(string sql)
        {
            if (connectionForAllOperations == null)
            {
                /// The connection will be opened only once, just before first operation.
                connectionForAllOperations = new SqlConnection(
                    Properties.Settings.Default.some_numbersConnectionString);
                connectionForAllOperations.Open();
            }

            SqlCommand anyCommand = new SqlCommand(sql, connectionForAllOperations);
            SqlDataReader anyReader = anyCommand.ExecuteReader();
            return anyReader;
        }

    }
}

I would like to take an opportunity to make a breaking point in the way coding is conducted. I think every manager would say that I should skip the first ** and proceed to working on the solution, probably to save time. I would totally disagree here. Here are my arguments.

I made a prototype really quickly, almost in no time. That is because I could do as I want and no code quality was needed. I also made the solution really quickly. You might not believe me but I copied most of the stuff and just renamed and refactored it. At the same time...

Class design is completely new. I eliminated the big flaws that were existing in the prototype. Therefore the solution is very maintainable. And that is worth some employees time, sweat and earnings in the future.

Also building a prototype gave me a real insight into how SQL queries work. That knowledge is very important when building a solution (first or not), as much as when solving bugs. It will also pay off when implementing all the details that a solution would require.

The manager could say: "Then design the software well in the beginning". Of course it sounds like a great idea. But how will I design something I never saw on my own eyes so far? I am pretty sure that the folks at NASA really took their time to design their first space rockets, those ones with higher oxygen level inside. They had the design, but not experience. Let the astronauts rest in peace.

Attached Thumbnails

  • reading records.jpg
  • operations logs.jpg

Attached Files


  • 2


#504473 Writing SQL commands in C# - Part 2 - Reading and deleting records

Posted by ArekBulski on 31 August 2009 - 01:40 AM

Welcome all! This is a second part of my SQL in C# tutorial series. If you are interested in writing INSERT commands then take a look at part 1: INSERT into table. In this tutorial I would like to show you how to read several records by using a SELECT statement, and how to delete records by using DELETE statement. Enjoy this short tutorial. :)

Reading records with SQL SELECT statment: using SqlDataReader class

So, so far we created a database, with a table for numbers and descriptions, and added a record. Remember, table NumbersTable has two columns, numbers and description. During insertion and deletion column names are not used, you need only their order. So when you write some code, take a look again at the table. If you make it wrong then god help you with debbuging.

SqlConnection connection1 = new SqlConnection(
    Properties.Settings.Default.some_numbersConnectionString);

SqlCommand insertCommand = new SqlCommand(
    "INSERT into NumbersTable values (1002, 'will delete this one')",
    connection1);

connection1.Open();
insertCommand.ExecuteNonQuery();
connection1.Close();

MessageBox.Show("Record inserted. Please check your table data. :)");

But a database is useless if you cannot use the data you inputed there, right? After all this is why created a database in the first place. So, let us read all the records from our table. While you can use some conditions to select only several records, it is not necessary in this case.

For a start you need a SqlConnection and SqlCommand classes. They are required for any SQL statement. This time however, we could also use a SqlDataReader class. It fetches the received data and lets you access them one record at a time.

After calling reader = selectCommand.ExecuteReader(), you are able to access your records one-by-one. By turns, call reader.Read() while checking are there any more records to read. If it returns false then you are done with reading. Then process the current record by reading reader[0], reader[1] and so on. Again, field order is important. Try hard to avoid making mistakes here.

SqlConnection connection1 = new SqlConnection(
    Properties.Settings.Default.some_numbersConnectionString);
SqlCommand selectCommand = new SqlCommand(
    "SELECT * FROM NumbersTable",
    connection1);

connection1.Open();
SqlDataReader reader = selectCommand.ExecuteReader();
string fetchedRecords = string.Empty;

while (reader.Read() == true)
{
    fetchedRecords += "Record: (number) " + reader[0] + " (descriptio) " + reader[1] + " \n";
}

connection1.Close();
MessageBox.Show("Found following records: \n \n" + fetchedRecords);

http://forum.codecal...=1&d=1251710678

Deleting several records: SQL DELETE statement

Well, deletion is as easy as a pie. There is nothing more than the short code below. Note that you can use several conditions, but ntext and varchar field types do not play with equal-to operator (=). That is why the other version is commented out.

SqlConnection connection1 = new SqlConnection(
    Properties.Settings.Default.some_numbersConnectionString);

SqlCommand insertCommand = new SqlCommand(
    "DELETE NumbersTable WHERE number = 1002",
    //"DELETE NumbersTable WHERE number = 1002 AND description = 'will delete this one'",
    connection1);

connection1.Open();
insertCommand.ExecuteNonQuery();
connection1.Close();

MessageBox.Show("Record 1002 deleted. Please check your table data again. :)");

http://forum.codecal...=1&d=1251711030

Thank the author, share some reputation points

I would like to thank everyone, especially Jordan and Siten, that were supporting me. Writing tutorials is a hard work. If you want to leave a comment or +rep my post then go ahead. I thank you in advance. :)

Attached Thumbnails

  • sshot-4.jpg
  • sshot-6.jpg

Attached Files


  • 4


#503756 Writing SQL commands in C# - Part 1 - INSERT into table

Posted by ArekBulski on 29 August 2009 - 02:35 AM

Welcome all! Hereby I would like to present you a little prototype of mine. This is a program showing that you can indeed write SQL commands using C#. Try out the code below, and if you are interested in reading further tutorials... please leave me a comment and some +rep. ;)

Connecting or creating a database

For a start let's run Visual Studio 2008. I also installed SQL Express which runs locally. If you want to connect remotly using TCP/IP then we can work on that, too. But I do not do that in this tutorial, part 1.

sshot-2.jpg

Now, before touching any database you need to do three things. For one, you need to create a database. In the Database Explorer click-right and click Add Connection. There you select a database provider (SqlClient is default) and a database file. I selected a new database file, to create a new database. Go ahead and create your own database, I will wait.

sshot-5.jpg

For two, you need to create a table. Again in the Database Explorer select the database, then Tables folder, then right-click and click Add New Table. Now go ahead and put few columns there, along with their types. I used types int and ntext. Better avoid other types, like DateTime . Then save the table, pick your own name for it. Go ahead.

sshot-8.jpg

For three, you need to make a connection string. This time use the Data Sources panel and right-click, then click Add New Data Source. The wizard is pretty straightforward. Select a Database. It should propose you the database file, that you selected earlier.

Warning: It will ask you do you want to copy the database into your project. If you click yes then it will restore the database at every run. I strongly suggest to click No. Otherwise you will loose your records all too often.

Next page will ask to save a connection string. You are going to need it in the code. Last page will ask you to import tables. I suggest you just import them all and sort it out later.

sshot-15.jpg


Writing SQL command: INSERT into table

Here we are. The precious moment of truth. Let us insert a nice record into our new table. Here is a simple piece of code that does that. Notice that you are going to include an import directive, use two classes, and that is about it.

The namespace System.Data.SqlClient contains the two classes, SqlConnection and SqlCommand that will do the whole work. As for the SQL language itself, there is some nice MSDN documentationfor that.

using System.Data.SqlClient;


SqlConnection connection1 = new SqlConnection(
Properties.Settings.Default.some_numbersConnectionString);

SqlCommand insertCommand = new SqlCommand(
"INSERT into NumbersTable values (128, 'as in 128 bits equal 16 bytes')",
connection1);

connection1.Open();
insertCommand.ExecuteNonQuery();
connection1.Close();

MessageBox.Show("Record inserted. Please check your table data. :)");


Here are some screenshots for the code, and running. Sorry, I could not resist to add some.

sshot-19.jpg


Looking at the actual database records

So how do you know that the INSERT command worked? Well, I do not mention how to pull out the records from a database, yet, thus you need to look up the database itself. Thankfully VS2008 has a nice feature. In the Database Explorer right-click the table and click Show Table Data. You see... all your inserts are okay. Nothing else to do, but to save the project.

[ATTACH]1988[/ATTACH]

All comments, critisism and +rep are welcomed. Go ahead and reply to me! ;)

Attached Thumbnails

  • sshot-21.jpg
  • sshot-18.jpg
  • sshot-17.jpg
  • sshot-13.jpg
  • sshot-14.jpg
  • sshot-12.jpg
  • sshot-11.jpg
  • sshot-10.jpg
  • sshot-6.jpg
  • sshot-3.jpg
  • sshot-1.jpg

Attached Files


  • 2


#499082 C# Tutorial: Cropping images and bitmaps

Posted by ArekBulski on 14 August 2009 - 11:40 AM

Introduction for curious people

I got a nice homework assignment from Siten, to make a program that crops images. It seemed easy at first, but then ...proven otherwise. Therefore let me show you some code that "cuts margins off images", or how Photoshop names it: crops images. :)

Cropping an image (or bitmap)

First of all, you can only crop a Bitmap class. If you have an Image class, you will have to transform it to a Bitmap object. This is my first code statement.


Bitmap croppedBitmap = new Bitmap(pictureBox1.Image);


Cropping a Bitmap may seem hard to implement, probably because it is being done by cloning... yes, Clone() method takes optional arguments that can be smaller than original image. This is second code statement.

My margins are provided by NumericUpDown controls, therefore I had to convert them from double to integer, which adds these "(int)" explicit conversions.


croppedBitmap = croppedBitmap.Clone(
new Rectangle(
(int)LeftMargin.Value, (int)TopMargin.Value,
(int)croppedBitmap.Width - (int)LeftMargin.Value - (int)RightMargin.Value,
(int)croppedBitmap.Height - (int)TopMargin.Value - (int)BottomMargin.Value),
System.Drawing.Imaging.PixelFormat.DontCare);


To show the results, my cropped image is put back into picturebox1. This is third code statement.


pictureBox1.Image = croppedBitmap;


Output to show that it works

Here are screenshots showing two subsequent cropping done on a picture made by NASA.

sshot-3.jpg

Code behind this prototype

You can open the whole solution and play with it as you want. Also you can run a compiled exe without using Visual Studio, just look into Bin\Release\ folder.

Solution code: [ATTACH]1909[/ATTACH]

With regards to Siten, my old friend...

Attached Thumbnails

  • sshot-1.jpg
  • sshot-2.jpg

Attached Files


  • 1


#477003 Please help me I have a very big problem!!

Posted by ArekBulski on 25 June 2009 - 11:39 PM

Indeed, Winged. This is why I gave a hint to look into Wikipedia. Mathematix, you earned some -rep for yourself. Giving wrong (unconfirmed) intel is as good as kicking someone's face.

See some pseudocode: Leap year - Wikipedia, the free encyclopedia
  • -1


#473017 Mkbundle: bundle Mono with applications

Posted by ArekBulski on 15 June 2009 - 03:45 AM

Mkbundle: bundle Mono with your applications

Did you ever wonder why you need .NET Framework or Mono installed to run your program? Well, it would be much more handy if you could distribute your applications without nagging your clients to install additional frameworks, is it not? So here we are. Lets bundle a .NET-based application with Mono, so you don't need Mono, or .NET installed to run it. :)

Prepare an environment

First you need to install newest Mono and Cygwin. Installing Mono is very straightforward so you cannot screw up anything. When you start installing Cygwin, go into Full view, then please include 4 additional packages. These are: gcc, mingw, mingw-zlib and zlib.

Now you need a command prompt. Both Mono and Cygwin create shortcuts for command prompts on your desktop, but you need to combine them into one. Here is a batch that does it for me. You may need to change it, if you have other Mono version for example.

echo Mono version 2.4 Build 6
echo Prepending 'C:\PROGRA~1\Mono-2.4\bin' to PATH
PATH=C:\PROGRA~1\Mono-2.4\bin;%PATH%

chdir C:\cygwin\bin
bash --login -i

Bundle an application with Mono

So we are now in a command prompt, running this Cygwin mode. Notice that this is not a DOS prompt anymore, and "dir" won't work anymore. To list files use linux command "ls". The folder you are browsing now is like the one below. Arek is a username.
C:\cygwin\home\Arek

Browse to this folder with your explorer. Now you copy 2 files into this folder. 1st is your application exe and 2nd is the file Mono.dll (2MB) that you can find in your Mono folder.
C:\Program Files\Mono-2.4\bin

For some reason the whole procedure does not work with long file names, so rename your application exe. It should comply with this old DOS 8.3 naming.

Lets go back to command prompt. You need only 1 command to bundle your application, and here is some explanation.

mkbundle is a program within Mono package | -o Bundled1.exe specifies how the Mono-bundled exe will be named | Winform1.exe says what will be included, Mono libraries will be included anyway | --deps is necessary although I am not sure what it does | -z will compress the output exe a lot

mkbundle -o Bundled1.exe Winform1.exe --deps -z

So now you got your Bundled1.exe, which contains your own app along with Mono itself. You should not need Mono nor .NET to run it. Notice that it will be 4MB or more in size. Those bundled exes are not lightweight.

Thank the author for his work

If you enjoyed reading my tutorial, please +rep me. You can also send me a cookie. :)
  • 5


#463427 Coder Battle #3: ASCII Encryption -- RESULTS!!!!

Posted by ArekBulski on 01 June 2009 - 02:21 AM

Hah, I am just teasing you, you know. Winged and Amrosama already +repped me. :)
  • 1


#462748 Coder Battle #3: ASCII Encryption -- RESULTS!!!!

Posted by ArekBulski on 28 May 2009 - 12:53 PM

Thank you everyone! I am so proud of myself right now! :)
  • 2




Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download