Thursday 6 September 2012

Windows Task Scheduler Result Codes


SCHED_S_TASK_READY
0x00041300
The task is ready to run at its next scheduled time.
SCHED_S_TASK_RUNNING
0x00041301
The task is currently running.
SCHED_S_TASK_DISABLED
0x00041302
The task will not run at the scheduled times because it has been disabled.
SCHED_S_TASK_HAS_NOT_RUN
0x00041303
The task has not yet run.
SCHED_S_TASK_NO_MORE_RUNS
0x00041304
There are no more runs scheduled for this task.
SCHED_S_TASK_NOT_SCHEDULED
0x00041305
One or more of the properties that are needed to run this task on a schedule have not been set.
SCHED_S_TASK_TERMINATED
0x00041306
The last run of the task was terminated by the user.
SCHED_S_TASK_NO_VALID_TRIGGERS
0x00041307
Either the task has no triggers or the existing triggers are disabled or not set.
SCHED_S_EVENT_TRIGGER
0x00041308
Event triggers do not have set run times.
SCHED_E_TRIGGER_NOT_FOUND
0x80041309
A task's trigger is not found.
SCHED_E_TASK_NOT_READY
0x8004130A
One or more of the properties required to run this task have not been set.
SCHED_E_TASK_NOT_RUNNING
0x8004130B
There is no running instance of the task.
SCHED_E_SERVICE_NOT_INSTALLED
0x8004130C
The Task Scheduler service is not installed on this computer.
SCHED_E_CANNOT_OPEN_TASK
0x8004130D
The task object could not be opened.
SCHED_E_INVALID_TASK
0x8004130E
The object is either an invalid task object or is not a task object.
SCHED_E_ACCOUNT_INFORMATION_NOT_SET
0x8004130F
No account information could be found in the Task Scheduler security database for the task indicated.
SCHED_E_ACCOUNT_NAME_NOT_FOUND
0x80041310
Unable to establish existence of the account specified.
SCHED_E_ACCOUNT_DBASE_CORRUPT
0x80041311
Corruption was detected in the Task Scheduler security database; the database has been reset.
SCHED_E_NO_SECURITY_SERVICES
0x80041312
Task Scheduler security services are available only on Windows NT.
SCHED_E_UNKNOWN_OBJECT_VERSION
0x80041313
The task object version is either unsupported or invalid.
SCHED_E_UNSUPPORTED_ACCOUNT_OPTION
0x80041314
The task has been configured with an unsupported combination of account settings and run time options.
SCHED_E_SERVICE_NOT_RUNNING
0x80041315
The Task Scheduler Service is not running.
SCHED_E_UNEXPECTEDNODE
0x80041316
The task XML contains an unexpected node.
SCHED_E_NAMESPACE
0x80041317
The task XML contains an element or attribute from an unexpected namespace.
SCHED_E_INVALIDVALUE
0x80041318
The task XML contains a value which is incorrectly formatted or out of range.
SCHED_E_MISSINGNODE
0x80041319
The task XML is missing a required element or attribute.
SCHED_E_MALFORMEDXML
0x8004131A
The task XML is malformed.
SCHED_S_SOME_TRIGGERS_FAILED
0x0004131B
The task is registered, but not all specified triggers will start the task.
SCHED_S_BATCH_LOGON_PROBLEM
0x0004131C
The task is registered, but may fail to start. Batch logon privilege needs to be enabled for the task principal.
SCHED_E_TOO_MANY_NODES
0x8004131D
The task XML contains too many nodes of the same type.
SCHED_E_PAST_END_BOUNDARY
0x8004131E
The task cannot be started after the trigger end boundary.
SCHED_E_ALREADY_RUNNING
0x8004131F
An instance of this task is already running.
SCHED_E_USER_NOT_LOGGED_ON
0x80041320
The task will not run because the user is not logged on.
SCHED_E_INVALID_TASK_HASH
0x80041321
The task image is corrupt or has been tampered with.
SCHED_E_SERVICE_NOT_AVAILABLE
0x80041322
The Task Scheduler service is not available.
SCHED_E_SERVICE_TOO_BUSY
0x80041323
The Task Scheduler service is too busy to handle your request. Please try again later.
SCHED_E_TASK_ATTEMPTED
0x80041324
The Task Scheduler service attempted to run the task, but the task did not run due to one of the constraints in the task definition.
SCHED_S_TASK_QUEUED
0x00041325
The Task Scheduler service has asked the task to run.
SCHED_E_TASK_DISABLED
0x80041326
The task is disabled.
SCHED_E_TASK_NOT_V1_COMPAT
0x80041327
The task has properties that are not compatible with earlier versions of Windows.
SCHED_E_START_ON_DEMAND
0x80041328
The task settings do not allow the task to start on demand.

Tuesday 12 June 2012

Friday 8 June 2012

SQL Transaction usage in Vb.NET

Dim sqlConn As New SqlConnection(Current.Application.Get("dbstring"))
........
sqlConn.Open()
Dim sqlTrans As SqlTransaction = sqlConn.BeginTransaction()

saveSupplierRecord(sqlTrans, ......
 sqlTrans.Commit() || sqlTrans.Rollback()
-------------------------------------------------------
Function InsertTransaction(ByRef sqlTrans As SqlTransaction .....
  Dim sqlConn As SqlConnection
  sqlConn = sqlTrans.Connection

.......
End Function

Wednesday 25 April 2012

ASP.NET with some AJAX

Here is the AjaxcontrolToolkit Link
http://www.asp.net/ajaxLibrary/AjaxControlToolkitSampleSite/Default.aspx
This toolkit is an open source project simply does ajax jobs relatively easier way.

Some JQuery and Javascript Links
http://www.dhtmlgoodies.com

Wednesday 18 April 2012

ASP.NET Template Field Command Triggering

 <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
                     OnRowCommand="GridView1_RowCommand">
                        <Columns>
                            <asp:BoundField DataField="ID" HeaderText="ID" Visible="False" />
                            <asp:BoundField HeaderText="Field Name" DataField="CurrencyName" >
                            </asp:BoundField>
                                                   
                             <asp:TemplateField ShowHeader="False">
                                 <ItemTemplate>
                                     <asp:ImageButton ID="ImageButton1" runat="server" CausesValidation="false" CommandArgument='<%# DataBinder.Eval(Container.DataItem, "ID")%>'
                                         CommandName="ItemDelete" ImageUrl="~/Admin/Img/Delete.png" Text="Button" />
                                 </ItemTemplate>
                                 <ItemStyle Width="18px" />
                            </asp:TemplateField>
                            
                        </Columns>
                  </asp:GridView>


    Protected Sub GridView1_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs)
        Dim MyPool As New LogicPool.DB("Conn")
        If (e.CommandName = "ItemDelete") Then

            Dim index As Integer = Convert.ToInt32(e.CommandArgument)
            MyPool.SQLRun("DELETE FROM AppCurrencyRules WHERE ID = " & index)
            FillGrid()
        End If
    End Sub

Tuesday 3 April 2012

Data Types (why?)

Finally in my 19th year in my professional carreer second time I saw another crazy programmer's code.
In the evaluation of computers and development techniques some developers resist to accept new techniques. about 10 years ago I had a collegue. He attented all those system analysis meetings, we built up data structure, process structure, road map together. We decided to use Informix SQL in those time as database. He had a strong background in DOS - Cobol systems. I think it was his first time to use a proper database. He used his own binary files as database until that time.

Then we began development. According to plan I was developing web end, he was developing windows end and we were good until the day we had to integrate both parts. I connected his database and surprised a bit. The data structure was OK but in every table there was one additional field which was binary. I didn't get it and asked him what it was. His answer was killing. He said "after he populates data from the screen he converted all of them to binary and write that field" I asked why didn't he use the all structure? He said he is faster with his way.

Nearly 1 year of analysis and data structure work has gone to rubbish bin. He suggest me to develop an interface to read his data.

In these 10 years it was my stragest memory. Until 5 minutes ago...

While I was examining the most complex code I ever seen I somehow couldn't find where is the problem. I can't debug it because of the arthitecture. I tried to follow the code line by line. In some point I saw there is an image field in database which is possible. There are some images and it can be normal. But the image field there bothered me and tried to find when it's used.

Yes. The same thing happened. Previous developer populated some fields and convert them into binary and wrote that field.

I can't believe this. Guys where did you see this technique ? First guy was Turkish  lives in Istanbul in all his life and second one is British living in UK.

Is it a kind of joke ?

Tuesday 6 March 2012

Text to Object or dynamically creating menu

The most important function is

    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


This function converts form names from text format to form objects. Here is my piece of code generating menu and assigning events to menu click.

Private Sub menuClickedEvent(ByVal sender As Object, ByVal e As EventArgs)
                 Dim ChildForm As New System.Windows.Forms.Form
                ChildForm = DynamicallyLoadedObject(newItem.Tag) 
                ChildForm.Show()

End Sub


Public Sub CreateMenu(ByVal MyMenuStrip As MenuStrip, Optional ByVal MyToolbar As ToolStrip = Nothing)
        Dim MyDB As New LogicPool.DB(_MySettings._DataConnection)
        Dim MYDS As New Data.DataSet
       
        MyDB.SQLReturnDT(MYDS, "Menu", "SELECT * FROM SysMenu M, SysUserRight H WHERE H.SysMenuID = M.ID AND H.SysUserID = " & _User._ID & " ORDER BY SortOrder")
    
        MyMenuStrip.Items.Clear()
        MenuPrepare(MYDS.Tables("Menu"), MyMenuStrip, MyToolbar)
    End Sub





Private Sub MenuPrepare(ByVal db As DataTable, ByVal MS As MenuStrip, Optional ByVal tb1 As System.Windows.Forms.ToolStrip = Nothing, Optional ByVal ref As Integer = 0, Optional ByVal ItemKey As Object = Nothing)
        Dim z As Integer
        Dim MyDB As New LogicPool.DB(_MySettings._DataConnection)
        For z = 0 To db.Rows.Count - 1
            ' 1. Seviye
            If ref = 0 Then
                If CInt(db.Rows(z).Item("RefID")) = 0 Then
                    Dim newItem As New System.Windows.Forms.ToolStripMenuItem
                    If db.Rows(z).Item("FormName").ToString.Trim.Length > 0 Then
                        newItem = MS.Items.Add(db.Rows(z).Item("MenuName"), Nothing, New System.EventHandler(AddressOf menuClickedEvent))
                        newItem.Tag = db.Rows(z).Item("FormName")
                    Else
                        newItem = MS.Items.Add(db.Rows(z).Item("MenuName"), Nothing)
                    End If
                    If db.Rows(z).Item("ImageName").ToString.Trim.Length > 0 Then
                        Dim Newimg As System.Drawing.Image
                        Newimg = FrmImages.imgMenu.Images(db.Rows(z).Item("ImageName").ToString)
                        newItem.Image = Newimg
                    End If

                    newItem.Name = "Mn" & db.Rows(z).Item("ID")
                    MenuPrepare(db, MS, tb1, db.Rows(z).Item("ID"), newItem)


                End If
                ' DiÄŸer Seviyeler
            Else
                If CInt(db.Rows(z).Item("RefID")) = ref Then
                    Dim newItem As New System.Windows.Forms.ToolStripMenuItem
                    Dim OldItem As System.Windows.Forms.ToolStripMenuItem
                    OldItem = ItemKey

                    newItem = OldItem.DropDown.Items.Add(db.Rows(z).Item("MenuName"), Nothing, New System.EventHandler(AddressOf menuClickedEvent))

                    If db.Rows(z).Item("FormName").ToString.Trim.Length > 0 Then
                        newItem.Tag = db.Rows(z).Item("FormName")
                    End If


                    If db.Rows(z).Item("ImageName").ToString.Trim.Length > 0 Then
                        Dim Newimg As System.Drawing.Image
                        Newimg = FrmImages.imgMenu.Images(db.Rows(z).Item("ImageName").ToString)
                        newItem.Image = Newimg
                        If Not tb1 Is Nothing Then
                            If db.Rows(z).Item("Toolbar") = 1 Then
                                Dim TB As System.Windows.Forms.ToolStripItem
                                TB = tb1.Items.Add(db.Rows(z).Item("MenuName"), Newimg, New System.EventHandler(AddressOf ToolbarClickEvent))
                                TB.Tag = db.Rows(z).Item("FormName")
                                If MyDB.ParameterGet("ToolbarText") = 0 Then
                                    TB.DisplayStyle = ToolStripItemDisplayStyle.Image
                                Else
                                    TB.DisplayStyle = ToolStripItemDisplayStyle.ImageAndText
                                End If
                                TB.ToolTipText = db.Rows(z).Item("MenuName")
                                tb1.Items.Add(New System.Windows.Forms.ToolStripSeparator)
                            End If
                        End If
                    End If

                    newItem.Name = "Mn" & db.Rows(z).Item("ID")
                    MenuPrepare(db, MS, tb1, db.Rows(z).Item("ID"), newItem)
                End If
            End If
        Next
    End Sub

Data to Image

This little function converts image data field in database to System.Drawing.Image object
Consider a datatable with an image field named ImgItem, we'll call the function below like this :

Dim MyImg as System.Drawing.Image
MyImg = DataToImage(MyDS.tables("SomeTable").rows(0).Item("ImgItem")
   


Public Shared Function DataToImage(ByVal DataItem As Object) As System.Drawing.Image
        Dim arrImage() As Byte = DirectCast(DataItem, Byte())
        Dim ms1 As New System.IO.MemoryStream(arrImage)
        Dim origimage As System.Drawing.Image = System.Drawing.Image.FromStream(ms1)
        Return origimage
End Function

When It comes to saving

                Dim ms As New System.IO.MemoryStream
                Me.ImgFoto.Image.Save(ms, ImgFoto.Image.RawFormat)
                Dim arrImage() As Byte = ms.GetBuffer
                ms.Close()


Now you may use arrImage to save into a datafield.

This is my way of saving. I'll explain this way later.

                MyPair.Add("Fotograf", arrImage)
        

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.

Monday 16 January 2012

Destiny of a Developer, Writing codes on other developers' softwares

In the first years as a developer I only developped my own programs. But then I changed jobs and I faced a new challange. Writing codes on other developers' softwares. If the previous developer implemets standards and had enough knowledge it was ok. Sometimes I worked with previous developer which was OK too. But the problem arised when previous developer was not around, or he was a newbie, or he hadn't got any idea of standards.  It's a kind of nightmare for a developer to put a brick on a terrible wall.

There are two ways you may follow in this sittuation.
1 - You can throw away the existing codes and build up a new perfect software
2 - You can look the sittuation as a money earning kind of thing and do your best on existing codes.

If you choose the first way, I may say you are brave. But according to my experiences it cannot be the best way. There are many other parameters should be taken into consideration to decide which one you should choose.

The most important parameter here is your employer. If the employer is not good at with computers ideal way is second. Don't even waste your time to tell the reality.
Here I got some question list showing how I decide what to do ?
  1. Does employer have enough knowledge what you talk about
  2. Is the code terrible enough to throw away
  3. How long will you planning to work in this job
  4. How long is your employer planning to use the software
  5. Is there any integrations with other softwares
  6. Is your role good enough to take this action (way 1)
  7. Do you have time for this ?
I recommend the second way. Even though if you are planning to do it in second way, start a new program but don't tell anybody until you reach the halfway.  Whenever you mention it you'll face time barriers.

What are the obstructions you'll face with a previous inadequate developers code ?
  • Wrong data structure
    • Wrong connections
      • I once faced a software written by a rookie who didn't know how to handle many to many relations, though there was a long string field to put the many relation IDs comma seperated.
      • I saw one field holding two connections at the same time like first 3 characters are one relation rest is another connection)
    • Wrong ID handling
      • I saw character based ID fields
      • Wrongly named ID fields (I couldn't find out which field related with which tables)
    • Wrong normalizations / optimisations
      • Keeping same data in 2 or more tables instead of relations. Which creates inconsistancy
  • Codes may be away from object oriented
    • Instead of writing a function or a class doing same job in different screens again and again. Like there are Insert and Update screens exactly the same but save functions written twice.
    • Because of not knowing about Enumarations there may be absurd values you may not understand unless you dig the code
    • Because of not knowing about DLL's same functions can be coded again and again in different programs.
  • Unnecessary excess codes
    • In an update screen, button_click event send data to save function and it can gather data and send to a web service, web service formats data and send to a stored procedure and repeat this cycle for insert screen. (Just put a parameter to save function to make the code simpler)
  • Performance can be ignored
    • To insert one line to database, reading all the table.
    • wrongly typed SELECT statements
      • I saw some nested SQL sentences with 3-4 levels depth.
  • Away from code formattings
    • No uppercase, lowercase formats of the code. (It makes really difficult to read)
      • Simple, You can read "SELECT ProfileID, FirstName, LastName FROM Profile WHERE Birthday BETWEEN '01/01/1970' AND '01/01/1980'  You'll see SQL commands are in uppercase and easily read it. Try it with all lowercase and you'll see it's more difficult to read.
  • Unnecessary complex architecture
    • Sometimes showing your ability is unnecessary. You may know AJAX but if you are coding an admin screen, postbacks can be simple and fast.
  • Unnecessary screens. If it's not desperetly needed, there is no mean to make 2 different screens for insert and update. Only difference is RecordID and SQL INSERT or UPDATE Command. You can handle it easily by using an IF statement. If there are 2 screens and you need to add a field, you may easily make mistake in one later. Less code, less screens are always preferable. For example I do all my different list entries in one screen by differentiating parameter. in this way I only do the screen once and I don't need to do same screens again and again. It is a real time saver. Also updates become very easy in this way

Learning A New Programming Language

This is my 19th year in IT. I've learned many programming languages, databases, platforms, operating systems, etc. I learned most of them by myself. I only take one course  16 years ago which was about SQL and r4gl (a programming language on UNIX / Informix databases).
When I begin to write programmes there was dBase and Dos. It was the good times only text based programmes, one way direct flows, simple operations. But then everything has been changed one by one.
First we switch xBase databases to SQL, then Dos to Windows, then came the Internet, then web based programming, then web + windows based programming, then .NET came and it's still coming.

I've learned these languages in order
Basic -> dBase -> Clipper -> r4gl -> Visual Objects -> Visual Fox Pro -> Visual Basic -> HTML -> ASP -> Javascript -> VB.NET -> ASP.NET -> C#.NET

After learning some of them I developped a methodology to learn languages. Now I will share my live experience while I'm learning a new language "Ruby".

Generally I begin with basic rules like variable definition, operators, function and subroutine syntax, passing parameters, conditions(if, case), loops (for next, while), startings (includes etc)

Then I go thru database connections, SQL implementations reading writing to a database etc. File operations and communications (mail, http sends and reads etc)

I'll write this new experience day by day. Because I'll not be dealing with this full time there can be gaps between blogs.

.NET Framework Problems

Problem / Symptom
Visual Studio .NET has detected that the specified Web server is not running ASP.NET version 1.1

Solution
 %windir%\Microsoft.NET\Framework\v1.1.4322\aspnet_regiis.exe -i