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!