Showing posts with label Data. Show all posts
Showing posts with label Data. Show all posts

Friday, October 26, 2012

A simple prize bond manager: old technology still works!

Introduction

The story begin with a simple problem, my father-in-law having some problem with his prize bonds. He has several prize bonds and each quarter government publish the prize bond lottery draw and he had to take each bond then go through the numbers. And it became hectic job for him.

Few days ago,  in a family dinner he told me about his problem, and asked me can I make a simple program so that his problem can be resolved. I kind of smiled and told him that I would be able to write something for him. Last weekend I sit and wrote some thing for him. Then I thought lets write an article about it, should be fun!.

My problems:

  1. It needs to be very simple.
  2. I can’t force him to use advance technology.
  3. Need to have some backup of data.
  4. Easy deployable.

It needs to be very simple

Decided to keep it very simple, so no login what so ever. One Main Screen where every thing is listed. A data add screen. And a simple match bond number screen to finding winning numbers. One interesting thing is that my father-in-law keep buying bonds for all the family members. so need to back up the data and ability to load backed up data.

I can’t force him to use advance technology

After little thought I decided to choose old technologies, because my client knows computer but i guess fancy advance technology might scare him off and my client will runway. And I believe it or not he use “windows xp” so what ever available with windows update.

Need to have some backup of data

Should be simple pretty simple steps to add delete and modify data. In case  user manage to screw thing up there should be a simple process with which he can backup the data and also restore data. Of course we have SQL Server and Enterprise manager to do that, but we don’t what clients to mange all those things. So I better use simple xml to generate back up.

Easy deployable

Important part, I don’t want to install anything in my pc beside the software, second the steps should be damn easy. kind of one client installer.

First thing First

Before writing any code I setup a open source project in github to keep my code. It’s a open source only because I want people to some how criticize me about my code and learn some thing out of it. Created my visual studio project. Now I have VS2012, and VS2010, I chose “VS2010” and as framework I chose “.net framework 2.0”.

Below the github project location is given. You guys can download and see what’s there if you want.

https://github.com/munnaonc/PrizeBondManager.git

Win forms 2.0 , .net framework 2.0 project

Alright, what ever I thought just gave me another shot to use some old technology, should be fun. After all the necessary code the solution explorer looks like the below screen shot.

image

Figure: Initial Project Structure in Solution explorer

To keep the data I have added a Microsoft SQL Server Compact Database also known as “.sdf” database named BondDB.sdf. Created a single table. In below screen shot the table structure is given.

image

Figure: Initial Project Structure in Solution explorer

For data retrieve and saving used one of the oldest technology that is typed dataset. Below screenshot gives you an idea of that work. In the dataset we have a custom query for the dataset named “GetDataBySerial” which returns the prize bond with serial number.

image

Figure: Initial Project Structure in Solution explorer

Wrapping Up the Coding

I added main feature as CRUD of Bonds, Backup Data, Load Data and of course Match a bond number, to find out if we have a winner or not. 

Without any user interface brush-up the application looks like the bellow screen shot. pretty bad right. We would make it presentable in future i guess, for the time being the idea is to get the application to my client quickly.

image

Figure: Main Application First Look

Data Layer codes for CRUD is given bellow

using System;
using System.Collections.Generic;
using System.Data;
using PrizeBonds.BondDBDataSetTableAdapters;

namespace PrizeBonds.Objects
{
public class DAL
{
public List<Bond> GetList()
{
var tBondTableAdapter = new t_bondTableAdapter();
var tBondDataTable = new BondDBDataSet.t_bondDataTable();
tBondTableAdapter.Fill(tBondDataTable);
var dataRows = tBondDataTable.Select();
return GetBonds(dataRows);
}

private static List<Bond> GetBonds(IEnumerable<DataRow> dataRows)
{
var bonds = new List<Bond>();
foreach (DataRow row in dataRows)
{
try
{
var bond = new Bond
{
Id = (Int64)row["ID"],
Serial = (Int64)row["Serial"],
Owner = row["Owner"].ToString(),
CreatedDate = (DateTime)row["CreatedDate"],
ModifiedDate = (DateTime)row["ModifiedDate"]
};
bonds.Add(bond);
}
catch (Exception exception)
{
exception.ToString();
}
}
return bonds;
}

public void AddBond(Bond bond)
{
var tBondTableAdapter = new t_bondTableAdapter();
tBondTableAdapter.Insert(bond.Serial, bond.Owner, bond.CreatedDate, bond.ModifiedDate);
}

public void DeleteBond(long id)
{
var tBondTableAdapter = new t_bondTableAdapter();
tBondTableAdapter.Delete(id);
}

public List<Bond> GetBondBySerial(long serial)
{
var tBondTableAdapter = new t_bondTableAdapter();
var bondDataTable = tBondTableAdapter.GetDataBySerial(serial);
if (bondDataTable.Rows.Count > 0)
{
return GetBonds(bondDataTable.Select());
}
return null;
}

public void UpdateBond(Bond bond)
{
var tBondTableAdapter = new t_bondTableAdapter();
var tBondDataTable = new BondDBDataSet.t_bondDataTable();
tBondTableAdapter.Fill(tBondDataTable);
var tBondRow = tBondDataTable.FindByID(bond.Id);
tBondRow.Owner = bond.Owner;
tBondRow.Serial = bond.Serial;
tBondRow.ModifiedDate = bond.ModifiedDate;
tBondTableAdapter.Update(tBondRow);
}
}
}


Created single object to manage and the application, named “bond”


using System;

namespace PrizeBonds.Objects
{
[Serializable]
public class Bond
{
public long Id { get; set; }
public long Serial { get; set; }
public string Owner { get; set; }
public DateTime CreatedDate { get; set; }
public DateTime ModifiedDate { get; set; }
}
}


 


Add, Update and match Bond serial


Below a very simple Add Bond window code is given. Its a win form window with tool window border style and displayed as a modal dialog.


image


same window is displayed with some property modified, to update the data also.


public void SetData(Bond dataBoundItem)
{
_updateBondCandidate = dataBoundItem;
txtOwner.Text = _updateBondCandidate.Owner;
txtSerial.Text = _updateBondCandidate.Serial.ToString(CultureInfo.InvariantCulture);
}


below the update window is given.


image


Below match bond window is given.


image


Code for Add update bond



private void UpdateBond()
{
_updateBondCandidate.Owner = txtOwner.Text;
_updateBondCandidate.Serial = Convert.ToInt64(txtSerial.Text);
_updateBondCandidate.ModifiedDate = DateTime.Now;

var dal = new DAL();
dal.UpdateBond(_updateBondCandidate);
this.Close();
}

private void AddNewBond()
{
var bond = new Bond
{
Serial = Convert.ToInt64(txtSerial.Text),
Owner = txtOwner.Text,
CreatedDate = DateTime.Now,
ModifiedDate = DateTime.Now
};
var dal = new DAL();
dal.AddBond(bond);
this.Close();
}






code for match bond


private void btnMatchBond_Click(object sender, EventArgs e)
{
if (ValidData())
{
var dal = new DAL();
var bonds = dal.GetBondBySerial(Convert.ToInt64(txtSerial.Text));
if (bonds == null)
{
lblMessage.Text = @"No match found!";
lblMessage.ForeColor = System.Drawing.Color.Red;
}
else
{
lblMessage.Text = @"Success! match found! You are a winner!";
lblMessage.ForeColor = System.Drawing.Color.Green;
}
}
}


private bool ValidData()
{
if (string.IsNullOrEmpty(txtSerial.Text))
{
ShowValidSerialMessage();
return false;
}
char[] charArray = txtSerial.Text.ToCharArray();
foreach (var val in charArray)
{
if (char.IsDigit(val) == false)
{
ShowValidSerialMessage();
return false;
}
}
if (txtSerial.Text.Length != 7)
{
ShowValidSerialMessage();
return false;
}
return true;
}

private void ShowValidSerialMessage()
{
MessageBox.Show(@"Please enter 7 digit valid Prize Bond Serial");
txtSerial.Focus();
}

private void btnCancel_Click(object sender, EventArgs e)
{
Close();
}

private void txtSerial_KeyPress(object sender, KeyPressEventArgs e)
{
char keyChar = e.KeyChar;
if (keyChar.Equals('\r'))
{
btnMatchBond_Click(sender,new EventArgs());
}
}



Save and Load Bond Data


For saving and loading data used old serialization concept. Below the code for saving and loading bond data is given.


using System.Windows.Forms;

namespace PrizeBonds.Objects
{
public class BackUpManager
{
public void LoadRule()
{

// Configure open file dialog box
var dlg = new OpenFileDialog { FileName = "Prize Bond Manager",
DefaultExt = ".pbm", Filter = @"Prize Bond Manager Files (.pbm)|*.pbm" };

// Show open file dialog box
var result = dlg.ShowDialog();

// Process open file dialog box results
if (result == DialogResult.OK)
{
// Open document
var filename = dlg.FileName;
var serializer = new Serializer();
var deSerializeObject = serializer.DeSerializeObject(filename);
var bonds = deSerializeObject.Bonds;
var dal = new DAL();
foreach (var bond in bonds)
{
dal.AddBond(bond);
}
}
}

public void SaveRule()
{
var dal = new DAL();
var bonds = dal.GetList();
if (bonds.Count == 0)
{
const string message = @"You do not have any bonds to Save, thus I am unable "
+ @" to save any bonds. Please add some bonds before Saving";
MessageBox.Show(message);
return;
}

var dlg = new SaveFileDialog { FileName = "Prize Bond Manager",
DefaultExt = ".pbm", Filter = @"Prize Bond Manager Files (.pbm)|*.pbm" };

// Show save file dialog box
var result = dlg.ShowDialog();

// Process save file dialog box results
if (result == DialogResult.OK)
{
// Save document
string filename = dlg.FileName;
var serializer = new Serializer();
var objectToSerialize = new ObjectToSerialize { Bonds = bonds };
serializer.SerializeObject(filename, objectToSerialize);
}
}
}
}



In future release I would try to improve the look and field of the application. since the purpose of the application is only to match and keep data. And of course the application will be used only in once a month so investing huge time to make it more stunning won't be  a good idea., but still will invest some amount of time.


Conclusion


In this short article we have built a small application for managing prize bond with some of the old technology exists in ms world. Hope you would like it. Please drop comment if you like it and don’t forget suggest me improvement tips.

Friday, October 19, 2012

SDF Database: Re Create objects if you missed setting primary key as identity

I was developing a demo application, as database I chose to add “.sdf” local database file. I added some columns and set primary key. Some how I forgot to set the identity property of primary key.

Went back to the same interface and try to modify the table schema and set identity property. End up with the following error.

image

I thought setting some property for instance “Prevent Saving changes that require table re-creation. In Options->Database Tools-> Table and Database Designers will do the job.

image

But it didn’t, Later what I did is very bad and didn’t feel any good about it. I cleared the table. Deleted the old ID field. And re-create the same ID column with right property again.

I would appreciate if any body help me on this issue to edit a primary key identity property without deleting or clearing the data.

Thursday, January 5, 2012

Firebird a true open source database

I  Spent a lot of time online searching for a embedded database that can be used with any kind of application regardless of platform and technology. And you all can guess that SQLite is the best option for the purpose. But there are some other options as well for instance firebird.  This firebird has also server package and has sp and trigger facility with is a big plus. Bellow a short description is given and taken from there home site.

image

“Firebird is a relational database offering many ANSI SQL standard features that runs on Linux, Windows, and a variety of Unix platforms. Firebird offers excellent concurrency, high performance, and powerful language support for stored procedures and triggers. It has been used in production systems, under a variety of names, since 1981.
The Firebird Project is a commercially independent project of C and C++ programmers, technical advisors and supporters developing and enhancing a multi-platform relational database management system based on the source code released by Inprise Corp (now known as Borland Software Corp) on 25 July, 2000.
FREE LIKE A BIRD. Anyone can build a custom version of Firebird, as long as the modifications are made available, under the same IDPL licensing, for others to use and build on.
FREE LIKE FREE BEER. No fees for download, registration, licensing or deployment, even you distribute Firebird as part of your commercial software package.
Firebird's development depends on voluntary funding by people who benefit from using it. Funding options range from donations, through Firebird Foundation memberships to sponsorship commitments.
Choosing Firebird and saving or making money by your choice? Show your appreciation and encouragement by contributing money in proportion to these benefits.”

No database is popular unless you have good management studio and administration facility for developers as well as database administrators. But unfortunately after spending few minutes in google I found no good free management studio for it. “EMS SQL Manager for InterBase/Firebird” is a commercial and trial ware that can be used to administer that firebird database. Bello a screen shot is given.

image

But we can use ado.net provider and leverage visualstudio data feature to work with firebird easily. Hope to write more about firebird in future.

References

http://www.firebirdsql.org/en/start/#get-started

Thursday, May 6, 2010

Data compare in visual studio 2010

Visual studio 2010 ultimate has many interesting and life saving feature, but let’s face it we can not put together in a single blog, rather today I am going to show you an interesting feature regarding data synchronization. Yes I am talking about “Data Compare”. In one of my blog I have put down few information about Schema comparison,

image

You can lunch the above window from Data Menu from top menu, after selecting both source database and target database just click on next, in this next screen you can select the database object types “Table” and “View”, select your desired object and then click on finish. The process would take few seconds to finish.

After the process is finished you would be presented with a screen like the bellow window.

image

After that you can select the command that you would like to perform from quick toolbar of visual studio 2010.

image

You can choose to sync directly, by pressing the “write updates” command or perhaps “export to editor” to examine and execute the generated query.

Hope this helps to some one. Until next time. Happy programming.

Thursday, April 8, 2010

Using Schema Comparison in visual studio 2010

Introduction

I am happy to share one of the interesting feature of Microsoft visual studio 2010, and the feature is under data named “Schema Comparison”. I am sure every now and then we need two pretty important stuff regarding database while deploy or test deploy our application’s data and those are

  • Data Synchronization
  • Schema Synchronization

In this particular post we are going to take a look at the schema comparison stuff. I am sure we have used some kind of schema comparison tool before, I my self is a big fan of red get sql belt, which has few really life saving tools and support to ease our life while working with data, but today I am bringing this because visual studio 2010 have same schema comparison option.

Process of Schema Comparison

To compare the database schema you need at least two database, this sounds stupid but still mention it you can select same data source in both target and source, which does not make sense. Any way to lunch the new schema comparison, go to top menu and find “Data” under data we have “Schema Compare” Sub menu under that we have a third level menu named “New Schema Comparison”. After selecting the menu it will bring up a new window where you would define the target database and source database. Bellow a screen shot is been given.

image

Figure: Schema Comparison Source selection

Please select both source and target database and click on “OK” to start the process after the process is been finish you would see a window like the bellow screen shot on visual studio. its simply the result and mismatch list that database have. And when you select each mismatch item you would see that required sql statement is also shown in object definition section. 

image

Figure: Schema Comparison Result

And bellow this you can find the entire script needed to update the target database, in “Schema Update Script” window. You can change the action that need to perform in the mismatch window and then click on refresh script option to regenerate the script again.

image

Figure: Schema Comparison update script

Actions to perform

You can perform the actions using the tool bar on top of the tool bar section or using menu from > data > Schema compare > [and the select any third level menu] to perform you desired action. You have the option to directly sync via write update command or perhaps you can save the generated script on a file using Export to File option. 

image

image

Figure: Schema Comparison Actions

Note

A few note before ending the post. This feature is available in Microsoft visual studio 2010 ultimate edition. which is a little bit disappointing for the developers, its such an useful tool and needed badly if we mess with data each day.