Tuesday, 12 June 2012

.NET include htm page to aspx

<!-- #include virtual="../header.htm" -->

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.: