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.


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.
          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...  
          Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(CheckMainWindow));  

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:
      if(date != String.empty)  
       //comment this statement, transfer outside inner loop...  
       //processing of items code statements...      
    } while (!(url.Equals(String.Empty)));  
    if(PageNo > totalPage)   
      EndOfPage = true;   

Credits to my fellow developer for the discovery.


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

Thursday, November 15, 2012

Custom DatagridviewCheckboxColumn

Here's a simple class implementation of a DatagridviewCheckboxColumn.
public class DatagridviewCustomCheckboxColumn : DataGridViewCheckBoxColumn   
     public DatagridviewCustomCheckboxColumn()   
      this.CellTemplate = new DatagridviewCheckboxCustomCell();   
   class DatagridviewCheckboxCustomCell : DataGridViewCheckBoxCell   
    public int row_index { get; set; }   
    public int CheckboxHeight    
      //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    
      //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);   
       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.
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.
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" />