Wednesday, 15 February 2012

Saving Dataset / Datatable to database in VB.NET

Hi again.
It's a kind of tricky to save the dataset or datatable to database using SQLClient or OleDB objects.
Here is a sample from my DLL library. I strongly advise you to make these kind of stuff as functions in a dll, so that you easily use them in your projects without any effort.

In the function below connection object parameter is optional because if nothing comes to function I use dll class's connection instead.

I think I have to explain what is going on here.
Until the line of stars it's just connection issues.
TempDS is a temporary dataset. I am using it while I am getting shema to the data adapter. SaveDA.FillSchema is the important trick here. By getting the schema to data adapter I can save my dataset to the database. The SqlSelectStr parameter is something like "SELECT TOP 1 * FROM TargetTable"
Remember I don't need that data but I strongly need schema.

Then another most important part, the CommandBuilder line : it seems meaningless. We create the object but never use but this line is essential. If you omit it you can't save your dataset.

Good luck.

 Public Sub SQLSaveData(ByVal DS As Data.DataSet, ByVal TableName As String, ByVal SqlSelectStr As String, Optional ByVal Connection As Data.OleDb.OleDbConnection = Nothing)

  If Connection Is Nothing Then
   Connection = Conn
  End If
  If Connection.State <> ConnectionState.Open Then
   Try
    Connection.Open()
   Catch ex As Exception
    MsgBox("Error in Database Connection. ", MsgBoxStyle.Critical, "Pool")
   End Try
  End If
' ***************************
  Dim TempDS As New Data.DataSet
  Dim SaveDA As New System.Data.OleDb.OleDbDataAdapter
  SaveDA.SelectCommand = New System.Data.OleDb.OleDbCommand(SqlSelectStr, Connection)
  SaveDA.FillSchema(TempDS, System.Data.SchemaType.Source, TableName)
  SaveDA.Fill(TempDS, TableName)
  Dim cb As New System.Data.OleDb.OleDbCommandBuilder(SaveDA)
  SaveDA.Update(DS, TableName)
 End Sub


Data connection and a simple read in VB.NET

Hi again.
This time I'm writing down a simple code block. For a vb.net developer I embed those steps mostly to a dll file and never deal with those codes for about 4-5 years. Now I can't carry my dll to this job. So When I need to connect to a database I open my dll source codes and look for how I did it in the past.

It's again nothing new but keeping them around may be handy. This is a SqlClient type of connection but if you want to connect thru OleDB then you should change SqlClient stuff to OleDb stuff.

You should change red words with yours before you use, I painted connection object to blue to show where you should use

        Dim Conn As New Data.SqlClient.SqlConnection("Password=DBPassword;User ID=DBUser;Initial Catalog=DatabaseName;Data Source=DBServerAddress;")
        Dim DA As New Data.SqlClient.SqlDataAdapter
        Dim DS As New Data.DataSet
        Conn.Open()
        DA.SelectCommand = New Data.SqlClient.SqlCommand("SELECT * FROM MyTable')", Conn)
        DA.Fill(DS, "JustGiveAName")

        Do something, do something
        Do something, do something
        Do something, do something
        Do something, do something

        DA = Nothing
        Conn = Nothing


Wednesday, 8 February 2012

Creating Custom ASP.NET Control using VB.NET

Today I'm developing a custom ASP.NET control.
It's usefull when you develop those libraries if you use them again and again. I know it makes you slow in the beginning but later you easily compansate that time. If you are a web developer and develope sites again and again how many times you deal with user authentication, authorisation kind of stuff. Copy paste can not be the exact solution many times.If you have other collegues working on the same project then copy paste operation sometimes can be a real mess. This time I'm developing Server Controls for a web-designer friend who has no knowledge about programing. He will open Visual Web Developer and install my server controls and insert them where he wants to. My controls here can create datatables, modify web.config and do everything he needed with just drag drop and property assignments. I also supply him an admin page to fill them in runtime. It will make my workload nearly zero. I only interfere in very complex or critical jobs.

Anyway, although I did this 4-5 years ago I couldn't remember most of the things. So I began with searching and reading articles about it. Then I started from zero.
1 - In Visual Studio I've started a new web project using ASP.NET Server Control project type
2 - In server controls there isn't any visual designer. so I have an empty code page. well not empty there are some imports.
3 - I started to build up a simple login screen.
4 - After some trials and fails I found a way to do it correctly. Here I attached the simplest code of it. I put some notes on important parts. You may use it as a template for beginning. I divide the code into regions to make it more understandable.
5 - Where I strugled most ?
Default Values. (look how I did in render section)
Event / Method stuff. ( I put comments on important parts)

Well it's just a beginning. Good Luck


BTW Adding an icon to the controls is tricky. Here is the link Microsoft explains how as walkthrough.
http://msdn.microsoft.com/en-us/library/yhzc935f(d=printer).aspx

I can't simply believe this. After reading and trying to implement those rubbish in Microsoft I discovered a very simple way to add icons to controls. here it is :
  1. Right click project in solurtion explorer and choose add existing item
  2. select a 16x16 bmp image
  3. Rename it and make the image name and control name same.
  4. Click image once in Solution explorer and change the Build Action property to Embedded Resource
 That's it.

After digging internet and books here are the tips you may hard to find.

Using URL as property

To use a URL path as a property you need to add reference to System.Design.DLL first.
Then you should import System.Drawing.Design at the top of the page like :
Imports System.Drawing.Design

Then here is a sample code to do the job

    <EditorAttribute(GetType(System.Web.UI.Design.UrlEditor), GetType(UITypeEditor))> _
    Public Property URL() As String
        Get
            Return http_url
        End Get
        Set(ByVal value As String)
            http_url = value
        End Set
    End Property
    Private http_url As String

And when you click this property you'll get this screen


Menu like Items Property (nested)

This is one another though job to do while you're developing an ASP.NET server control. If you want an Items box for user to fill items you should do something like this.

It took so much time to find the exact solution.
Here is the complete code block

Private _menuItems As New List(Of MenuItem)()
    <PersistenceMode(PersistenceMode.InnerProperty)> _
    Public ReadOnly Property MenuItems() As List(Of MenuItem)
        Get
            Return _menuItems
        End Get
    End Property
End Class
<ToolboxItem(False)> _
<ParseChildren(True, "MenuItems")> _
Public Class MenuItem
    Private _clientClick As String
    Private _menuItems As New List(Of MenuItem)()
    <Localizable(True)> _
    Public Property Title() As String
        Get
            Return m_Title
        End Get
        Set(ByVal value As String)
            m_Title = value
        End Set
    End Property
    Private m_Title As String
    Public Property Href() As String
        Get
            Return m_Href
        End Get
        Set(ByVal value As String)
            m_Href = value
        End Set
    End Property
    Private m_Href As String
    Public Property Id() As String
        Get
            Return m_Id
        End Get
        Set(ByVal value As String)
            m_Id = value
        End Set
    End Property
    Private m_Id As String
    <PersistenceMode(PersistenceMode.InnerDefaultProperty)> _
    Public Property MenuItems() As List(Of MenuItem)
        Get
            Return _menuItems
        End Get
        Set(ByVal value As List(Of MenuItem))
            _menuItems = value
        End Set
    End Property

When you click that small button near MenuItem you are now have this screen to make the entry easier.:



Tuesday, 7 February 2012

Some Usefull Code Samples For VB.NET Developers

Here I wrote some very useful code samples and some are in form of functions. Hope you like.

This function creates an empty Access database

 Public Shared Function CreateAccessDatabase(ByVal DatabaseFullPath As String) As Boolean
  Dim bAns As Boolean
  Dim cat As New ADOX.Catalog()
  Try
   Dim sCreateString As String
   sCreateString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & DatabaseFullPath
   cat.Create(sCreateString)
   bAns = True
  Catch Excep As System.Runtime.InteropServices.COMException
   bAns = False
  Finally
   cat = Nothing
  End Try
  Return bAns
 End Function


Collection Class Sample

 Public Class DataPairCollection
  Inherits System.Collections.CollectionBase
  Public Sub Add(ByVal NewPair As DataPair)
   List.Add(NewPair)
  End Sub

  Public Sub Add(ByVal NDataName As Object, ByVal NScreenVal As Object)
   List.Add(New DataPair(NDataName, NScreenVal))
  End Sub

 End Class
 Public Class DataPair
  Public DataName As Object
  Public ScreenVal As Object

  Public Sub New(ByVal NDataName As Object, ByVal NScreenVal As Object)
   DataName = NDataName
   ScreenVal = NScreenVal
  End Sub
 End Class


Dynamically Create Object From String

 Public Function DynamicallyLoadedObject(ByVal objectName As String, Optional ByVal args() As Object = Nothing) As Object
  Dim returnObj As Object = Nothing
  Dim type As Type = Assembly.GetExecutingAssembly().GetType(Application.ProductName & "." & objectName)

  If Not type Is Nothing Then
   returnObj = Activator.CreateInstance(type, args)
  End If

  Return returnObj
 End Function

Some Utilities Make Your Life Easier

My installation of a new computer takes so much time. I always hesitate to format and install my development computer.I have many utilities that I want under my hand.

Here I'm introducing some of them;

My top utility is editplus it's actually a simple text editor but it can load large text files . When you begin to use this editor it's hard to quit. Because there are features for web developers and also it's handy when you just want a quick peek your specific codes in a large project. The evaluation period actually never ends but if you want to get rid of the registration screen here is a link for you

Number two is Microsoft Image Composer. it's a very old program. I think it was distrubuted with Frontpage 98 CD set. Then I don't know why but Microsoft stop distributing it. It's basically an image editor without layers. Photoshop is always a bit complex for me. To get quick results I prefer to use it for years.

MS Access. This is a must have one. I use this for many purposes along use as a simple database. For example I always keep an empty Access Database in my web mail. To transfer MS SQL tables it's handy to export them to access and carry those exports in mdb format.
I especially use MS Access for one specific occasion.  When I develop a multi user windows desktop application with multilanguage features. I keep language dictionaries in MS Access in clients. So I don't go to MS SQL over network for translations and don't create traffic over network.

ColorPicker is a simple one I like. Just activate it and put mouse cursour on an image to see the color codes of that pixel. If you develop a web application without any graphics support this small software can save your life.

The Snippet Editor. This small software can make you write your codes nearly two times faster if you use Visual Studio. You can download it free on MSDN Site which I linked.  You can add new snippets to visual studio and after you write 2-3 letters and pressing tab can bring lines of code.

I had developped some utilities for myself too. I have one for database - screen fields matcher. I use it when I develop database applications. I wish I can give it to you but it's completely reflects my coding characteristics. If you read my naming style. I use a slightly different way of ID naming in database tables.

I shared my Folder Watcher before.

I also have a large DLL. There are Database, communication, file system, image and many other libraries in it. Whenever I face a problem I always think if this is a one time problem or can I face again in the future. If I decide that I can face again I put the code to my DLL. So it grows day by day. But I may say I forgat how to save screen fields to database bacause I use my own functions to do this easily. I suggest you to develop this kind of library for yourself. development time can be longer in the begining but later you'll code incredibly fast. Also you will use it in other development projects. without any effort.

I also have some reporting tools which I developed to create reports in distance. This tool has commercial value, thats why I can't share it with you.

A Rich Text Editor is essential in developing ASP.NET sites isn't it. Here is the link for you. It's free and also you can download the source codes as well. http://rte.codeplex.com/



I will continue to write others in time.

Friday, 3 February 2012

Object Oriented vs Object Spagetti

Novadays I'm dealing with some other developer's software. It's a bit old software. Nobody here knows who wrote the codes. It's written in .NET Framework 1.1 and using Visual Studio 2003.

Yes yes I know migrate the codes to current framwork instead of talking you're saying probably. Wait a little and be patient my friends.

I think the developer was new to .NET and probably this is his first codes in .NET. You know when .NET first introduced "Object Orientation" was the first think people talked.  But as I always say "you have to balance the theory and practice". Technology is a kind of fashion for male programmers.
"Ohh this year Object Oriented Programming is so popular",
"Are you still using tables... I am using divs "
"3 Tier application is old fashioned"

If you are old enough you may know server strategies in time. Once there were 1 huge server for everything Then people think that it's dangerous to keep all the eggs in one basket. We switch to multi server environment. File Server, Mail Server, Database Server, Domain Server.... Then again somehow we changed our mind and a huge server came back with the virtual servers.

Lets come back to our subject. I am digging the codes to understand why he did something like a spagetti.
A process started in an application and I follow the codes in 10 different functions in 5 different application written in 2 different languages PLUS Stored Procedures, using user defined nested functions in 4 level. It's like an adventure. I never know where I'm going to end when I start from a point.

My first manager told me some golden rules of IT.

1 - One day we may die. Write the codes clear, understandable, standardised and documented. so that one other programmer can continue your job immedialtely

2 - Always keep it simple. This is not an arena for you to show your talents.

3 - Updating a code is harder. Always write codes to change anything easily.

I will tell you the rest of them in future. But he is right. You may write in C# and VB but you don't need to use both of them in one project. (Actually I don't understand why we need to use C# anyway.)

Now I'll tell what I did to add a simple field to a screen.
I opened the insert screen and added a textbox
I opened the database and added the field
I opened the codes (in VB) of the insert screen and try to add this field to save buttons click event.  but I realized that the screen values are loaded into variables and sended to a functions in a dll.
I found the dll application and open the source and began editing.(dll was in C# )
I follow the dll and saw there is another reference to another dll which is directly related to insert operation.
I opend other dll application and update the lines. But I saw that the screen values now sended to a stored procedure as parameters.
I open SQL server and updated stored procedure.

Finally I finished the insert but I also did the similar things for the display and update screens (I don't know why but there were 2 screens for insert and updates.

So now I have to compile them in order and include the dll's to main application.
Come on.. This is just a waste of time.  It's the third challanging job in my carrier.

1 - I saw a man storing the data like this : first he creates the line then he converts the line into binary then he wrote to a database table. it's true and he did it for the whole application and NO the data was not sensitive. I realized that he used his binary files for his database needs for his whole life. When He found SQL server in front of him he didn't understand about query, relation etc. He did everything with his best knowledge.

2 - There was a ERP system written by a rookie. Front screens and gui  was good. but in codes and database it was unbelievible. ID fields were character based. If you want to create a relation between 3 table you had to know which characters are the link part of the which table. Even worse part was he had no idea about cross reference tables, he had no clue about field naming. Also he had no idea about object orientation he repeat many code parts in many places in his code.

After them this is less challanging for me. :)

Final Word : Please my friends. Keep your codes simple and updatable. Reading standards will take your 2 hours maximum. But will save days in the future.

Friday, 27 January 2012

My Free Small Programs

Folder Watch
Ever need a program that copy all the changed or created files you worked from your work space to another folder. I needed today. Because I'm now dealing with a pretty old software written in Visual Studio 2003 and .NET Framework 1.1 which i should work in a virtual machine (XP), run in Windows 7 and collect my changed files to upload a server. (Don't ask me why)

So I need to copy all changed files to windows 7 IIS environment as well as an "update folder". I collect my updated files in the "update folder" and bulk export to other company to compile and build with their codes.

It's somehow difficult to keep tracks manually. So I developped this small software using file system watcher. You may reach this small program's setup here, or you may reach the source codes here.

Feedbacks are welcome.

Friday, 20 January 2012

Many to many data table connection handling

There are some other ways to create connnections but as a programmer you should allways consider the future. An ideal program should work when it's grow or forcing the borders without changing any field lengths.

So you have to plan the future for the worst scenerios. Many to many connections are the gaps that new developers fall into it.

This is the ideal way of handling this situation.

When will you need many to many connections ?
Consider there are two tables Profile and Hobbies.
There are many profiles and many hobbies. How will you keep which profile has which hobbies or finding profiles who play chess ?
In this case you'll need another table to keep connections. Which we call "Cross Reference Table"

Here is the table structure

ProfileHobbyProfileHobbyCross
IDIDID
........ProfileID
........HobbyID

You may say that there is no need to keep ID field in cross reference table. I find it useful but it's up to you.

Keeping a cross reference table expands the horizons of your program. Whatever the record numbers will be you can handle it. Also updates can be done easily.

Database Table and ID Naming

Database, Tables and Fields should have clear, understandable and functional names. I think all programmers agree on that. But I'm not sure that all are agree in same standards.

Database name can be anything unless it's not a copy of other. But it's the easiest one.

Lets think about table names. Although you are completly free in naming, you should allways think that one day, another stranger will have to continue coding your programs. Or even you will forget how you did something. Believe me, may be you would have full control in your first 4-5 programs but then you will loose your control. When it happens, "standards" are the life saver.

You may notice that there are some naming standards for variables, file names, table names, field names etc. I admit that most of them OK, but I have an objection to data table field namings in some point. Especially ID Fields. I am developing database applications nearly 20 years. In a large databases with more than 200 tables ID fields must be more specific. if you have just 10-20 tables you may understand anything with a quick look. But with 200 table it may be hard to follow tables.

This is my way of naming ID Fields. May be it's useful for you too. Actually it never let me down in 20 years.
Rule 1 : Name of the ID field in the table itself is "ID". Every single table has a field as ID. (only in few exceptions, you may not need ID field)
Rule 2 : A reference to an ID field of an other table must be named as TableNameID
Example
Assume there are two tables like Profile and Country.

ProfileCountry
IDID
CountryIDCountryName
FirstName

In this way when you look for at the profile table you see there is a link to an ID field in Country table easily and also when you will write an SQL sentence it's easy to remember the connection.
Like
SELECT * FROM Profile INNER JOIN Country ON Profile.CountryID = Country.ID

(We will mention how useful are the uppercase lowercase syntax later. )
if the connection with the tables is one to one or one to many this will be very easy to find. We'll mention many to many connections later.

I don't know why but it's not the Microsoft way. I think this is more logical than their namings .

When it comes to table names,  mostly related tables should begin with the same way. So that when you look at the database you could see them together. I will explain my way. It may enlight your vision.

First I decide which modules I need. For example if I use accounting, operation and crm modules in a program, I simply determine shortnames for them
Accounting -> acc
Operation -> opr
CRM -> crm
and also I'll need some  base modules which can be defined as prg

Now I name the tables like
accCurrency
accCurrencyRate
accAccount
accAccountHistory
oprTask
oprTaskAssignment
crmProfile
crmProfileDetail
prgParameters
In this way when you browse tables in SQL Management Studio your close related tables follow each other.
Also you can find accounting related tables easily.

I'll be happy for any comments or questions.

Tuesday, 17 January 2012

Learning A New Programming Language Day 1

Hello and Welcome to my Day 1
Today I started the day by searching in google how can I install the environment and which setups do I need stuff. I found ruby installer for windows in http://rubyinstaller.org/downloads/ When I install it I found a ruby book in pdf format. This is even better to start a journey otherwise I probably now searching for a book.

I started to read the book, I skipped some story parts. (If you are experienced in 2 or more languages you can easily skip these parts) Later if I have time I may read the history, story etc.

Now I'm in Chapter One with the subtitle of (Strings, Numbers, Classes and Objects)
Like most of the programming languages there are some input and output commands. I can see that there are print and puts to print something on screen (I think I won't need them in the future but it's good to know) The first important thing is getting familiar with the syntax. If I can understand the logic and syntax then I jump thru the half way in once.

Now I will list the important parts I read in this book. I normally keep a small sized notebook and I suggest you to do so. It can fit into a pocket, no lines if possible and there should be more than 200 pages. And I write all the critical knowledge into this book with a permanent pen. Reason is simple 20 years ago I wrote my notes with other pens and in a rainy day I lost some of my writings. Since then I allways use permanent pens.

Normally I just read and take notes in the beginning, then I put those notes to their correct places. Unfortunatally not all the books follow my way of learning.

Ruby is case sensitive
Don't need to declare variables before use
Line remarks start with #
Multiline comments start with "=begin" end with "=end" and must be flushed with left margin
=begin
This is a
multiline
comment
=end

Condition Stuff
if (condition) then
do something
end
"if" condition can be in one line

global variables start with $

Class Declaration
Class name should begin with uppercase letter
class ClassName
  def subName(SubParameter)
    @MyName = SubParameter
  end

  def getName
      return @MyName
   end
end

variables starts with @ means instance variable which belongs to a class instance
variables starts with @@ means class variable which belongs to a class itself

mydog = Dog.new
mydog.subName('Fido')

When a class contains a method named initialize this will be automatically called when an object is created using the new method.

Ruby automatically de-stroys objects and reclaims the memory they used when they are no longer referenced in your program.

Inspecting Objects
ObjectName.inspect and p(ObjectName) are the ways to inspect objects - (I will look them later I think they are for debugging related)

Parent - Child / Super - Sub Classes
class Treasure < Thing means Treasure is a sub class of Thing

In a child class there is a keyword like "super" which pass child parameters to parent. and can be used standalone to pass all the parameters or with specific parameters

‘SET’ Accessor
When you write a set accessor in this way, you must append the = character to the method name, not merely place it somewhere between the method name and the arguments.
So this is correct: def name=( aName ) But this is an error: def name = ( aName )

Strings
Format Strings
%d – decimal number
%f – floating point number
%o – octal number
%p – inspect object
%s – string
%x – hexadecimal number

Now I need to do some work in .NET. See you in next session.