Tuesday, December 18, 2012

Get Textbox or RichtextBox value using pInvoke (Windows API)

Assuming you already get the pointer handle of the textbox/richtextbox control from source calling function, the snippet to get the content of the edit control is as follows.
Code:
public const int GWL_ID = -12;  
 public const int WM_GETTEXT = 0x000D;  
 [DllImport("User32.dll")]  
 public static extern int GetWindowLong(IntPtr hWnd, int index);  
 [DllImport("User32.dll")]  
 public static extern IntPtr SendDlgItemMessage(IntPtr hWnd, int IDDlgItem, int uMsg, int nMaxCount, StringBuilder lpString);  
 [DllImport("User32.dll")]  
 public static extern IntPtr GetParent(IntPtr hWnd);  
 private StringBuilder GetRichEditText(IntPtr hWndRichEdit)  
 {  
   Int32 dwID = GetWindowLong(hWndRichEdit, GWL_ID);  
   IntPtr hWndParent = GetParent(hWndRichEdit);  
   StringBuilder title = new StringBuilder(128);  
   SendDlgItemMessage(hWndParent, dwID,  
     WM_GETTEXT,  
     128, title);  
   return title;  
 } 
For labels and buttons, you use the GetWindowText() function... :)

Greg

Sunday, December 16, 2012

WPF Webbrowser loop through html elements and submit

A question was raised on vbforums on how to invoke click a button using WPF webbrowser control. This sample loads google.com page and writes a sample text on the textbox and then invoking the click button.
Code:
 HTMLDocument document = (HTMLDocument)wbGetHost.Document;  
       foreach (IHTMLElement myelem in document.getElementsByTagName("input"))  
       {  
         if (myelem.id != null)  
         {  
           if (myelem.id.Equals("lst-ib") && myelem.className.Equals("lst lst-tbb") && !document.documentElement.innerHTML.ToLower().Contains("wikipedia"))  
           {  
             HTMLInputElement el = myelem as HTMLInputElement;  
             el.value = "Bill Gates";  
             HTMLInputElement searchButton = (HTMLInputElement)document.all.item("btnK", 0);  
             searchButton.click();  
             break;  
           }  
         }  
       } 
Greg

Thursday, December 6, 2012

The controller for path /favicon.ico does not implement IController

In an application using Controller factory, i encountered an error as stated in the title. My MVC does not have a favicon.ico. The solution is to add a parameter constraint that does not allow .ico filenames in your routes. I got the solution from forums.asp.net
Code:
 routes.MapRoute(  
           "Default",                       // Route name  
           "{controller}/{action}/{id}",              // URL with parameters  
           new { controller = "ProductView", action = "Index", id = "" }, // Parameter defaults  
           new { controller = @"[^\.]*" }    // Parameter constraints (regex/string expression)  
         ); 

Wednesday, December 5, 2012

Count duplicate or repeating records from union all query

Here's a query to count number of repeating records based from union all query. Union all query does not remove duplicate records. Here's a sample script:
1:  select resultsduplicate.url as job_item,  
2:  count(resultsduplicate.url) as repeat_occurence  
3:  from  
4:  (  
5:    SELECT url FROM mainTable  
6:     where id = 47 and url like '%testsite.com%' and _active = 1  
7:    UNION ALL  
8:    SELECT url FROM detailTable  
9:     where id = 47 and url like '%testsite.com%' and _active = 1  
10:  )resultsduplicate   
11:  group by resultsduplicate.url  
12:  having (count(resultsduplicate.url) >1);  
Original Source (Stackoverflow.com) Cheers!

Tuesday, December 4, 2012

Content Types/MIME Types List in ASP.NET(MVC)

I have searched for content types which is suitable for asp.net or asp.net mvc applications using the HttpResponse class ContentType property.

Here's the website with the MIME list: Mime Type List

Here's a sample asp.net/mvc snippet.
Code:
HttpResponseBase response = context.HttpContext.Response;  
response.ContentType = "application/pdf";  

Greg

Sunday, December 2, 2012

Codeformatter

Code formatter with line numbers...

http://codeformatter.blogspot.com/

Wednesday, November 28, 2012

WPF controls not rendering properly on Windows 7 OS

The problem was that the windows 7 theme was changed to classic window. Turning it back to Windows 7 default view, solved it.

Greg

Wednesday, November 21, 2012

Check if controls on another wpf window have rendered using thread

Given you have two WPF windows namely MainWindow and OtherWindow. You basically want to check if the controls in main window have successfully loaded using statements in OtherWindow. The solution is to use Application dispatcher object.
Code:
if(Application.Current.Dispatcher.CheckAccess())
        {  
          while (true)  
          {  
            foreach (Window window in Application.Current.Windows)  
            {  
              if (window.Title.Equals("Project Title"))  
              {  
                if (window.FindName("your_control") != null)  
                {  
                  //do your stuff here...  
                }  
              }  
            }  
            break;  
          }  
        }  
        else  
        {  
          Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(CheckMainWindow));  
        }  
Cheers!

Tuesday, November 20, 2012

GC.Collect() method slowing web crawlers

In our web crawlers, we encountered slow crawling of items specially XML feeds. We checked our codes if there are lines generating bottlenecks.

It turned out that we placed GC.Collect() in an inner loop that's processing item per item.

The solution is to comment out GC.Collect() in the inner loop and transfer it to the outer loop statement. Here's the code:
Code:
  while(!EndOfPage)  
  {  
    do  
    {  
      if(date != String.empty)  
      {  
       //comment this statement, transfer outside inner loop...  
       //GC.Collect();  
       //processing of items code statements...      
      }  
    } while (!(url.Equals(String.Empty)));  
    GC.Collect();  
    PageNo++;  
    if(PageNo > totalPage)   
    {   
      EndOfPage = true;   
    }  
  }

Credits to my fellow developer for the discovery.

Greg

Monday, November 19, 2012

Regex Match Capture Index Property Returns 0 instead of -1

Yesterday, while working on Regex Index property, I encountered a weird problem. Supposedly, string.indexOf(string variable) returns -1 value if there's no occurrence of such substring. However, using
Code:
Regex.Match(source.ToLower(), @"regex pattern").Index
returns 0 if instead of -1 if no such substring occurs. The solution was pointed out in stack overflow: Return index position of string after match found using Group.Success in which case returns a boolean value.
So, here's the tip:
Code:
  if ((Regex.Matches(source.ToLower(), @"<ol[^>]*>").Count < 1)   
  && (Regex.Matches(source.ToLower(), @"<ul[^>]*>").Count > 0))  
  {  
    if (Regex.Match(source.ToLower(), @"<ul[^>]*>", RegexOptions.IgnoreCase).Success)  
    {  
      // your if statements here.... :)      
    }    
  } 
Greg

Thursday, November 15, 2012

Custom DatagridviewCheckboxColumn

Here's a simple class implementation of a DatagridviewCheckboxColumn.
Code:
public class DatagridviewCustomCheckboxColumn : DataGridViewCheckBoxColumn   
   {   
     public DatagridviewCustomCheckboxColumn()   
     {   
      this.CellTemplate = new DatagridviewCheckboxCustomCell();   
    }   
   }   
   class DatagridviewCheckboxCustomCell : DataGridViewCheckBoxCell   
   {     
    public int row_index { get; set; }   
    public int CheckboxHeight    
    {   
     get   
     {   
      //your_desired_checkbox_height is a variable   
      //that contains the desired height of your checkbox   
      //you may set or get the property value..   
      return your_desired_checkbox_height;   
     }   
    }   
    public int CheckboxWidth    
    {   
     get   
     {   
      //your_desired_checkbox_width is a variable   
      //that contains the desired width of your checkbox   
      //you may set or get the property value..   
      return your_desired_checkbox_width;   
     }    
    }   
    /// <summary>   
    /// constructor   
    /// </summary>   
    public DatagridviewCheckboxCustomCell()   
    {   
    }   
    protected override void Paint(Graphics graphics, Rectangle clipBounds, Rectangle cellBounds, int rowIndex, DataGridViewElementStates elementState,    
     object value, object formattedValue, string errorText, DataGridViewCellStyle cellStyle, DataGridViewAdvancedBorderStyle advancedBorderStyle,    
     DataGridViewPaintParts paintParts)   
    {   
     base.Paint(graphics, clipBounds, cellBounds, rowIndex, elementState, value, formattedValue, errorText, cellStyle, advancedBorderStyle, paintParts);   
     this.row_index = rowIndex;   
     //create rectangle object then set    
     //the x,y,height,width based on your desired    
     //rectangle size...   
     Rectangle rect = new Rectangle();   
     if (value != null)   
     {   
      if ((bool)value)   
      {   
       graphics.FillRectangle(Brushes.Blue, rect);   
      }   
      else   
      {   
       graphics.FillRectangle(Brushes.Green, rect);   
      }   
     }   
    }   
   } 
The output resembles to the form shown below.

You may noticed that the last column in the datagridview shows a checkbox painted with colors rather than having checkmarks . True values are painted with blue while false values are painted with green. Cheers!

Monday, November 12, 2012

Highligh GridView Row on click in ASP.NET (REPOST)

This is based from the article of Vincent Maverick Durano's blog on HIGHLIGHT GRIDVIEW ROW ON CLICK AND RETAIN SELECTED ROW ON POST BACK.

I just added some statements on javascript to check if the selected row is less than total gridview row count and server side code for paging.
JAVASCRIPT CODE:
1:  <script type="text/javascript">  
2:    var prevRowIndex;  
3:    function ChangeRowColor(row, rowIndex) {  
4:      var parent = document.getElementById(row);  
5:      var currentRowIndex = parseInt(rowIndex) + 1;  
6:      //count number of gridview rows  
7:      var rowscount = $("#<%=grdCustomer.ClientID %> tr").length;  
8:      if (prevRowIndex == currentRowIndex) {  
9:        return;  
10:      }  
11:      else if (prevRowIndex != null) {  
12:        parent.rows[prevRowIndex].style.backgroundColor = "#FFFFFF";  
13:      }  
14:      //check if current index is a number...  
15:      if (IsNumeric(currentRowIndex)) {  
16:        //check if row index is less or equal to rowcount...  
17:        if (currentRowIndex <= rowscount) {  
18:          parent.rows[currentRowIndex].style.backgroundColor = "#FFFFD6";  
19:          prevRowIndex = currentRowIndex;  
20:          $('#<%= Label1.ClientID %>').text(currentRowIndex);  
21:        }  
22:      }  
23:      else {  
24:        $('#<%= Label1.ClientID %>').text("No row selected...");  
25:      }      
26:      $('#<%= hfParentContainer.ClientID %>').val(row);  
27:      $('#<%= hfCurrentRowIndex.ClientID %>').val(rowIndex);  
28:    }  
29:    function IsNumeric(num) {  
30:      return (num >= 0 || num < 0);  
31:    }  
32:    $(function () {  
33:      RetainSelectedRow();  
34:    });  
35:    function RetainSelectedRow() {  
36:      var parent = $('#<%= hfParentContainer.ClientID %>').val();  
37:      var currentIndex = $('#<%= hfCurrentRowIndex.ClientID %>').val();  
38:      if (parent != null) {  
39:        ChangeRowColor(parent, currentIndex);  
40:      }  
41:    }   
42:    </script>  
ASPX Markup.
1:  <asp:HiddenField ID="hfCurrentRowIndex" runat="server"></asp:HiddenField>  
2:    <asp:HiddenField ID="hfParentContainer" runat="server"></asp:HiddenField>  
3:    <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Trigger Postback" />  
4:    <asp:GridView ID="grdCustomer" runat="server" AutoGenerateColumns="false"   
5:      onrowdatabound="grdCustomer_RowDataBound" AllowPaging="True"   
6:      onpageindexchanging="grdCustomer_PageIndexChanging">  
7:      <Columns>  
8:        <asp:BoundField DataField="CompanyName" HeaderText="Company" />  
9:        <asp:BoundField DataField="ContactName" HeaderText="Name" />  
10:        <asp:BoundField DataField="ContactTitle" HeaderText="Title" />  
11:        <asp:BoundField DataField="Address" HeaderText="Address" />  
12:      </Columns>  
13:    </asp:GridView>  

Thursday, November 8, 2012

Get absolute server path of resources in ASP.NET MVC

In a scenario where you want to load images or other resources, Url.Content() does not return the exact resource path like this (D:\Cart\CartProject\Images\Item4.jpg). Hence, resulting into a null exception or empty resource.

Instead of using Url.Content() or ResolveUrl(), i get the server path of the resource using HttpContext of the application.
Code:
return new ImageResult(HttpContext.Server.MapPath("~/Images/Item" + id + ".jpg")); 
Note: Testing is done locally and not on a virtual directory...

Source: Find Absolute Path the the App Data Folder from Controller Cheers!

Display Bitmap Image in ASP.NET MVC View from Database with Image data type.

I encountered this weird problem rendering bitmap image from a database table that a friend of mine develops in his company. The task is to display the image on the mvc view. I thought it was a gif or jpeg or png format. But to my surprise as I rendered the binary data on webpage, the image was a bitmap type.. The code to show the bitmap image is as follows. That is to render the bitmap image into a jpeg format.
C# Code:
public ActionResult ShowCategories()  
{   
 var model = from n in oContext.ApplianceCategories  
    select n;  
 return View(model);        
}  

public void ShowImage(int id)  
{  
 var image = (from m in oContext.ApplianceCategories  
     where m.CategoryID == id  
     select m.Picture).FirstOrDefault();  
 TypeConverter tc = TypeDescriptor.GetConverter(typeof(Bitmap));  
 Bitmap bitmap1 = (Bitmap)tc.ConvertFrom(image);  
 bitmap1.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);  
} 
I got the trick from stack overflow... Cheers!

ASP.NET MVC generates error = "OutputStream is not available when a custom TextWriter is used"

In a simple application I'm creating, I have a custom ActionResult class that returns an image data. In my view, I simply used:
1:  <%= Html.Action("GetImage", "ImageCustom", new{id = item.CategoryID}) %>  
to call the custom action class ExecuteResult method. This method reads the image byte array and store's it in a stream object. However, the call generates an error stated in the title. Html.Action writes html which implements text writer class. The solution would be using Url.Action() embedded in the image src attribute:
1:  <img src='<%= Url.Action("GetImage","ImageCustom", new {id = item.CategoryID}) %>'   
2:  alt="No Photo" width="100" height="100" />  
Greg

Wednesday, October 24, 2012

Object doesn't support property or method call in consuming JSON object from ASP.NET MVC (IE9)

Recently,
I've followed a simple tutorial regarding consuming JSON object in ASP.NET MVC. The error stated from the title of this post appears in IE9. The original snippet is this:
1:  $(document).ready(  
2:      $.getJSON(  
3:        'http://localhost:6222/home/customerjson',  
4:         function (item) {  
5:           $('#result') //show product name in   
6:            .html('<p>' + item.CurrentCustomer.CustomerName + '</p>');  
7:         }  
8:      )  
9:    );  
The solution is to enclose $.getJSON() in a function() statement based from the modified code below. The popup script just went away.
1:  $(document).ready(function(){  
2:        $.getJSON(  
3:          'http://localhost:6222/home/customerjson',  
4:           function (item) {  
5:             $('#result') //show product name in   
6:              .html('<p>' + item.CurrentCustomer.CustomerName + '</p>');  
7:           }  
8:        )  
9:      });   
Cheers!

Friday, October 12, 2012

Eliminate duplicate rows in a Datatable

Assuming you have a datatable that has merged contents from different datatables and you want to eliminate the datatable with distinct rows, you can use the statement below.
Code:
dt.DefaultView.ToTable(true, new string[] { "id", "name" }); 
Cheers!

Wednesday, October 3, 2012

Column 'column_name' already belongs to another DataTable

In a scenario where I added columns using AddRange(), I encountered an error as specified by the title.
Here's the C# code:
Code:
table1.Columns.AddRange(new DataColumn[] { col1, col2, col3 });  
table2.Columns.AddRange(new DataColumn[] { col1, col2, col3 });
Where col1, col2, col3 are DataColumn objects.
What I did was to initialize columns in the addrange method. But there are other solutions in the forums.
Code:
table1.Columns.AddRange(new DataColumn[] { new DataColumn("ID"), new DataColumn("WEB ID"), new DataColumn("URL") });  
table2.Columns.AddRange(new DataColumn[] { new DataColumn("ID"), new DataColumn("WEB ID"), new DataColumn("URL") });

Thursday, September 27, 2012

WPF Datagrid (Prevent DataGrid last row from being sorted on column header clicked!)

Here's the WPF version of prevent total rows from being sorted.
Images:
1. Form Load, no column header is clicked (unsorted records)

2. Name header is clicked (sorting by column). The names are sorted alphabetically.

Below are the methods used:
Code:
      /// <summary>  
      /// column header clicked(sorting)  
      /// </summary>  
      private void dgProducts_Sorting(object sender, DataGridSortingEventArgs e)  
      {  
        DataRowView rv = (DataRowView)dgProducts.Items[dgProducts.Items.Count - 1];  
        if (rv[0].ToString().Contains("Total:"))  
        {  
          dvCopy = dgProducts.Items.SourceCollection as DataView;  
          rv.Delete();  
        }  
        sorted_aborted = e.Handled;  
      }  

      /// <summary>  
      /// layout is updated  
      /// </summary>  
      private void dgProducts_LayoutUpdated(object sender, EventArgs e)  
      {  
        if (!sorted_aborted)  
        {          
          //method to add totals computation  
          ShowProductSorted();  
          sorted_aborted = true;  
        }  
        else  
        {  
          DisableLastRow();  
        }  
      }    

      /// <summary>  
      /// show sorted products  
      /// </summary>  
      private void ShowProductSorted()  
      {  
        Total = 0;  
        DataTable dt = new DataTable();  
        dt = dvCopy.ToTable();  
        dvCopy = null;  
        dgProducts.ItemsSource = null;  
        foreach (DataRow row in dt.Rows)  
        {  
          Total = Total + Convert.ToDouble(row[1].ToString());  
        }  
        DataRow dr1 = dt.NewRow();  
        dr1[1] = Total;  
        dt.Rows.Add(dr1);  
        yourdatagrid.ItemsSource = dt.AsDataView();        
      }  

Sunday, September 23, 2012

Add checkbox in WPF Datagrid DatagridTemplateColumnHeader(for checkall)

Here's how to add checkbox in WPF Datagrid DatagridTemplateColumn to simulate checkall. I have included the TSQL script, XAML and C# codes. The source code is available for download here: WPF DataGrid Check/Uncheck All Functionality

Perform these steps below
1. Create an MSSQL database with the following Product Table schema below:
Table: Products
Fields:
-    ProductID (int, autoincrement)
-    ProductName (varchar)
-    UnitPrice (decimal)
-    QuantityPerUnit (varchar)
-    Discontinue (bit) 
SQL Script:
 USE [Your_Database_Name]  
 GO  
 /****** Object: Table [dbo].[Products]  Script Date: 05/27/2013 14:07:39 ******/  
 SET ANSI_NULLS ON  
 GO  
 SET QUOTED_IDENTIFIER ON  
 GO  
 SET ANSI_PADDING ON  
 GO  
 CREATE TABLE [dbo].[Products](  
      [ProductID] [int] NOT NULL,  
      [ProductName] [varchar](50) NULL,  
      [UnitPrice] [decimal](18, 2) NULL,  
      [QuantityPerUnit] [varchar](50) NULL,  
      [Discontinue] [bit] NULL,  
  CONSTRAINT [PK_Products] PRIMARY KEY CLUSTERED   
 (  
      [productID] ASC  
 )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]  
 ) ON [PRIMARY]  
 GO  
 SET ANSI_PADDING OFF  
 GO  
Note: You may add values after creating the table.

2. Change the App.config with your database settings.
 <?xml version="1.0"?>   
  <configuration>   
  <connectionStrings>   
   <add name="products"   
    connectionString="data source=testPC\SQLEXPRESS;Initial Catalog=your_test_database;User ID=your_user_id;Password=your_password;"   
    providerName="System.Data.SqlClient" />   
  </connectionStrings>   
  <startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/></startup></configuration>   

3. Update your xaml and classes as presented below.
Here is the DataGrid xaml:
 <DataGrid Name="dgProducts" AutoGenerateColumns="False" Grid.Row="1" Grid.RowSpan="3" Grid.ColumnSpan="2" CanUserAddRows="False">    
    <DataGrid.Columns>    
    <DataGridTextColumn Header="Name" Binding="{Binding Path=ProductName}" Width="215"/>    
    <DataGridTextColumn Header="Price" Binding="{Binding Path=UnitPrice}"/>    
    <DataGridTextColumn Header="Quantity Per Unit" Binding="{Binding Path=QuantityPerUnit}" Width="180"/>    
    <DataGridTemplateColumn>    
     <DataGridTemplateColumn.Header>    
     <CheckBox Content="Discontinue All" Click="CheckBox_Click" />    
     </DataGridTemplateColumn.Header>    
     <DataGridTemplateColumn.CellTemplate>    
     <DataTemplate>    
      <CheckBox Name="chkDiscontinue" IsChecked="{Binding Path=Discontinue,Mode=TwoWay}" Margin="45 2 0 0" Click="chkDiscontinue_Click" />    
     </DataTemplate>    
     </DataGridTemplateColumn.CellTemplate>    
    </DataGridTemplateColumn>    
    </DataGrid.Columns>    
   </DataGrid>    
Main Window class:
public partial class MainWindow : Window
{
 public MainWindow()
 {
  InitializeComponent();
 }

 private void Window_Loaded(object sender, RoutedEventArgs e)
 {
  dgProducts.ItemsSource = Connections.GetProduct().AsDataView();
 }

 /// <summary>
 /// check all checkbox
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 private void CheckBox_Click(object sender, RoutedEventArgs e)
 {
  var row = GetDataGridRows(dgProducts);

  if (((CheckBox)sender).IsChecked == true)
  {
   SetCheckbox(row, true);
  }
  else
  {
   SetCheckbox(row, false);
  }
 }

 //individual checking
 private void chkDiscontinue_Click(object sender, RoutedEventArgs e)
 {
  object a = e.Source;
  CheckBox chk = (CheckBox)sender;

  DataGridRow row = FindAncestor<DataGridRow>(chk);
  if (row != null)
  {
   DataRowView rv = (DataRowView)row.Item;
   
   //LINQ or Database Method to Update Product discontinue status
   Connections.UpdateProductDiscontinue((bool)chk.IsChecked, rv["ProductName"].ToString());
  }
 }
 
 private void SetCheckbox(IEnumerable<DataGridRow> row, bool value)
 {
  //loop through datagrid rows
  foreach (DataGridRow r in row)
  {
   DataRowView rv = (DataRowView)r.Item;
   foreach (DataGridColumn column in dgProducts.Columns)
   {
    if (column.GetType().Equals(typeof(DataGridTemplateColumn)))
    {
     rv.Row["Discontinue"] = value;

     //LINQ or Database Method to Update Product discontinue status
     Connections.UpdateProductDiscontinue(value, rv.Row["productname"].ToString());                                                
    }
   }
  }
 }

 public IEnumerable<DataGridRow> GetDataGridRows(DataGrid grid)
 {
  var itemsSource = grid.ItemsSource as IEnumerable;
  if (null == itemsSource) yield return null;
  foreach (var item in itemsSource)
  {
   var row = grid.ItemContainerGenerator.ContainerFromItem(item) as DataGridRow;
   if (null != row) yield return row;
  }
 }

 #region visual tree helpers

 /// <summary>
 /// Returns the first ancester of specified type
 /// </summary>
 public static T FindAncestor<T>(DependencyObject current) where T : DependencyObject
 {
  current = VisualTreeHelper.GetParent(current);
  while (current != null)
  {
   if (current is T)
   {
    return (T)current;
   }

   current = VisualTreeHelper.GetParent(current);
  };
  return null;
 }

 private childItem FindVisualChild<childItem>(DependencyObject obj) where childItem : DependencyObject
 {
  for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
  {
   DependencyObject child = VisualTreeHelper.GetChild(obj, i);
   if (child != null && child is childItem)
    return (childItem)child;
   else
   {
    childItem childOfChild = FindVisualChild<childItem>(child);
    if (childOfChild != null)
     return childOfChild;
   }
  }
  return null;
 }       

 #endregion
}
Database Manipulation class:
class Connections
{
 public static DataTable GetProduct()
 {
  DataSet ds = new DataSet();
  string query = "Select * from Products;";                    
   
  try
  {
   using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["products"].ConnectionString.ToString()))
   {
    SqlCommand cmd = new SqlCommand(query, conn);
    conn.Open();
    SqlDataAdapter da = new SqlDataAdapter(cmd);                    
    da.Fill(ds);
    conn.Close();
   }
  }
  catch (Exception ex)
  {
   throw ex;   
  }            
  return ds.Tables[0];
 }

 public static int UpdateProductDiscontinue(bool value, string product_name)
 {
  int result = 0;
  string query = String.Format("Update Products set discontinue = '{0}' where productname = '{1}' ;",value,product_name);

  try
  {
   using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["products"].ConnectionString.ToString()))
   {
    SqlCommand cmd = new SqlCommand(query, conn);
    conn.Open();
    result = cmd.ExecuteNonQuery();
    conn.Close();
   }
  }
  catch (Exception ex)
  {
   throw ex;
  }
  return result;
 }
}

Sample Output:
a. On form load (some of the checkbox are set to true, others are false)

b. Checkbox in column header is selected

c. Checkbox in column header is deselected

Thursday, September 20, 2012

Prevent DataGridView Last Row From Being Sorted On Column Click

Hello,
You might have a row in the DataGridView typically the last one that computes total and the grid control is unbound to a datasource. And then if a sorting event occurs, you dont' wanna include that row during sort event. So given that your application has a form and a DataGridView control, the code to perform databinding is handled in the Form Load Event.
DataGridViewRow dgRowTotalCount;
DataTable dataTable;

private void Form1_Load(object sender, EventArgs e)
{
 DataTable dt = new DataTable("tblEntTable");
 dt.Columns.Add("ID", typeof(string));
 dt.Columns.Add("Amount", typeof(decimal));
 dt.Rows.Add(new object[] { "1", 100.51 });
 dt.Rows.Add(new object[] { "2", 200.52 });
 dt.Rows.Add(new object[] { "6", 500.24 });
 dt.Rows.Add(new object[] { "8", 1000.11 });
 dt.Rows.Add(new object[] { "4", 400.31 });
 dt.Rows.Add(new object[] { "5", 600.88 });
 dt.Rows.Add(new object[] { "3", 700.11 });
 dt.Rows.Add(new object[] { "7", 700.12 });
 dt.Rows.Add(new object[] { "9", 300.12 });

 foreach (DataRow row in dt.Rows)
 {
  string id = row[0].ToString();
  decimal amount = Convert.ToDecimal(row[1].ToString());
  datagrid.Rows.Add(new object[]{ id, amount });
 }
}
To exclude the totals row from being sorted, the solution is pretty straightforward.  Clone and copy cell content values of the totals row to a DataGridRow object in the Cell Click Event of the grid. Then remove that row from the control.
private void datagrid_CellClick(object sender, DataGridViewCellEventArgs e)
{
 if (e.RowIndex == -1)
 {
  dgRowTotalCount = (DataGridViewRow)datagrid.Rows[((DataGridView)sender).Rows.Count - 1].Clone();
  for (Int32 index = 0; index < ((DataGridView)sender).Rows[((DataGridView)sender).Rows.Count - 1].Cells.Count; index++)
  {
   dgRowTotalCount.Cells[index].Value = ((DataGridView)sender).Rows[((DataGridView)sender).Rows.Count - 1].Cells[index].Value;
  }
  ((DataGridView)sender).Rows.RemoveAt(((DataGridView)sender).Rows.Count - 1);
 }
}
In the sorted event of the grid control, re-insert the row that was cloned and removed from the cell click event.
private void datagrid_Sorted(object sender, EventArgs e)
{
 datagrid.Rows.Insert(((DataGridView)sender).Rows.Count, dgRowTotalCount); 
}

Output (Records sorted by ID in ascending and descending order)
Cheers! :)

Monday, September 17, 2012

Regex Word Boundary (Not working if using a variable)

In this scenario, I have to match an exact state abbreviation (QLD) that is Queensland. I declared an array containing state constant values. Normally this would work without using a string variable in C#:
Code:
Regex.IsMatch(address, @"\bQLD\b")
However, this won't work:
Code:
if (Regex.IsMatch(address, @"\b" + str + "\b"))
The solution is to put an @ sign on both "\b" of the expression:
Code:
  string[] states = new string[]{"ACT","NSW","QLD"};  
  foreach (string str in states)  
  {  
    if (Regex.IsMatch(address, @"\b" + str + @"\b"))  
    {  
       state= str;  
       address = address.Replace(str, "").Trim();  
       break;  
    }  
  } 

Thursday, September 13, 2012

ASP.NET MVP Design Pattern (Simple)

Out of boredom, I decided to read some ASP.NET Articles and came stumbling to Dino Esposito's MVP Flavors. After reading it, I decided to translate this into an ASP.NET application. I revised specifically the Presenter class since this has most of the interaction. Below are some snippets and screen shots: Image: 1. Solution Explorer for the Sample ASP.NET MVP Site
2. On Drop Down Selection of Customer
3. Button Expand Is Clicked, Show other records on other textbox controls.
Presenter Class:
Code:
  public class Presenter  
    {  
      private IDefaultView view;  
      public Presenter(IDefaultView viewObject)  
      {  
        view = viewObject;  
      }  
      public void InitializeView()  
      {  
:        view.AddCustomer("Alfreds Futterkiste", "ALFKI");  
        view.AddCustomer("Ana Trujillo Emparedados y helados", "ANATR");  
        view.AddCustomer("Antonio Moreno Taquería", "ANTON");  
      }  
      public void ExpandCustomer()  
      {  
        // Get input data  
        string id = view.SelectedCustomer.ToString();  
        // Perform the action (through the model)  
        northwindEntities rep = new northwindEntities();  
        CustomersInfo c = (from cus in rep.Customers  
                 where cus.CustomerID == id  
                 select cus).FirstOrDefault();  
        // Update the view  
        view.CustomerID = c.CustomerID;  
        view.CompanyName = c.CompanyName;  
        view.ContactName = c.ContactName;  
        view.Country = c.Country;  
      }  
    } 
CustomerInfo Class:
Code:
// model class to hold results from  
//data context  
public partial class CustomersInfo  
{  
   public string CustomersID { get; set; }  
   public string CompanysName { get; set; }  
   public string ContactsName { get; set; }  
   public string Countrys { get; set; }     
}    
Cheers!

Wednesday, September 12, 2012

Convert time from a specific timezone to another using CONVERT_TZ()

In this scenario, we have to convert a timezone from Central USA to Hongkong time. I took note of DST here from (-06:00) to (-05:00). Here's a sample query.
SELECT CONVERT_TZ('2012-09-12 04:35:00', '-05:00', '+08:00') as convert_to_ph;
Cheers!

Monday, September 10, 2012

Adding an Item to WPF Datagrid (C#)

Here's the c# .net version.
Code:
DataGridTextColumn c1 = new DataGridTextColumn();  
c1.Header = "Test";  
c1.Binding = new Binding("test");  
 c1.Width = 473;  
dataGrid.Columns.Add(c1);  
dataGrid.Items.Add(new Names() {test="just testing"});
Class property:
Code:
public string test { get; set; }  
XAML code:
 <DataGrid AutoGenerateColumns="False" Height="289" HorizontalAlignment="Left" Margin="10,10,0,0" Name="dataGrid"   
          VerticalAlignment="Top" Width="481" Grid.ColumnSpan="2" ItemsSource="{Binding }">  
     </DataGrid>  
:)

Add an item to WPF Datagrid (VB.NET)

There was a question on visual basic forum on how to add an item to a wpf datagrid. Here's a simple example:
Code view:
Dim linkColumn As New DataGridTextColumn : Dim titleColumn As New DataGridTextColumn  
linkColumn.Header = "Links:" : titleColumn.Header = "Titles:"  
linkColumn.Width = dataGrid.Width / 2 : titleColumn.Width = dataGrid.Width / 2  
linkColumn.Binding = New System.Windows.Data.Binding("Link") : titleColumn.Binding =   
New System.Windows.Data.Binding("Title")  
dataGrid.Columns.Add(linkColumn) : dataGrid.Columns.Add(titleColumn)  
dataGrid.Items.Add(New DataItems() With {.Link = "http://testingme.com", .Title = "mytesting"})
XAML:
 <DataGrid AutoGenerateColumns="False" Height="289" HorizontalAlignment="Left" Margin="10,10,0,0" Name="dataGrid"   
          VerticalAlignment="Top" Width="481" Grid.ColumnSpan="2" ItemsSource="{Binding }">  
     </DataGrid>  
VB.NET Class
     Private _link As String  
         Public Property Link() As String  
           Get  
             Return _link  
           End Get  
          Set(ByVal l As String)  
             _link = l  
           End Set  
         End Property  
        Private _title As String  
        Public Property Title() As String  
          Get  
            Return _title  
          End Get  
          Set(ByVal t As String)  
            _title = t  
          End Set  
        End Property

That's it... :)

Sunday, September 9, 2012

CREATE DATABASE permission denied in database ‘master’.

I successfully installed MSSQL Server 2008 in my working pc. But when I tried creating a database
I encountered an error

CREATE DATABASE permission denied in database ‘master’. 


I recalled my username has no privilege as domain administrator. So, the solution was to 
1. login on my  working pc as domain administrator
2. change server authentication to mixed mode
3. change password of sa.
4. reconnect using sa account

That's it...

Tuesday, September 4, 2012

WPF TimePicker control

Based from these sources:
 a. (http://jobijoy.blogspot.com.au/2007/10/time-picker-user-control.html)
 b. Dipitimaya Patra's datepicker in Datagrid

I came up with a modified custom timepicker control embedded in WPF Datagrid with databinding features. I encountered bugs on migrating the present time picker custom control throughout development in .Visual Studio 2010 and I manage to fix them myself. The errors are specifically found on the keydown events and time updates (increment/decrement of values).

Here are the things that I did to make this work:

1. I added a dependency property to the user control
Code:
  public DateTime TimeValue  
      {  
        get { return (DateTime)GetValue(TimeProperty); }  
        set { SetValue(TimeProperty, value); }  
      }  
      public static readonly DependencyProperty TimeProperty =  
        DependencyProperty.Register("TimeValue", typeof(DateTime), typeof(TimeControlBinding),  
        new UIPropertyMetadata(DateTime.Now, new PropertyChangedCallback(OnTimeChangedTimeVal)));  
      private static void OnTimeChangedTimeVal(DependencyObject obj, DependencyPropertyChangedEventArgs e)  
      {  
        TimeControlBinding control = obj as CustomDatePickerTimeControlBinding;  
        control.Value = new TimeSpan(control.TimeValue.Hour, control.TimeValue.Minute, control.TimeValue.Second);  
      } 

2. Added a datagrid template column for the time field.
  <DataGridTemplateColumn Header="Hired Time" Width="100">   
       <DataGridTemplateColumn.CellTemplate>   
        <DataTemplate>   
         <TextBlock Text="{Binding HiredTime, StringFormat=hh:mm:ss}"/>   
        </DataTemplate>   
       </DataGridTemplateColumn.CellTemplate>   
       <DataGridTemplateColumn.CellEditingTemplate>   
        <DataTemplate>   
         <local:TimeControlBinding TimeValue="{Binding Path=HiredTime, Mode=TwoWay}" />   
        </DataTemplate>   
       </DataGridTemplateColumn.CellEditingTemplate>   
      </DataGridTemplateColumn>   
Here's how the control works:
a. on form load

b. on cell editing (used keydown or keyup to modify the values)
c. on cell leave (after modifying the time values), binding occurs.

Cheers!

Thanks to the original sources for the inputs of this control.. :)

Thursday, August 23, 2012

DataGridviewCell Fore color/Font Weight

Here's the code to apply font weight and font color to your datagridview cell.
Code:
DataGridViewCellStyle style = new DataGridViewCellStyle();  
style.ForeColor = Color.Red;  
style.Font = new Font(this.Font, FontStyle.Bold);  
dg.Rows[dg.Rows.Count - 1].Cells[i + 2].Style = style; 
Greg

Wednesday, August 15, 2012

Check if mouse coordinate is outside the form coordinates in mouseup event

Code:
  private void dgvScriptsTime_MouseUp(object sender, MouseEventArgs e)  
  {  
    if(!this.ClientRectangle.Contains(e.Location))  
    {  
       FShowGrid showGrid = new FShowGrid("Test", dgvScriptsTime);  
       showGrid.ShowDialog();  
    }  
  }

Tuesday, August 14, 2012

Show sql server instances with the network (ASP.NET)

The key is the SqlDataSourceEnumerator to display all instances. You can use gridview or ajax controls for display purposes.
Code:
      protected void Page_Load(object sender, EventArgs e)  
      {  
        // Retrieve the enumerator instance and then the data.  
        SqlDataSourceEnumerator instance = SqlDataSourceEnumerator.Instance;  
        System.DataDataTable table = instance.GetDataSources();  
        // Display the contents of the table.  
        DisplayData(table);  
      }  

      private void DisplayData(System.DataDataTable table)  
      {  
        foreach (System.DataDataRow row in table.Rows)  
        {  
          foreach (System.DataDataColumn col in table.Columns)  
          {  
            Response.Write(String.Format("{0} = {1}<br>",  
              col.ColumnName, row[col]));  
          }  
        }  
      } 

Wednesday, August 8, 2012

Save RGB color to SolidBrush object

To save a RGB color to a Solidbrush object, pass the RGB color in the solidbrush constructor.
Code:
olidBrush brush = new SolidBrush(Color.FromArgb(211, 222, 229)); 
Then apply it in your graphics method.
Code:
evs.Graphics.FillRectangle(brush, evs.CellBounds);
Cheers!

Monday, August 6, 2012

Graphic Lines in picture box gone after switching tab pages (C#)

In a program i'm working with, I have a timer event which draws lines or graphs on a picture box. This picture box is inside a tab and panel.

When I switched views to other tabs and return to the tab that has the picture box, the previous lines or graphs disappears. I suspect, the controls are redrawn when switching tabs.

I tried several solutions and options in picture box paint event and infact tried overriding it. Same results.

Luckily, I found a tip in an article to draw the real time graphics on the image itself. This helped solve the issue.

Greg

Thursday, July 19, 2012

Limit flickering on winforms

Here's the snippet to limit flicker in forms. Put it above the initialize component method in your constructor.
Code:
//limit flicker  
SetStyle(ControlStyles.OptimizedDoubleBuffer   
    | ControlStyles.UserPaint | ControlStyles.AllPaintingInWmPaint, true);  
 InitializeComponent();  
Cheers! Source: mijalko

Monday, July 16, 2012

Process memory usage percentage not computing properly

In a scenario when i want to compute the percentage of a process memory consumption against the total memory installed, I encountered a logic error where in the result is zero. The simple formula is this:
Code:
double x = p.PrivateMemorySize64 / installed_memory_pc * 100; 

However, the result in x is zero. The trick is to convert p.PrivateMemorySize64 and installed_memory_pc to megabytes by dividing each variable with 1048576. 1Mb = 1048576 bytes. The modified formula is:
Code:
mbInstalledMemory = (int)installedMemory / 1048576;  
mbUsage = (int)p.PrivateMemorySize64 / 1048576;
Then you can apply the percentage formula.
Cheers!

Wednesday, July 4, 2012

Enable/Disable ToolstripButton using Delegates (Thread)

Assuming you will access the toolstrip button from another thread, then here's the code to do it.
Code:
  delegate void EnableDisableButtonRunDeleg(bool value);  
      private void EnableDisableButtonRun(bool value)  
      {  
        if (tsMenu.InvokeRequired)  
        {  
         this.tsMenu.Invoke(new EnableDisableButtonRunDeleg   
          (EnableDisableButtonRun), value);  
        }  
        else  
        {  
          ToolStripItem ts = tsMenu.Items[0];  
          ((ToolStripButton)ts).Enabled = value;  
        }  
      }

Cheers!

Monday, July 2, 2012

Get Icon from process (C#)

Code:
Icon ico = Icon.ExtractAssociatedIcon(process.MainModule.FileName);
if you want to convert to image, just cast it to a bitmap object.
Source: Stack overflow

Prevent Listview column from being resized (Winform)

I added the snippet below in the columnwidthchanging event:
Code:
  switch (e.ColumnIndex)  
        {  
          case 0:  
            e.NewWidth = 400;  
            break;  
          case 1:  
            e.NewWidth = 200;  
            break;  
          case 2:  
            e.NewWidth = 100;  
            break;  
          case 3:  
            e.NewWidth = 100;  
            break;  
          default:  
            break;  
        }  
       e.Cancel = true;

Where 400, 200, and 100 are the original column sizes.