Wednesday, March 28, 2012

Sorting Dictionary<TKey,TValue> by value or by key using LINQ

var sortedDict = (from entry in SortedWebsiteNames orderby entry.Value   
ascending select entry).ToDictionary(pair => pair.Key, pair => pair.Value);  
var sortedDict = (from entry in SortedWebsiteNames orderby entry.Value   
ascending select entry).ToDictionary(pair => pair.Key, pair => pair.Value);
Source: StackOverflow

Monday, March 26, 2012

AutoComplete Winforms search not working if item is one character digit (Bug?)

Textbox properites: autocompletemode = append, autcompletesource = customsource. Assuming the autocompletestringcollection of the textbox are as follows:


If you type the number 8 in the textbox, the textbox autocomplete does not suggest. As defined, it will search the prefix of the source. So, i guess one character does not have a prefix at all. The workaround for this is to
add a space character after the digit 8. So, "8" becomes "8 ". Below is the code:
private void PopulateWebsiteName()  
          if (dtWebsiteNames != null) { dtWebsiteNames.Clear(); }  
          dtWebsiteNames = JobsReporting.Scripts.GetWebsiteNamesLocal();  
          if (dtWebsiteNames.Rows.Count > 0)  
            foreach (DataRow row in dtWebsiteNames.Rows)  
              if (row[1].ToString().Trim().Length == 1)   
                row[1] = row[1] + ' '.ToString();  
          txtWebsiteName.AutoCompleteCustomSource = websiteNameCollection;  
        catch (Exception e)  
         MessageBox.Show("Error Loading Website Names",   
         "", MessageBoxButtons.OK, MessageBoxIcon.Error);   
GetWebsiteNamesLocal() is the method to retrieve websites from the database.

Sunday, March 25, 2012

ASP.NET Website Administration (Exception when adding users)

Upon registering new users, I encountered this error upon saving.
An error was encountered. Please return to the previous page and try again.
The following message may help in diagnosing the problem:

Exception has been thrown by the target of an invocation. at System.RuntimeMethodHandle._InvokeMethodFast(Object target, Object[] arguments, SignatureStruct& sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner) at System.RuntimeMethodHandle.InvokeMethodFast(Object target, Object[] arguments, Signature sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner) at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks) at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) at System.Web.Administration.WebAdminMembershipProvider.CallWebAdminMembershipProviderHelperMethodOutParams(String methodName, Object[] parameters, Type[] paramTypes)

I already have a custom ASPNETDB in my database..and using this db in my
test program will cause the exception above.

The solution is to add the default ASPNETDB in my APP_DATA folder
and change my web config settings to this:
 <add name="ApplicationServices" connectionString="data source=SERVERNAME;  
 Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;"   
Since my db is an sql dev edition... :)

Thursday, March 15, 2012

Simple Pager Template in ASP.NET

1:  <PagerTemplate>  
2:   Page: <%=gvPRocess.PageIndex + 1%> of <%=gvPRocess.PageCount %>  
3:   <asp:button ID="btnFirst" runat="server" CommandName="Page"   
4:  CommandArgument="First" Text="<<"/>  
5:   <asp:button ID="btnPrev" runat = "server" CommandName="Page"   
6:  CommandArgument="Prev" Text="<"/>  
7:   <asp:button ID="btnNext" runat = "server" CommandName="Page"   
8:  CommandArgument="Next" Text=">"/>  
9:   <asp:button ID="btnLast" runat = "server" CommandName="Page"   
10:  CommandArgument="Last" Text=">>"/>  
11:   </PagerTemplate>  

Limit RAM usage of Mozilla Firefox

I noticed that Firefox takes a lot of RAM space on my workstation. After googling around, I found a solution on how to limit it's memory consumption.

1. Open Mozilla firefox
2. type about:config in the url/address bar
3. just click i'll be careful i promise
4. filter "browser.cache."
5. change browser.cache.disk.capacity from original value
in my pc it's 1059997.
I changed it to 30000 since my RAM space is 2GB.
6. Choose OK
7. Close and restart Mozilla firefox

(i noticed the memory usage of firefox lowered to a significant level)

Cheers! :=)

Wednesday, March 14, 2012

ASP.NET MVC (Add,Edit,Delete,View/View All) Example in C#

Original Source: Developer Resources

Just this evening, i modified an ASP.NET MVC example from Visual Basic.Net to C#. I also completed the steps and added some basic functionalities of my own. The database used is MS SQL Server 2008 and the data source is an ADO.NET Entity object.

Below are the screenshots:

Here is the snippet for the validation side in C#. This is not sophisticated:
  protected void ValidateEmployee(Employee EmployeeToValidate)  
        if (EmployeeToValidate.EmployeeName == null)  
  , "Employee name is required field.");  
       if (EmployeeToValidate.Department == null)  
  , "Employee Department is required field.");  
        if (EmployeeToValidate.EmployeeSalary == null)  
  , "Employee Salary is required field.");  
        if (EmployeeToValidate.Age == null)  
  , "Employee Age is required field.");  
        if (EmployeeToValidate.Role == null)  
  , "Employee Role is required field.");  
        if (EmployeeToValidate.Skillset == null)  
  , "Employee Skillset is required field.");  

Monday, March 12, 2012

The remote server returned an error: (500) Internal Server Error (Webclient)

The solution is to set the user agent and add it as header to the webclient object.
"Mozilla/5.0 (Windows NT 6.1; rv:2.0) Gecko/20100101 Firefox/4.0");

SET variable (user defined) in mysql returns NULL (MySQL Browser)

Source: MySQL bug Forum
1. Open MySQL Browser
2. Click Tools menu
3. Click Options
4. Choose Browser
5. Check Show Advanced Toolbars
6. Click Apply
7. Click close
8. Transactions Toolbar appears on MySQL Browser
9. Click the Transaction button on the transaction toolbar everytime
you execute the query
Sample query:
Set @names = 'james';
select @names;

Friday, March 9, 2012

Get Response URL from WebRequest

//domain url:  
//response url:  
WebRequest request =   
HttpWebResponse resp = HttpWebResponse)request.GetResponse();  
string ur = resp.ResponseUri.ToString();  

Wednesday, March 7, 2012

Add Reference to WPF Merged Resource Dictionary in Window.xaml

Good evening guys!
Here's how to add reference to WPF Merged Dictionary in Window.xaml.
      <!--resource dictionary is placed in folder-->  
      <ResourceDictionary Source="/ResourceDictionaries/RoundedButton.xaml" />   
      <!--dictionary is inside WPF project-->  
      <!--<ResourceDictionary Source="RoundedButton.xaml" /> -->   

Monday, March 5, 2012

Download File using Webrequest w/ Credentials

  HttpWebRequest request;  
            HttpWebResponse response = null;  
              string username = "xxxuser";  
              string password = "yyypass";  
              NetworkCredential myCredentials =   
  new NetworkCredential(username, password);  
              request = (HttpWebRequest)WebRequest.Create(ListURL);  
              request.Timeout = 900000000;  
              request.Credentials = myCredentials;  
              request.AllowWriteStreamBuffering = false;  
              response = (HttpWebResponse)request.GetResponse();  
              Stream s = response.GetResponseStream();  
              //Write to disk  
              FileStream fs = new FileStream("\\\xmldata.xml"  
  , FileMode.Create);  
              byte[] read = new byte[256];  
              int count = s.Read(read, 0, read.Length);  
              while (count > 0)  
                fs.Write(read, 0, count);  
                count = s.Read(read, 0, read.Length);  
              //Close everything  
            catch (WebException e)  
              if (response != null){ response.Close(); }  

Enable saving of changes that require table to be re-created...

Source: SQL Server Central
The solutions is:
1. Go to Tools on MS SQL IDE
2. Click Options
3. Then Designers
4. Then Table and Database Designers
5. Uncheck Prevent saving changes that require table re-creation.