Wednesday, February 27, 2013

Unknown database 'your_database' error in MySQL in app.config

There's a weird scenario when retrieving table names from a specific database, upon querying, using connection.Open() in C#, an error such as "Unknown database 'database_name'" shows in the exception object.

I was simply checking the database name using MySQL Browser and found out that the database name starts with a space. So, after thinking about it, I decided to modify the app.config and changed the value of the connection string by enclosing the name with single quotes to include the space character of the database name.

Not working app.config setting:
 <add key="try" value="server=127.0.0.1;database=database_v1;Uid=james;pwd=pass123;"/>  
Working app.config setting with database name enclosed in single quotes:
 <add key="try" value="server=127.0.0.1;database=' database_v1';Uid=james;pwd=pass123;"/>  

Note: This fix is applied towards database names that starts/ends with space.
Cheers! That was a quick fix! :D

Greg

Tuesday, February 19, 2013

ASP.NET MVC AJAX Sys is undefined error (ASP.NET MVC 2.0 Remote Validation)

Referencing a remote validation can be a pain in the arse since several javascript errors will pop up such as stated in the title. So, in order to remove those unwanted script errors in ASP.NET MVC 2.0, use the solution below.
 <script src="<%= Url.Content("~/Scripts/MicrosoftAjax.debug.js") %>" type="text/javascript"></script>    
 <script src="<%= Url.Content("~/Scripts/MicrosoftMvcValidation.debug.js") %>" type="text/javascript"></script>  
 <script src="../../Scripts/RemoteValidationScript.js" type="text/javascript"></script>  

Note: RemoteValidationScript.js is an external Validation javascript file. The referencing of scripts should be in order to avoid null or property not found javascript exceptions(RemoteValidationScript should be referenced last). You may also use (../../Scripts/MicrosoftAjax.debug.js) for long method.

Reference: Sys is undefined error

Cheers!

Greg

Thursday, February 7, 2013

Pass GUID as parameter to Action using ASP.NET MVC ContribGrid

Hi, In a scenario where in you want to pass a GUID object to an Action Parameter, the parameter might contain a null value. Since Guid is not nullable, you can't simply just pass it to an action parameter because Action parameters require nullable and reference types. You might encounter an error like this:
An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter
Assuming you have an aspx view below:
 <div>    
  <% Html.Grid(Model).Columns   
    (c =>   
     {   
      c.For(m => m.Price);   
      c.For(m => m.ProductName);   
      c.For(m => m.ProductID);   
      c.For("View Person").Named("").Action(m =>      
      { %>   
       <td>   
        <%= Html.ActionLink("View Person", "ProductDetail", "Home", new { @id = m.ProductID.ToString() })%>         
         </td>   
      <% }); %>      
    <%}).Render(); %>   
  </div>   
and an action below:
Code:
public ActionResult ProductDetail(Guid id)   
{   
   //do something here...where p is your product object   
   return View(p);   
}   
Passing of guid as action parameter isn't possible. But here's a trick. You can substitute the ActionLink() with an HTML hyperlink tag and pass the Guid to the action.
       <a href="<%=Url.Action("ProductDetail","Home",new { @id = m.ProductID }) %>" >View Person</a>  
Cheers! :)
Greg

Tuesday, February 5, 2013

Embedding a Datagridview in Combobox Item

Hi,

There's a post in codeproject that will host a datagridview in a combobox. It is in vb.net and I converted it to C#. I made some changes on the custom controls to retrieve the datagridview selected row.

This was not provided in the author's post, so I made some changes myself. In total, the control was purely awesome. So, here's the C# equivalent. I won't be posting all the codes since the custom control is posted in codeproject. I'll be posting the main class instead.

Credits: Niemand25 of Lithuania
Code:
using System;  
 using System.Collections.Generic;  
 using System.ComponentModel;  
 using System.Drawing;  
 using System.Data;  
 using System.Linq;  
 using System.Text;  
 using System.Windows.Forms;  
 using System.Reflection;  
 namespace MyGridComboBoxCSharp  
 {  
   [ToolboxItem(true)]  
   [ToolboxBitmap(typeof(ComboBox))]  
   [DefaultBindingProperty("SelectedValue")]  
   [LookupBindingProperties("DataSource", "DisplayMember", "ValueMember", "SelectedValue")]  
   public partial class AccGridComboBox : ComboBox   
   {  
     private const UInt32 WM_LBUTTONDOWN = 513;    
     private const UInt32 WM_LBUTTONDBLCLK = 515;    
     private const UInt32 WM_KEYF4 = 308;    
     private ToolStripDataGridView myDataGridView = null;    
     private ToolStripDropDown myDropDown = null;    
     private object _SelectedValue = null;    
     private bool _InstantBinding = true;  
     [Browsable(false)]  
     [EditorBrowsable(EditorBrowsableState.Never)]  
     public new ComboBoxObjectCollection Items {  
       get {  
         return base.Items;  
       }  
     }  
     [Browsable(false)]  
     [EditorBrowsable(EditorBrowsableState.Never)]  
     public new object DataSource  
     {  
       get   
       {  
         return null;  
       }  
     }  
     public AccGridComboBox()   
     {  
       InitializeComponent();  
       myDropDown = new ToolStripDropDown();  
       myDropDown.AutoSize = false;  
       myDropDown.Closed += new ToolStripDropDownClosedEventHandler(this.ToolStripDropDown_Closed);  
     }  
     public bool HasAttachedGrid  
     {  
       get {  
         return !(myDataGridView == null);  
       }  
     }  
     public DataGridView AttachedGrid   
     {  
       get   
       {  
         if (!(myDataGridView == null))  
         {  
           return myDataGridView.DataGridViewControl;  
         }  
         return null;  
       }  
     }  
     protected virtual bool DisposeToolStripDataGridView   
     {  
       get   
       {  
         return true;  
       }  
     }  
     public bool InstantBinding   
     {  
       get   
       {  
         return _InstantBinding;  
       }  
       set   
       {  
         _InstantBinding = value;  
       }  
     }  
     public object SelectedValue  
     {  
       get  
       {  
         return _SelectedValue;  
       }  
       set  
       {  
         SetValue(value, true);  
         base.OnSelectedValueChanged(new EventArgs());  
       }  
     }  
     public void AddDataGridView(DataGridView nDataGridView, bool nCloseOnSingleClick)   
     {  
       if (!(myDataGridView == null))   
       {  
         throw new Exception("Error. DataGridView is already assigned to the AccGridComboBox.");  
       }  
       int count = nDataGridView.Rows.Count;  
       myDataGridView = new ToolStripDataGridView(nDataGridView, nCloseOnSingleClick);  
       myDropDown.Width = Math.Max(this.Width, myDataGridView.MinDropDownWidth);  
       myDropDown.Height = nDataGridView.Height;  
       myDropDown.Items.Clear();  
       myDropDown.Items.Add(this.myDataGridView);  
     }  
     internal void AddToolStripDataGridView(ToolStripDataGridView nToolStripDataGridView)  
     {  
       if (((nToolStripDataGridView == null) || (!(myDataGridView == null)   
             && (myDataGridView == nToolStripDataGridView))))   
       {  
         return;  
       }  
       myDataGridView = nToolStripDataGridView;  
       myDropDown.Width = Math.Max(this.Width, myDataGridView.MinDropDownWidth);  
       myDropDown.Height = myDataGridView.DropDownHeight;  
       myDropDown.Items.Clear();  
       myDropDown.Items.Add(this.myDataGridView);  
     }  
     private void ToolStripDropDown_Closed(object sender, ToolStripDropDownClosedEventArgs e) {  
       if ((e.CloseReason == ToolStripDropDownCloseReason.ItemClicked))   
       {  
         if (!base.Focused)  
         {  
           base.Focus();  
         }  
         if ((myDataGridView.DataGridViewControl.CurrentRow == null))  
         {  
           SetValue(null, false);  
         }  
         else   
         {  
           SetValue(myDataGridView.DataGridViewControl.Rows[myDataGridView.DataGridViewControl.CurrentCell.RowIndex].Cells[0].Value.ToString(), false);           
         }  
         base.OnSelectedValueChanged(new EventArgs());  
         if (_InstantBinding)  
         {  
           foreach (Binding b in base.DataBindings)   
           {  
             b.WriteValue();  
           }  
         }  
       }  
     }  
     private void SetValue(object value, bool IsValueMemberValue)   
     {  
       if ((value == null))   
       {  
         this.Text = "";  
         _SelectedValue = null;  
       }  
       else if (((this.ValueMember == null) || (string.IsNullOrEmpty(this.ValueMember.Trim()) || IsValueMemberValue)))   
       {  
         this.Text = value.ToString();  
         _SelectedValue = value;  
       }  
       else   
       {  
         object newValue = GetValueMemberValue(value);  
         if ((newValue == null))   
         {  
           this.Text = value.ToString();  
           _SelectedValue = value;  
         }  
         else {  
           this.Text = newValue.ToString();  
           _SelectedValue = newValue;  
         }  
       }  
     }  
     private Point CalculatePoz()  
     {  
       Point point = new Point(0, this.Height);  
       if (((this.PointToScreen(new Point(0, 0)).Y + (this.Height + this.myDataGridView.Height)) > Screen.PrimaryScreen.WorkingArea.Height))   
       {  
         point.Y = ((this.myDataGridView.Height - 7) * -1);  
       }  
       return point;  
     }  
     protected override void WndProc(ref Message m)  
     {  
       //base.WndProc(ref m);  
       if ((m.Msg == WM_KEYF4))  
       {  
         this.Focus();  
         this.myDropDown.Refresh();  
         if (!this.myDropDown.Visible)  
         {  
           ShowDropDown();  
         }  
         else  
         {  
           myDropDown.Close();  
         }  
         return;  
       }  
       // #End Region  
       // #Region "WM_LBUTTONDBLCLK"  
       if (((m.Msg == WM_LBUTTONDBLCLK) || (m.Msg == WM_LBUTTONDOWN)))  
       {  
         if (!this.myDropDown.Visible)  
         {  
           ShowDropDown();  
         }  
         else  
         {  
           myDropDown.Close();  
         }  
         return;  
       }  
       // #End Region  
       base.WndProc(ref m);  
     }  
     protected override void OnResize(SystemEventArgs e)   
     {  
       int minWidth = 0;  
       if (!(this.myDataGridView == null))   
       {  
         minWidth = this.myDataGridView.MinDropDownWidth;  
       }  
       myDropDown.Width = Math.Max(this.Width, minWidth);  
       if (!(myDataGridView == null))  
       {  
         myDataGridView.Width = Math.Max(this.Width, minWidth);  
         myDataGridView.DataGridViewControl.Width = Math.Max(this.Width, minWidth);  
         myDataGridView.DataGridViewControl.AutoResizeColumns();  
       }  
       base.OnResize(e);  
     }  
     protected override void OnKeyDown(System.Windows.FormsKeyEventArgs e)   
     {  
       if ((e.KeyCode == Keys.Down))   
       {  
         ShowDropDown();  
         e.Handled = true;  
       }  
       base.OnKeyDown(e);  
     }  
     private void ShowDropDown()   
     {  
       if (!(this.myDataGridView == null))   
       {  
         if (!myDropDown.Items.Contains(this.myDataGridView))   
         {  
           myDropDown.Items.Clear();  
           myDropDown.Items.Add(this.myDataGridView);  
         }  
         myDropDown.Width = Math.Max(this.Width, this.myDataGridView.MinDropDownWidth);  
         myDataGridView.Size = myDropDown.Size;  
         myDataGridView.DataGridViewControl.Size = myDropDown.Size;  
         myDataGridView.DataGridViewControl.AutoResizeColumns();  
         if ((_SelectedValue == null) || System.DBNull.Value.Equals(_SelectedValue))  
         {  
           myDataGridView.DataGridViewControl.CurrentCell = null;  
         }  
         else if ((!(this.ValueMember == null) && !string.IsNullOrEmpty(this.ValueMember.Trim())))  
         {  
           if (((myDataGridView.DataGridViewControl.Rows.Count < 1) || ((myDataGridView.DataGridViewControl.Rows[0].DataBoundItem == null)   
                 || (myDataGridView.DataGridViewControl.Rows[0].DataBoundItem.GetType().GetProperty(this.ValueMember.Trim(), (BindingFlags.Public | BindingFlags.Instance)) == null))))   
           {  
             myDataGridView.DataGridViewControl.CurrentCell = null;  
           }  
           else {  
             object CurrentValue;  
             foreach (DataGridViewRow r in myDataGridView.DataGridViewControl.Rows)  
             {  
               if (!(r.DataBoundItem == null))   
               {  
                 CurrentValue = GetValueMemberValue(r.DataBoundItem);  
                 if ((_SelectedValue == CurrentValue))   
                 {  
                   myDataGridView.DataGridViewControl.CurrentCell = myDataGridView.DataGridViewControl[0, r.Index];   
                   break;  
                 }  
               }  
             }  
           }  
         }  
         else   
         {  
           bool SelectionFound = false;  
           foreach (DataGridViewRow r in myDataGridView.DataGridViewControl.Rows) {  
             try {  
               if ((_SelectedValue == r.DataBoundItem))   
               {  
                 myDataGridView.DataGridViewControl.CurrentCell = myDataGridView.DataGridViewControl[0, r.Index];  
                 SelectionFound = true;  
                 break;  
               }  
             }  
             catch (Exception ex)   
             {  
               try   
               {  
                 if ((_SelectedValue == r.DataBoundItem))   
                 {  
                   myDataGridView.DataGridViewControl.CurrentCell = myDataGridView.DataGridViewControl[0, r.Index];  
                   SelectionFound = true;  
                   break;  
                 }  
               }  
               catch (Exception e)  
               {  
               }  
             }  
           }  
           if (!SelectionFound) {  
             myDataGridView.DataGridViewControl.CurrentCell = null;  
           }  
         }  
         myDropDown.Show(this, CalculatePoz());  
       }  
     }  
     object GetValueMemberValue(object DataboundItem) {  
       object newValue = null;  
       try   
       {  
         newValue = DataboundItem.GetType().GetProperty(this.ValueMember.Trim(), (BindingFlags.Public | BindingFlags.Instance)).GetValue(DataboundItem, null);  
       }  
       catch (Exception ex) {  
       }  
       return newValue;  
     }  
   }  
 }  
Here's the image with datagridview in combobox where no selection has been made.
And here's the image where a selection has been done in the datagrid, and the selected cell value appears in the combobox Text property.

Cheers!

ASP.NET MVC String.Format() not showing correct format in Views using jQuery Calendar

Greetings,

Formatting display output of dates in asp.net mvc should work using String.Format() with custom date formatting criteria. However, applying String.Format() in asp.net ascx view does not display the desired format that I want. Example markup:
 <%: Html.TextBoxFor(model => model.HireDate, String.Format("{0:g}", Model.HireDate))%>  
Given Date Input: 2/6/2013 12:00:00 AM
Desired Output should be with time portion removed: 2/6/2013

Solution:
The trick to display the desired format was to decorate a display format attribute in my model class HireDate property:
Code:
     private DateTime hDay;  
     [DisplayName("Hire Date")]  
     [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yyyy}")]  
     public DateTime HireDate  
     {  
       get  
       {  
         if (hDay == DateTime.MinValue)  
         {  
           return DateTime.Today;  
         }  
         else  
           return hDay;  
       }  
       set  
       {  
         if (value == DateTime.MinValue)  
         {  
           hDay = DateTime.Now;  
         }  
       }  
     }
And in your .ascx view, use EditFor() instead of TextBoxFor()
 <%: Html.EditorFor(model => model.HireDate, Model.HireDate)%>  
Incorrect Format with jQuery datepicker

Correct Format with jQuery datepicker


Greg

Sunday, February 3, 2013

Clean Invalid XML Characters in C#

Here's a cool way to clean Large XML files with invalid xml characters.
Note: Stream from is the original xml file, while Stream to is the new xml file with invalid characters removed.
Code:
private void Copy(Stream from, Stream to)   
{   
       TextReader reader = new StreamReader(from);   
       TextWriter writer = new StreamWriter(to);   
       writer.WriteLine(CleanInvalidXmlChars(reader.ReadToEnd()));   
       writer.Flush();   
}   
     
public static string CleanInvalidXmlChars(string text)   
{   
       string re = @"[^\x09\x0A\x0D\x20-\xD7FF\xE000-\xFFFD\x10000-x10FFFF]";   
       return Regex.Replace(text, re, "");   
}  
Source: http://social.msdn.microsoft.com/Forums/
Post: Invalid character returned from webservice