Posts

Showing posts from 2013

Donate

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!

Remove Extra Spacing In Between NumericUpDownExtender Default Buttons (ASP.NET Ajax)

Image
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 to remove the extra space in between NumericUpDownExtender Default Buttons is 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!

Append Text To Textfile In FTP Or SFTP Using SSH.NET

Hello, 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. 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( "Con

Get All Records Before The Last Inserted Record In SQL Server T-SQL

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

Check If File Exists On FTP Server Using C# Or VB.NET

Method in VB.NET and C# here: File Exists on FTP Server

Predicate Wrapper Custom Class in VB.NET

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

Read Excel 2010 64 Bit File On A 64 Bit Machine Using OleDB Provider In VB.NET

Hello, Here's the VB.NET Version of this post Read Excel 2010 64 bit file using OleDB Provider in C# on how to read Microsoft Excel 64 Bit File On a 64 bit maching using OleDB Provide and VB.NET as the language. 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 T

Read Excel 2010 64 Bit File On A 64 Bit Machine Using OleDB Provider In C#

Good afternoon! 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: 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.OleDb

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

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

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: Thread.CurrentThread.Name; The equivalent code in task is shown below: int currentTask = Task.CurrentId; Greg

Pivot Or Crosstab SQL Query Example

Image
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 Second Example 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

How To 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

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

A field or property with the name 'ClassName.Property' was not found on the selected data source In 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= &quo

Using AutoMapper In Asp.Net Web Forms Database Application

Image
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 by incorporating the tool in an ASP.NET WebForms application. Here's the code snippets breakdown: Order class: /// <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: public class OrderView { public int OrderId { get ; set ; } public DateTime OrderDate { get ; set ; } public DateTime RequiredDate { get ; set ; } public string ShipName { get ; set ;

WPF Datagrid Paging In VB.NET Using CollectionView Class

Image
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

DataGridview Paging Using BindingSource And BindingNavigator In VB.NET

Image
Hi, In reference to the previous post on DataGridView paging using C# Datagridview paging using BindingSource in C# , I developed a Visual Basic.NET version for VB.NET Developers. 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 initiali

DataGridview Paging Using BindingSource And BindingNavigator In C#

Image
Hello, VB.NET Version Here: DataGridview Paging Using BindingSource And BindingNavigator In VB.NET 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, EventAr

Textbox Custom Controls With Autosuggest Features In C# Windows Forms

Image
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 Using C# And Windows Forms

Here's a function to compute the text width of a given string in pixel. Original Author: Mongus Pong (Stack Overflow) 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

Close ToolStripDropdown Object When Parent Container Or Form Is Clicked In C# Windows Forms

To close the ToolStripDropdown object which is part of the textbox custom control, add event handler signatures and event definition using the code below: //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 In Custom Controls Windows Forms C#

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: _dropDown.AutoClose = false ; //ToolStripDropDown object Greg

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!

Accessing App.Config Values In Class Library Not Working In 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 In 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: //Note: this is just a fragment of the JSON animation //the actual animation might be a little bit specific than this. var animation = "AnimationTarget":"' + '<%= panelDescription.ClientID %>' + '","AnimationChildren"'; //set click behavior animationExtender.set_OnClick(animation); Cheers!

Multiple controls with the same ID '_header' were found. FindControl requires In 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: 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();)) Cheers!

.NET 4.5 Framework Features

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

Combobox With CheckListBox Supports Multi highlighting (C#)

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

CheckBoxList Control With Multi-Highlighting Support In C# Windows Forms

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

Custom Extender Type Or 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: CustomExtenders.DisabledTextBehavior.registerClass( 'CustomExtenders.DisabledTextBehavior' , AjaxControlToolkit.BehaviorBase); To 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: 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: public class CustomPanelExtender : ExtenderControlBase { //your code goes here.... }

Show Smart Tag(Shift + Alt + F10) Is Disabled Or Greyed In ASP.NET Web Forms 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!

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 Operating System

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

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

Image
Hello and Good afternoon! Here's a useful Acer Aspire V5-431P/471P Tip that is to 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.

Donate