Thursday, February 23, 2012

Webbrowser control not displaying webpage (no internet connection message)

In one of our codes, we used web browser to scrape data.
Recently, the webbrowser control can't display the webpage.
The error states that THERE IS NO INTERNET CONNECTION.

The solution was to Clear History of Internet Explorer Browser..(cookies/passwords/forms/temporary internet files)

Cheers!

JSON Response in webrequest class

Code:
req.ContentType = "application/json; charset=utf-8";

Source: Stackoverflow

Wednesday, February 22, 2012

Attach MSSQL DB to SQL Developer Edition on runtime

If you have a program migrated to a pc where there is no sql express edition installed but a developer or enterprise edition is found and the database is part of the solution file.

If you run the program, a connection timeout error will occur. All you need to do is change the datasource name from .\sqlexpress to your Servername. Then change the credentials such as username and password.

Assuming you declare your connection string in app.config or web.config, here is an example:
1:  <add name="Southridge.Properties.Settings.SouthridgeConnectionString"  
2:        connectionString="Data Source=PC_SERVERNAME;  
3:        AttachDbFilename=|DataDirectory|\Southridge.mdf;user=sa;  
4:  password=yourpassword;  
5:        Connect Timeout=30;"  
6:        providerName="System.Data.SqlClient" />  

Tuesday, February 21, 2012

Convert/Cast mysql database column collation in sql code!

Software Used: Mysql 5.0 connector/Visual Studio 2010
We encounter a tricky problem when showing mysql database column value with collation of typelatin1_swedish_ci. The value retrieved from the column and shown on a c# string variable is not the same with what is in the database. The ascii characters has been stripped off in the string variable.
Here is a string variable with special character apostrophe stored in a column with latin1swedish collation.

Ex. Take on bank robbers, beat the bad guys or shoot it out with the police in the quest for freedom – all in the name of fun! Doesn’t sound like your average day out, but today we’re making this happen!

In order to preserve the ascii characters from a latin1 column to be shown on C# code, you need to put a Convert() function in your sql statement.
Example:
string sql = "select convert(description using utf8)
as description from
your_table where id='554be79124998120b8c3505d47c88c2d'";
Code:
private void TestDeals()  
{  
    DataTable dt = new DataTable();  
    string conn_s = ConfigurationManager.AppSettings["LocalDB"];  
    string sql = "select convert(description using utf8) as description   
        from your_table where id='554be79124998120b8c3505d47c88c2d'";  
    MySqlConnection conn = null;        
    ASCIIEncoding ascii = new ASCIIEncoding();  
    try  
    {  
        conn = new MySqlConnection(conn_s);  
        conn.Open();  
        MySqlCommand cmd = new MySqlCommand(sql, conn);  
        MySqlDataAdapter da = new MySqlDataAdapter(cmd);  
        da.Fill(dt);  
        //IDataReader read = cmd.ExecuteReader();  
        //dt.Load(read, LoadOption.PreserveChanges);          
        string desc = dt.Rows[0]["description"].ToString();  
        MessageBox.Show(desc);         
    }  
    catch (Exception ex)  
    {  
        throw;  
    }  
    finally  
    {  
       conn.Close();  
    }  
} 

Show processes in ur pc using asp.net

Code behind:
Code:
protected void ShowProcessToGrid()  
{      
   Dictionary<string,string> process = new Dictionary<string,string>();  
   foreach(Process p in Process.GetProcesses())  
   {  
      process.Add(p.Id.ToString(),p.ProcessName);  
   }  
   this.gvPRocess.DataSource = process;  
   this.gvPRocess.DataBind();  
}  

protected void gvPRocess_PageIndexChanging(
object sender, GridViewPageEventArgs e)  
{  
    gvPRocess.PageIndex = e.NewPageIndex;  
    ShowProcessToGrid();  
} 
Here is the aspx markup:
 <asp:GridView ID="gvPRocess" runat="server" AllowPaging="True"   
       BackColor="White" BorderColor="Black" BorderStyle="Solid" BorderWidth="1px"   
       CellPadding="4" style="margin:auto" AutoGenerateColumns="False"   
       onpageindexchanging="gvPRocess_PageIndexChanging">  
       <Columns>  
         <asp:BoundField DataField="Key" HeaderText="ID">  
         <ItemStyle Width="50px" />  
         </asp:BoundField>  
         <asp:BoundField DataField="Value" HeaderText="Name">  
         <ItemStyle Width="200px" />  
         </asp:BoundField>  
       </Columns>  
       <HeaderStyle BackColor="#003399" Font-Bold="True" ForeColor="#CCCCFF" />  
       <PagerStyle BackColor="#99CCCC" ForeColor="#003399" HorizontalAlign="Left" />  
       <RowStyle BackColor="White" ForeColor="#003399" />  
       <SelectedRowStyle BackColor="#009999" Font-Bold="True" ForeColor="#CCFF99" />  
       <SortedAscendingCellStyle BackColor="#EDF6F6" />  
       <SortedAscendingHeaderStyle BackColor="#0D4AC4" />  
       <SortedDescendingCellStyle BackColor="#D6DFDF" />  
       <SortedDescendingHeaderStyle BackColor="#002876" />  
     </asp:GridView>  

Monday, February 20, 2012

Return First Array Item that has duplicates!

Code:
  //in your main function  
   #region testdata  
  //string[] split_cities = new string[] { "perth", "sydney", "perth" };  
  //string[] split_cities = new string[] { "perth", "sydney", "gold" };  
  //string[] split_cities = new string[] { "nsw", "sydney", "sydney" };  
  //string[] split_cities = new string[] { "nsw", "nsw", "sydney" };  
  //string[] split_cities = new string[] { "nsw", "coast", "sydney", "nsw" };  
  //string[] split_cities = new string[] { "auck", "coast", "nsw", "nsw" };  
  string[] split_cities = new string[] { "auck", "nsw", "nsw", "coasts" };  
  //string[] split_cities = new string[] { "auck", "coast", "nsw", "auck" };  
  //string[] split_cities = new string[] { "auck", "coast", "nsw", "auc" };  
  #endregion  
        #region string method  
        string occur = OccurMoreThanOnceString(split_cities);  
        if (!occur.Equals(string.Empty))  
        {  
          Console.Write(occur);  
        }  
        else  
        {  
          Console.Write("No duplicates");  
        }  
        #endregion  
  //method declaration  
  //------------------------------------------------------------  
   private static string OccurMoreThanOnceString(string[] split_cities)  
      {  
        string occur_more = "";  
        int check_index = 0;  
        string temp = split_cities[0].ToLower().Trim();  
        for (int j = 0; j < split_cities.Length; j++)  
        {  
          if (check_index == j) //array to be checked is same location   
          {  
            continue;  
          }  
          else  
          {  
            string x = split_cities[j].ToLower().Trim();  
            if (temp.Equals(split_cities[j].ToLower().Trim()))  
            {  
              occur_more = temp;  
              break;  
            }  
          }  
          //if it has reached end of loop  
          if (j == split_cities.Length - 1)  
          {  
            ++check_index;  
            temp = split_cities[check_index];  
            j = -1; //reset loop  
          }  
        }  
        return occur_more;  
      } 

Wednesday, February 15, 2012

Draggable Window in WPF

In my WPF application, the opacity of the window has been set to transparent and the ResizeMode has been set to No Resize. This application has a user control as child element.

When the window is renedered on screen, i can't drag the object/window in my screen. So to do this, you have to check the mouse down event in your windows. Then call the DragMove method.

Here is the snippet:
Code:
void Window_MouseDown(object sender, MouseButtonEventArgs e)  
{  
   if (e.LeftButton == MouseButtonState.Pressed)  
      this.DragMove();  
} 

Monday, February 13, 2012

Add control to Grid in WPF

Code:
Label lbl = new Label();  
lbl.Content = "1";  
grdClock.Children.Add(lbl);
Where: grdClock is the Grid control