Wednesday, December 18, 2013

Append an element to an existing XML File (VB.NET)

Here's an example of appending a node to an xml file in VB.NET.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
Dim doc As New XmlDocument()  
 Dim file As New FileStream("your_filename", FileMode.Open)  
 doc.Load(file)  
 Try  
      file.Close()  
      file.Dispose()  
      Dim root As XmlNode = doc.DocumentElement  
      Dim el As XmlElement = doc.CreateElement("Invoices", "http://schemas.openxmlformats.org/package/2006/Invoices")  
      el.SetAttribute("Id", "Test")  
      doc.DocumentElement.AppendChild(el)  
      root.InsertBefore(el, doc.DocumentElement.FirstChild)  
      doc.Save("your_filename")  
 Catch ex As Exception  
      Throw ex  
 End Try  

Cheers!

Wednesday, December 11, 2013

Remove extra spacing in between NumericUpDownExtender default buttons (ASP.NET Ajax)

When integrating NumericUpDown Extender to your asp.net apps, there's a wide gap in between the up/down buttons as shown below:
The trick was to replace the doctype declaration in master page from:
 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">  
to:
 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
Note: This DTD contains all HTML elements and attributes, INCLUDING presentational and deprecated elements (like font) as described in w3. So, I believe there are presentational elements or deprecated elements incorporated into this extender.
Reference: StackOverflow

Cheers!

Tuesday, December 10, 2013

Append text to textfile in FTP or SFTP using SSH.NET

FtpWebRequest in .NET has few dozen bugs and some limitations when communicating to an FTP or perhaps an SFTP server. So, I decided to use SSH.NET which is a 3rd party .NET FTP client. You can use WinSCP or other existing FTP clients out there. Here's a sample code to append text to a textfile located in an FTP or SFTP Server.
Adding of reference:
 using Renci.SshNet;  
Append Text Method:
Code:
private void AppendTextToTextFile()  
     {  
       const int port = 22;  
       const string host = "192.168.2.1";  
       const string username = "greg";  
       const string password = "testpassword";  
       const string workingdirectory = "/root/files";  
       const string uploadfile = @"D:\uploadfile.txt";  
       Console.WriteLine("Creating client and connecting");  
       try  
       {  
         using (var client = new SftpClient(host, port, username, password))  
         {  
           client.Connect();  
           Console.WriteLine("Connected to {0}", host);            
           //add items to List<string> object  
           for (int i = 0; i < 5; i++)  
           {  
             dataToInsert.Add("test" + i);  
           }  
           //append text to file            
           using (StreamWriter writer = client.AppendText(workingdirectory + "/TestFile.txt"))  
           {  
             foreach (string data in dataToInsert)  
             {  
               byte[] writeData = Encoding.ASCII.GetBytes(data);  
               writer.WriteLine(data);  
             }    
           }  
         }  
       }  
       catch (Exception ex)  
       {  
         throw ex;  
       }  
     }  

Cheers! :)

Get all records before the last inserted record in SQL Server (TSQL)

In a scenario where you want to show all records before the latest injected record, one solution would be to get the latest date or perhaps tha latest primary key field. But, in cases where there is no primary key defined, there's another solution using Row_Number() in SQL Server. See the two queries below:
 -- option 1  
 select Production.Product.ProductID, Name as ID from Production.Product   
  where (ProductID < (Select MAX(ProductID) from Production.Product))  
  order by ProductID desc;
-- option 2 WITH ProductsView AS ( SELECT ProductID, Name, ROW_NUMBER() OVER (ORDER BY ProductID) AS RowNumber From Production.Product ) SELECT ProductID, Name FROM ProductsView WHERE (RowNumber < (select Max(RowNumber) from ProductsView)) order by ProductID desc;
Reference: Row_Number() in TSQL

Sunday, December 8, 2013

Predicate Wrapper Custom Class in VB.NET (REPOST)

Here's a custom predicate wrapper class I got from visual basic forums. I'll be converting and posting the C# equivalent for this.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
Public Delegate Function PredicateWrapperDelegate(Of T, A) _  
  (ByVal item As T, ByVal argument As A) As Boolean  
 
 Public Class PredicateWrapper(Of T, A)  
   Private _argument As A  
   Private _wrapperDelegate As PredicateWrapperDelegate(Of T, A)  
   Public Sub New(ByVal argument As A, _  
    ByVal wrapperDelegate As PredicateWrapperDelegate(Of T, A))  
     _argument = argument  
     _wrapperDelegate = wrapperDelegate  
   End Sub  
 
   Private Function InnerPredicate(ByVal item As T) As Boolean  
     Return _wrapperDelegate(item, _argument)  
   End Function  
 
   Public Shared Widening Operator CType( _  
    ByVal wrapper As PredicateWrapper(Of T, A)) _  
    As Predicate(Of T)  
     Return New Predicate(Of T)(AddressOf wrapper.InnerPredicate)  
   End Operator  

Here's the findtrack function:
1
2
3
4
Public Shared Function FindIndexTrackNumber(ByVal SysTrack As SystemTrack, ByVal searchArg As Integer) As Boolean  
     'Searches for the SystemTrack with TrackNumber searchArg  
     Return SysTrack.ID.Equals(searchArg)  
   End Function 

Here's its sample use:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
Dim SearchNumber As Integer = 456  
     Dim Index As Integer  
     Dim SystemTracks As New List(Of SystemTrack)  
     SystemTracks.Add(New SystemTrack With {.ID = 111, .Title = "Help Me", .Author = "Greg Phil"})  
     SystemTracks.Add(New SystemTrack With {.ID = 222, .Title = "Help Me1", .Author = "James Nelson"})  
     SystemTracks.Add(New SystemTrack With {.ID = 456, .Title = "Help Me2", .Author = "Tom Enigma"})  
     SystemTracks.Add(New SystemTrack With {.ID = 12, .Title = "Help Me3", .Author = "Lord Brown"})  
     Index = SystemTracks.FindIndex(New PredicateWrapper(Of SystemTrack, Integer)(SearchNumber, AddressOf SystemTrack.FindIndexTrackNumber))  
     If Index <> -1 Then  
       Console.WriteLine("Sytem Track has been found at: " & Index)  
     Else  
       Console.WriteLine("System Track not found! ")  
     End If  
     Console.ReadLine()  
:)

Wednesday, December 4, 2013

Read Excel 2010 64 bit File on a 64 Bit Machine using OleDB Provider in VB.NET

Here's the VB.NET Version of this post Read Excel 2010 64 bit file using OleDB Provider in C#
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
Option Strict On  
 Option Infer On  
 Imports System.Data  
 Public Class Form1  
   Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load  
     Dim MyConnection As New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source='c:\\temp\\test.xlsx';Extended Properties=Excel 12.0;")  
     Dim DtSet As New DataSet()  
     Dim MyCommand As New OleDb.OleDbDataAdapter("select * from [Sheet1$]", MyConnection)  
     Try  
       MyCommand.Fill(DtSet)  
       DataGridView1.DataSource = DtSet.Tables(0)  
       MyConnection.Close()  
     Catch ex As ApplicationException  
       Throw ex  
     Finally  
     End Try  
   End Sub  
 End Class  

Read Excel 2010 64 bit File on a 64 Bit Machine using OleDB Provider in C#

In the forums where I am a contributor, here's a tip on how to read an excel 2010 64/32 bit file using C#. The Operating System of my machine is Windows 8 64 bit. So, here are the steps.
1. Download AccessDatabaseEngine_x64.exe
For 32 bit excel on windows 8 64 bit machines, download AccessDatabaseEngine.exe
2. Install it in my laptop.
3. Restart my laptop.
3. Change Active Config of Visual Studio Solution to Debug|Any CPU.
For 32 bit excel, choose Debug|X86 4. Clean and Rebuild The Solution.
Code:
Code:
     private void Form1_Load(object sender, EventArgs e)  
     {  
       try  
       {  
         System.Data.OleDbOleDbConnection MyConnection;  
         System.DataDataSet DtSet;  
         System.Data.OleDbOleDbDataAdapter MyCommand;  
         MyConnection = new System.Data.OleDbOleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source='c:\\temp\\test.xlsx';Extended Properties=Excel 12.0;");  
         MyCommand = new System.Data.OleDbOleDbDataAdapter("select * from [Sheet1$]", MyConnection);  
         //MyCommand.TableMappings.Add("Table", "TestTable");  
         DtSet = new System.DataDataSet();  
         MyCommand.Fill(DtSet);  
         dataGridView1.DataSource = DtSet.Tables[0];  //load excel file to datagridview
         MyConnection.Close();  
       }  
       catch (Exception ex)  
       {  
       }  
     }  
Run my program.
Cheers!

Greg

Tuesday, December 3, 2013

The Controls collection cannot be modified because the control contains code blocks(i.e.<% …%>) (ASP.NET HTML Editor Extender)

After adding an HTML Editor extender to my asp.net page, an error shows when rendering the page to the browser as stated which is the title of this post. I found the solution in asp.net forums which is to wrap aspx markup codes enclosed with <% %> using placeholder control. The code below is in my ASP.NET Master Page:
 <head runat="server">  
   <title></title>  
   <link href="~/Styles/Site.css" rel="stylesheet" type="text/css" />  
   <asp:PlaceHolder Runat="server">  
     <script src='<%=Page.ResolveUrl("~/Scripts/jquery-1.4.1.min.js") %>' language="javascript" type="text/javascript"></script>  
   </asp:PlaceHolder>  
   <asp:ContentPlaceHolder ID="HeadContent" runat="server">  
   </asp:ContentPlaceHolder>  
 </head>  
Reference: Handling Ajax Extenders Error
:)

Monday, December 2, 2013

ASP.NET jQuery $find() not working in onclick() event of radio button

In an application where i want trigger the onclick event of radio button that has a $find() method, which will retrieve the radio button's value, the code below doesn't work.
 <input type="radio" id="rb1" name="format" value="format2" runat="server"  
             onclick="$find('<%=dpe1.ClientID %>').populate(this.value);" />d.m.y  
  <input type="radio" id="rb2" name="format" value="format3" runat="server"  
             onclick="$find('<%=dpe1.ClientID %>').populate(this.value);" />y/m/d  
where dpe1 is a DynamicPopulateExtender Ajax Extender.The solution I made was to remove the populate logic and transfer it to a javascript function. Here's the revised code:
 //javascript code  
 function rbFunction() {  
     //$find('<%=dpe1.ClientID %>').populate($("input:radio:checked").val());  
 }  
 //html code  
 <input type="radio" id="rb2" name="format" value="format2" runat="server"  
       onclick="javascript:rbFunction()" />d.m.y  
 <input type="radio" id="rb3" name="format" value="format3" runat="server"  
       onclick="javascript:rbFunction()" />y/m/d  
Cheers!

Thursday, November 28, 2013

ASP.NET Gridview not getting new values in RowUpdating() Event

Assuming in your row updating event, you do some editing in your textbox and then click update button. The event in turn saves your modified records to the database. However, when you tried rebinding the datasource of gridview it seems that you didn't get the newly updated values. The simple trick would be to set the gridview property EnableViewState to false. :)

Get current ID in Task object (C#)

Doing some research on Task (TPL) i wonder if there's a way in retrieving the id of the current task executing. In thread, we can do it like this:
Code:
Thread.CurrentThread.Name; 
The equivalent code in task is shown below:
Code:
int currentTask = Task.CurrentId;  
Greg

Wednesday, November 27, 2013

Pivot or Crosstab SQL Query (REPOST)

Based from Visual Basic Forums, I learned a tip on using Crosstab/Pivot queries. This is presented with SQL Server Execution Plan. It's better to use the concept of the second one compared with the first one.
 SELECT SUM(CASE WHEN DATEDIFF(DAY, upload_package_received_date, GETDATE()) = 0  THEN 1 ELSE 0 END) AS Today,   
           SUM(CASE WHEN DATEDIFF(DAY, upload_package_received_date, GETDATE()) <= 7 THEN 1 ELSE 0 END) AS Last_Week,   
           SUM(CASE WHEN DATEDIFF(DAY, upload_package_received_date, GETDATE()) <= 30 THEN 1 ELSE 0 END) AS [30 Days Ago]  
      FROM temp_uploadpackage  
 SELECT (SELECT COUNT(1) FROM temp_uploadpackage WHERE DATEDIFF(DAY, upload_package_received_date, GETDATE()) = 0)  AS Today,   
     (SELECT COUNT(1) FROM temp_uploadpackage WHERE DATEDIFF(DAY, upload_package_received_date, GETDATE()) <= 7) AS Last_Week,   
     (SELECT COUNT(1) FROM temp_uploadpackage WHERE DATEDIFF(DAY, upload_package_received_date, GETDATE()) <= 30) AS [30 Days Ago]  

Greg

Wednesday, November 20, 2013

Reference System.Web.Mvc in class Library (ASP.NET Mvc)

If your going to add reference to System.Web.Mvc in your class library, simply locate the assembly in Microsoft ASP.NET folder in program files.

Using search in windows explorer in my workstation, the assemblies are located here:
C:\Program Files\Microsoft ASP.NET\ASP.NET MVC (version_number)\Assemblies

Greg

Friday, November 15, 2013

DataGridview current row returns null in SelectionChanged Event

When retrieving selected row cell values in the DataGridview, you might encounter object not set to reference of an instance. It's because the current row has not been initialized. Check first the cell value of the current row if it has cell contents.
Code:
private void dgvAccounts_SelectionChanged(object sender, EventArgs e)  
 {  
   string countryName = string.Empty;  
   if (dgvAccounts.SelectedRows.Count > 0)  
      {  
         if (dgvAccounts.CurrentRow.Cells[1].Value != null)  
      {  
            countryName = dgvAccounts.CurrentRow.Cells[1].Value.ToString();                   
         }        
   }  
 }  
This will ensure that databinding has finished.
Cheers!

Thursday, November 14, 2013

A field or property with the name 'ClassName.Property' was not found on the selected data source (ASP.NET Gridview)

As i was running an asp.net application in my local machine, I encountered an exception which is the title of this post. This asp.net app runs perfectly from the other workstation. I tried searching solutions in google but found out that most of the recommendations were to redo the model or the business tier.

One option I tried was to replace the BoundField of the gridview with TemplateField with label as the bound control using Eval("expression").
Glad that worked. It could be an IIS issue as stated in other forums.
Here's the gridview markup changes:
(Windows 7 64 Bit using BoundField)
 <asp:BoundField DataField="Product.Name" HeaderText="Name" >  
      <ItemStyle Width="350px" />  
 </asp:BoundField>  
(Windows 7 32 Bit using TemplateField)
  <asp:TemplateField HeaderText="Product Name">  
     <ItemStyle Width="350px"/>  
     <ItemTemplate>  
     <asp:Label ID="lblProductName" Text='<%# Eval("Product.Name")%>' runat="server">     
     </asp:Label>  
     </ItemTemplate>                
  </asp:TemplateField>  
Note: I also tested the program in a Windows 8 64 Bit machine. TemplateField simply works. I believe that BoundField has some issues with 32 bit machines.
Cheers!

Using AutoMapper in Asp.Net Database Application

Hello,
Based from Scott Millet's Asp.Net Design Patterns, I was curious on the AutoMapper Framework that maps Domain Entities to View Models. So I tried to give it a spin. Here's the code snippets breakdown:
Order class:
Code:
   /// <summary>  
   /// One order may contain one or many order details.  
   /// </summary>  
   public class Order  
   {  
     public int OrderId { get; set; }  
     public DateTime OrderDate { get; set; }  
     public DateTime RequiredDate { get; set; }  
     public string ShipName { get; set; }  
     public string ShipAddress { get; set; }  
     public IList<OrderDetails> OrderDetail { get; set; }  
   }
Order View class:
Code:
 public class OrderView  
   {  
     public int OrderId { get; set; }  
     public DateTime OrderDate { get; set; }  
     public DateTime RequiredDate { get; set; }  
     public string ShipName { get; set; }  
     public string ShipAddress { get; set; }  
     public IList<OrderDetails> OrderDetail { get; set; }  
   }  
Bootstrapper class:
Code:
//Bootstrapper class  
 public class BootStrapper  
   {  
     public static void ConfigureAutoMapper()  
     {  
       Mapper.CreateMap<Customer, CustomerView>();  
       Mapper.CreateMap<Order, OrderView>();  
       Mapper.CreateMap<OrderDetails, OrderDetailsView>();  
     }  
   }  
Global.asax:
Code:
//Global.asax 
void Application_Start(object sender, EventArgs e) 
{ 
   // Code that runs on application startup       
   BootStrapper.ConfigureAutoMapper(); 
} 
OrderExtension class:
Code:
public static class OrderExtensionMethods  
  {  
    public static OrderView ConvertToOrderView(this Order order)  
    {  
      return Mapper.Map<Order, OrderView>(order);  
    }  
  }  
Order Service class:
Code:
//OrderService class method  
 public CustomerView GetAllOrders(string Id)  
 {  
      CustomerView customerView;  
      ModelCustomer customer = new ModelCustomer();  
      customer.Orders = _orderRepository.FindAllOrders(Id);  
      customerView = customer.ConvertToCustomerView();  
      return customerView;  
 }  
Order Repository class:
Code:
/// <summary>  
     /// Repository class  
     /// Search orders by customer id.  
     /// </summary>  
     public IList<Model.Order> FindAllOrders(string Id)  
     {  
       var Orders = from _order in context.Orders  
              where _order.CustomerID == Id  
              select _order;  
       foreach (var item in Orders)  
           {  
         orders.Add(new ModelOrder()  
         {  
           OrderId = item.OrderID,  
           RequiredDate = Convert.ToDateTime(item.RequiredDate),  
           ShipAddress = item.ShipAddress,  
           ShipName = item.ShipName,  
           OrderDate = Convert.ToDateTime(item.OrderDate),  
           //get details per order  
           OrderDetail = FindAllOrderDetails(item.OrderID)   
         });  
           }  
       return (IList<Model.Order>)orders;  
     }  
Running asp.net website:
As you noticed from the image above, a customer's placed orders
are shown in the first gridview. While the order details of a
specific order is displayed on the second grid.

The asp.net sample focused on the Northwind database.
This application will retrieve all customers and their placed
orders. Additionally, this will retrieve the order details for
a specific order.

Basically, I just derived the concept from Scott's sample and
translatting it to a database project. The changes made for this
application is minimal.

Cheers!

Monday, November 11, 2013

WPF Datagrid Paging in VB.NET using CollectionView class

Based from the solution posted by timmyl here: How can I paginate a WPF DataGrid?. I managed to fix some bugs and added some functionalites such as MoveToFirstPage and MoveToLastPage.

Paging Class
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
Option Infer On  
 Imports System.Collections  
 Imports System.Collections.Generic  
 Imports System.ComponentModel  
 Imports System.Windows.Data  
 
 
 Public Class PageCollectionView  
   Inherits CollectionView  
   Private ReadOnly _innerList As IList  
   Private ReadOnly _itemsPerPage As Integer  
   Private _currentPage As Integer = 1  
   
 
   ' Constructor  
   Public Sub New(ByVal innerList As IList, ByVal itemsPerPage As Integer)  
     MyBase.New(innerList)  
     Me._innerList = innerList  
     Me._itemsPerPage = itemsPerPage  
   End Sub  
   
 
   Public Overrides ReadOnly Property Count() As Integer  
     Get  
       Return Me._itemsPerPage  
     End Get  
   End Property  
   
 
   Public Property CurrentPage() As Integer  
     Get  
       Return _currentPage  
     End Get  
     Set(ByVal value As Integer)  
       _currentPage = value  
       Me.OnPropertyChanged(New PropertyChangedEventArgs("CurrentPage"))  
     End Set  
   End Property
  
  
   Public ReadOnly Property ItemsPerPage() As Integer  
     Get  
       Return Me._itemsPerPage  
     End Get  
   End Property
   
  
   Public ReadOnly Property PageCount() As Integer  
     Get  
       Return (Me._innerList.Count + Me._itemsPerPage - 1) _  
           / Me._itemsPerPage  
     End Get  
   End Property  
   
 
   Private ReadOnly Property EndIndex() As Integer  
     Get  
       Dim _end = Me._currentPage * Me._itemsPerPage - 1  
       Return If(_end > Me._innerList.Count, Me._innerList.Count, _end)  
     End Get  
   End Property
 
  
   Private ReadOnly Property StartIndex() As Integer  
     Get  
       Return (Me._currentPage - 1) * Me._itemsPerPage  
     End Get  
   End Property
 
  
   Public Overrides Function GetItemAt(ByVal index As Integer) As Object  
     Dim offset = index Mod (Me._itemsPerPage)  
     If (((Me.StartIndex + offset) >= Me._innerList.Count)) Then  
       Return New Object  
     Else  
       Dim temp = Me._innerList(Me.StartIndex + offset)  
       Return Me._innerList(Me.StartIndex + offset)  
     End If  
   End Function  
 
 
   Public Sub MoveToFirstPage()  
     If Me._currentPage >= 1 Then  
       Me.CurrentPage = 1  
     End If  
     Me.Refresh()  
   End Sub  
 
 
   Public Sub MoveToPreviousPage()  
     If Me._currentPage > 1 Then  
       Me.CurrentPage -= 1  
     End If  
     Me.Refresh()  
   End Sub  
 
 
   Public Sub MoveToNextPage()  
     If Me._currentPage < Me.PageCount Then  
       Me.CurrentPage += 1  
     End If  
     Me.Refresh()  
   End Sub  
 
 
   Public Sub MoveToLastPage()  
     If Me._currentPage < Me.PageCount Then  
       Me.CurrentPage = Me.PageCount  
     End If  
     Me.Refresh()  
   End Sub  
 End Class

Screenshot:
Note: I didnt include the source code for XAML declaration and the code behind since it can be converted easily.

Greg

Wednesday, November 6, 2013

DataGridview Paging using BindingSource and BindingNavigator in VB.NET

Hi,
In reference to the previous post on DataGridView paging using C# (see link below)
Datagridview paging using BindingSource in C#
I developed a Visual Basic.NET version for your reference:
Main Form Class:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
Option Infer On  
      Imports System.Configuration  
      Imports System.ComponentModel  
      Imports MySql  
      Imports MySql.Data  
      Imports MySql.Data.MySqlClient  
      Public Class FBinding  
        Public Property TotalRecords() As Integer  
        Public Const PageSize = 10  
       Private sourceData As New List(Of String)  
       Private dtSource As New DataTable  
       Dim page As New PageOffsetList()  
       Public Sub New()  
         ' This call is required by the designer.  
         InitializeComponent()  
         ' Add any initialization after the InitializeComponent() call.  
         Me.bindingNav.BindingSource = bindingWebsite  
         AddHandler Me.bindingWebsite.CurrentChanged, AddressOf Me.bindingWebsite_CurrentChanged  
         SetSource()  
       End Sub  
       Private Sub FBinding_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load  
         Me.bindingWebsite.DataSource = page  
       End Sub  
       Private Sub bindingWebsite_CurrentChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bindingWebsite.CurrentChanged  
         Dim offset As Integer = CType(Me.bindingWebsite.Current, Int32)  
         Dim records As New List(Of Record)  
         Dim i As Integer = offset  
         While i < offset + PageSize AndAlso i < TotalRecords  
           records.Add(New Record() With  
           { _  
             .Website = sourceData(i).ToString() _  
           })  
           i += 1  
         End While  
         dgWebsites.DataSource = records  
       End Sub  
       Private Sub SetSource()  
         Dim sql As String = "select trim(website_host), url_host from table_website order by trim(website_host) asc"  
         Dim conn As MySqlConnection  
         conn = Nothing  
         Try  
           Dim connection As String = ConfigurationManager.AppSettings("WebsiteConnection").ToString()  
           conn = New MySqlConnection(connection)  
           conn.Open()  
           Dim cmd As New MySqlCommand(sql, conn)  
           Dim da As New MySqlDataAdapter(cmd)  
           da.Fill(dtSource)  
           If dtSource.Rows.Count Then  
             For Each item As DataRow In dtSource.Rows  
               If Not String.IsNullOrEmpty(item(0).ToString()) AndAlso Not String.IsNullOrEmpty(item(1).ToString()) Then  
                 sourceData.Add(item(0).ToString() & ", " & item(1).ToString())  
               End If  
             Next  
           End If  
           TotalRecords = sourceData.Count  
           conn.Close()  
         Catch ex As Exception  
           conn.Close()  
           conn.Dispose()  
         End Try  
       End Sub  
     End Class  

PageOffList Class:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
Option Infer On  
 Imports System.ComponentModel  
 Public Class PageOffsetList  
   Implements IListSource  
   Public ReadOnly Property ContainsListCollection() As Boolean _  
     Implements System.ComponentModel.IListSource.ContainsListCollection  
     Get  
       Return False  
     End Get  
   End Property  
   Public Function GetList() As System.Collections.IList _  
     Implements System.ComponentModel.IListSource.GetList  
     Dim pageOffset As New List(Of Int32)  
     Dim offset As Integer = 0  
     While offset <= FBinding.TotalRecords  
       pageOffset.Add(offset)  
       offset = offset + FBinding.PageSize  
     End While  
     Return pageOffset  
   End Function  
 End Class 

Record Class:
1
2
3
Public Class Record  
   Public Property Website As String  
 End Class

Output: Cheers!

DataGridview Paging using BindingSource and BindingNavigator in C#

Here's a simple way to integrate paging in Datagridview using BindingNavigator and BindingSource. The original source can be found here: How can we do paging in datagridview in winform
I made some modifications to simulate loading of thousands of records from a database.
Main Form Class:
public partial class FBinding : Form  
{  
 public static int totalRecords { get; set; }  
 public const int pageSize = 10;  
 private List<string> sourceData = new List<string>();  
 private DataTable dtSource = new DataTable();        
 public FBinding()  
 {  
   InitializeComponent();  
   bindingNav.BindingSource = bindingWebsite;  
   bindingWebsite.CurrentChanged += new EventHandler(bindingWebsite_CurrentChanged);  
   SetSource();  
   bindingWebsite.DataSource = new PageOffsetList();  
 }  
 void bindingWebsite_CurrentChanged(object sender, EventArgs e)  
 {  
   // The desired page has changed, so fetch the page of records using the "Current" offset   
   int offset = (int)bindingWebsite.Current;  
   var records = new List<Record>();  
   for (int i = offset; i < offset + pageSize && i < totalRecords; i++)  
   {  
  try  
  {  
    records.Add(new Record() { Website = sourceData[i].ToString() });  
  }  
  catch (Exception ex)  
  {  
  }  
   }  
   dgWebsites.DataSource = records;  
 }  
 private void SetSource()  
 {  
   string sql = string.Format("select trim(website), url from tblwebsite order by trim(website) asc;");  
   MySqlConnection conn = null;  
   try  
   {  
  string connection = ConfigurationManager.AppSettings["AdminWebsite"].ToString();  
  conn = new MySqlConnection(connection);  
  conn.Open();  
  MySqlCommand cmd = new MySqlCommand(sql, conn);  
  MySqlDataAdapter da = new MySqlDataAdapter(cmd);  
  da.Fill(dtSource);  
  if (dtSource.Rows.Count > 0)  
  {  
    //totalRecords = dtSource.Rows.Count;  
    foreach (DataRow item in dtSource.Rows)  
    {  
   if (!string.IsNullOrEmpty(item[0].ToString()) && !string.IsNullOrEmpty(item[1].ToString()))  
   {  
     sourceData.Add(item[0].ToString() + ", " + item[1].ToString());  
   }  
    }  
  }  
  totalRecords = sourceData.Count;  
  conn.Close();  
   }  
   catch (Exception e)  
   {  
  conn.Close();  
  conn.Dispose();  
   }  
 }  
 private void FBinding_Load(object sender, EventArgs e)  
 { }  
}  
Here's the classes used in Databinding:
public class Record   
{   
    public string Website { get; set; }   
}  
Paging class:
public class PageOffsetList : IListSource   
   {   
    public bool ContainsListCollection    
    {    
     get;    
     protected set;   
    }   
    private int TotalRecords = 0;   
    private int pageSize = 0;   
    public PageOffsetList(int pageSize, int total)   
    {   
     this.TotalRecords = total;   
     this.pageSize = pageSize;   
    }   
    public System.Collections.IList GetList()   
    {      
     // Return a list of page offsets based on "totalRecords" and "pageSize"   
     var pageOffsets = new List<int>();   
     for (int offset = 0; offset <= TotalRecords; offset = offset + pageSize)   
     {   
      pageOffsets.Add(offset);   
     }   
     return pageOffsets;   
    }   
   }   
Here's the result of the program:
I also segregated the classes in my application to simplify the approach.
Thanks to the original source! :)

Monday, November 4, 2013

Textbox custom controls with Autosuggest Features (C#)

A textbox custom control developed by Aland Li, MSDN Moderator was the basis for the creation of three new versions of textbox custom controls with Autosuggest features. I managed to fixed some bugs and improve the functionalities of the control.

The first control integrates Suggest + Append feature.
The second control integrates exact keyword searching which is a limitation to the built-in .NET textbox autosuggest feature that is using startswith algorithm.
The third control is an enhancement of the second control
with keyword highlighting,
Thanks to the original creator of the control

Cheers.

Measure width of a given string in pixel (REPOST)

Here's a function to compute the text width of a given string
in pixel. Original Author: Mongus Pong (Stack Overflow)
Code:
protected int _MeasureDisplayStringWidth ( Graphics graphics, string text, Font font, float    
        width, float height )  
      {  
           if ( text == "" )  
                return 0;  
           StringFormat format = new StringFormat ( StringFormat.GenericDefault );  
           RectangleF rect = new RectangleF ( 0, 0, width, 1000 );  
           CharacterRange[] ranges = { new CharacterRange ( 0, text.Length ) };  
           Region[] regions = new Region[1];  
           format.SetMeasurableCharacterRanges ( ranges );  
           format.FormatFlags = StringFormatFlags.MeasureTrailingSpaces;  
           regions = graphics.MeasureCharacterRanges ( text, font, rect, format );  
           rect = regions[0].GetBounds ( graphics );  
           return (int)( rect.Right );  
      }  

Greg

Wednesday, October 30, 2013

Close ToolStripDropdown object when parent container/form is clicked

To close the ToolStripDropdown object which is part of the textbox custom control, add event handler signatures and event definition using the code below:
Code:
//add statements in the custom control constructor  
  this.Parent.Click += new EventHandler(Parent_Click);  
  this.Parent.Move += new EventHandler(Parent_Click);  

 //event body  
  private void Parent_Click(object sender, EventArgs e)  
 {  
      _dropDown.Close(); //ToolStripDropdown object  
  }  
Cheers!

Focus or Caret on TextBox Control gone if ToolstripDropdown is shown.

Im trying to implement a custom textbox control with auto-suggest features. Upon rendering the ToolStripDropdown object just below the textbox control, the focus seems to be lost.

I found the trick by setting the AutoClose property to false in the Textbox OnHandleCreated(EventArgs e) event. See the code below:
Code:
 _dropDown.AutoClose = false; //ToolStripDropDown object 

Greg

Friday, October 25, 2013

Include Foreign Key Columns In The Model Disabled (ADO.NET Entity Framework)

When adding database objects to your entity data model, The checkbox option labeled (Include foreign key columns in the model) might be disabled.

I later found out that the class library's target framework was .NET 3.5 Framework. While the solution and asp.net website's
target framework is .NET 4.0.

The solution was to change the target framework to .NET 4.0 then recompiled the class library. Alas! the include foreign key columns is now enabled.

Cheers!

Wednesday, October 23, 2013

Accessing app.config values in class library not working (C#)

In a project that we are working with involves several class libraries. And one of them involves setting/getting the connection string. We simply added an application config file with the connection string in it. However, accessing the key/value of connection string returns null.

One possible solution is to add a Settings file in the class library where you can set the connection string. And to access the connection string value, refer to the code below:
 //Settings is the Settings File.  
 //SalesConnection is the Name of the connection string  
  return new Settings().SalesConnection;  
Here's a similar post regarding Settings File:
Setting app.config in ASP.NET
Cheers!

AnimationExtender Animation using JSON not working (ASP.NET)

When setting animations for AnimationExtender control using JSON/Javascript, setting the AnimationTarget with the explicit control id such as panel ID does not work when rendered to browser specified by the code below:
 "AnimationTarget":"panelDescription"  
The workaround is to get the clientID of the panel control rendered through the browser. Below is the workaround code:
   1:  //Note: this is just a fragment of the JSON animation  
   2:  //the actual animation might be a little bit specific than this.  
   3:  var animation = "AnimationTarget":"' 
   4:  + '<%= panelDescription.ClientID %>' + '","AnimationChildren"';  
   5:  //set click behavior  
   6:  animationExtender.set_OnClick(animation);
Cheers!

Sunday, October 20, 2013

Multiple controls with the same ID '_header' were found. FindControl requires....(Asp.net Ajax)

Good day!

After integrating ajax accordion pane controls in my asp.net app,
An exception pops up as stated by the title of the post.

The culprit was that I initialized two AccordionPane objects w/o
specifying the ID's of each object.

The solution is to include ID's in each control.See example below:
Code:
AccordionPane ap1 = new AccordionPane();  
 ap1.ID = "ap1";  
 ap1.HeaderContainer.Controls.Add(new LiteralControl("Product Code"));  
 ap1.ContentContainer.Controls.Add(new LiteralControl(datarow["ID"].ToString();));  

 AccordionPane ap2 = new AccordionPane();  
 ap2.ID = "ap2";  
 ap2.HeaderContainer.Controls.Add(new LiteralControl("Product Name"));  
 ap2.ContentContainer.Controls.Add(new LiteralControl(datarow["Prod_Name"].ToString();));
Greg

Friday, October 11, 2013

.NET 4.5 Framework Features

Here's an image i got from 
http://muralitharan.info blog.
Thanks to the guy who uploaded this image... :)


Greg

Thursday, October 10, 2013

Combobox with CheckListBox supports Multi highlighting (C#)

A control developed by: Stelios Alexandrakis which I found it cool
is a combobox with checklistbox as the dropdown item.

After fixing a few bugs, I integrate the feature of multi-highlighting
based from the previous post on customizing CheckListBox control:
CheckBoxList Multihighlight
Here's some screenshots to illustrate each of the custom controls.
Cheers!

Tuesday, October 8, 2013

CheckBoxList control with multi-highlighting support (C#)

If you want to customize the CheckBoxList control to support multi-highlighting (each checked item is highlighted), you can simply override the OnDrawItem() by adding Graphics statements as shown below:
Here's an image sample of the extended CheckBoxList control:
Cheers!
Code:
     protected override void OnDrawItem(DrawItemEventArgs e)  
     {  
       int index = e.Index;  
                if (this.GetItemCheckState(index) == CheckState.Checked)  
                {  
                     string text = this.Items[index].ToString();  
                     Graphics g = e.Graphics;  
                     Point point = this.GetItemRectangle(index).Location;  
                     point.X += estimated_point; //estimated point is a value you may set manually  
                     //background:  
                     SolidBrush backgroundBrush;            
                     backgroundBrush = reportsBackgroundBrushSelected;  
                     //estimated point is a value you may set manually  
                     g.FillRectangle(backgroundBrush, estimated_point , e.Bounds.Y, this.Width, e.Bounds.Height);  
                     //text:  
                     SolidBrush foregroundBrush = reportsForegroundBrushSelected;  
                     g.DrawString(text, e.Font, foregroundBrush, point);  
                }        
     }  

Tuesday, October 1, 2013

Custom Extender type/class is undefined in AjaxToolkit/ASP.NET

Hi!
When running an asp.net app that includes an ajax custom extender control, a javascript alert pops up message "EXTENDER is undefined". Sample error message:
CustomExtenders.DisabledTextBehavior is undefined
where: CustomExtenders.DisabledTextBehavior is Namespace.Type

After troubleshooting for several hours, I came up with the solution:
1. Download Ajax Toolkit Stable Release for the specific .NET Framework.
 I tried versions for September release and it's not working.
2. Replace code:
Code:
CustomExtenders.DisabledTextBehavior.registerClass('CustomExtenders.DisabledTextBehavior', AjaxControlToolkit.BehaviorBase);  
To
Code:
CustomExtenders.DisabledTextBehavior.registerClass('CustomExtenders.DisabledTextBehavior', Sys.Extended.UI.BehaviorBase); 

Note: AjaxControlToolkit.BehaviorBase is used in previous versions of AjaxToolkit.
Cheers!

AjaxControlToolkit ExtenderControlBaseDesigner class requires T

Hello!

The previous version of ExtenderControlBaseDesigner does not require T as parameter. However, in recent versions you might notice that the class is declared with T. Here's a sample declaration:
Code:
AjaxControlToolkit.Design.ExtenderControlBaseDesigner<T>  

T means AjaxControlToolkit.ExtenderControlBase. In order for the Custom Extender Designer to work, supply the T with class that inherits the ExtenderControlBase. This sample class inherits the ExtenderControlBase:
Code:
public class CustomPanelExtender : ExtenderControlBase  
 {  
    //your code goes here....  
 } 

Show Smart Tag(Shift + Alt + F10) is disabled/greyed in ASP.NET Server Control

When adding ajax extenders to asp.net server controls using Smart Tag, you often encounter an issue such as Show Smart Tag is greyed out/disabled.

The best thing to do is to use the latest stable version of AjaxToolkit.
And then, reset the toolbox. Sometimes, you have to close the Visual Studio IDE just to make sure.

IDE Version: Visual Studio 2010 Professional
Ajax Toolkit Binary: AjaxControlToolkit.Binary.NET4 (Stable Version)

Cheers!

Saturday, September 21, 2013

SQL Server 2012 Pre-Requisite Issue

Hi all!

On a Windows 8 environment where in you have VS 2010 installed and you want to add SQL Server 2012 to your list of software, install first VS 2010 SP1 to make changes to setup configurations.

Cheers!

Visual Studio 2008 Failed Install on WIndows 8

Solution:

Turn on .NET Framework 3.5 which is built-in Windows 8. Make sure windows updates is turned on also.

Cheers!

Wednesday, September 18, 2013

Change BIOS Boot Options for Acer Aspire V5-431P/471P

Useful Acer Tip: Change BIOS Boot Options for Acer Aspire V5-431P/471P
(I Series)

1. Restart/Shutdown the Laptop
2. Tap F2 key on startup
3. When BIOS interface appears, go to Boot Menu
4. Change Boot Mode to Legacy BIOS.
5. Restart Again the laptop and perform step 2.
6. Set the Boot Priority of Devices using F5/F6.

Monday, September 16, 2013

SQL Server Function Date Range Example

The function below retrieves the top Freight amount specified by date range values
 use CompanySales  
 IF object_id (N'dbo.GetTopFreightValueRange', N'FN') IS NOT NULL  
 drop function GetTopFreightValueRange  
 go  
 create function GetTopFreightValueRange  
 (  
   @startDate nvarchar(50), @endDate nvarchar(50)  
 )  
 returns decimal(10,2)   
 as  
 begin   
 declare @result varchar(50)   
      set @result =   
      (  
            select FreightAmount   
                 from dbo.Orders  
            where CONVERT(VARCHAR(10), ShippedDate, 120) >= @startDate  
                  and  
                  CONVERT(VARCHAR(10), ShippedDate, 120) <= @endDate  
      )  
 return @result  
 end  
 go  
-- select dbo.GetTopFreightValueRange('1996-11-01','1996-11-30') as freight_value;