Wednesday, March 28, 2012

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

Code:
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:

James
Philipp
Mariah
Clara
8
Ryan
GregEsguerra

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:
Code:
private void PopulateWebsiteName()  
      {  
        try  
        {  
          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();  
              }  
              websiteNameCollection.Add(Convert.ToString(row[1]));  
              website_id.Add(row[0].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;"   
 providerName="System.Data.SqlClient"/>  
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:
Code:
  protected void ValidateEmployee(Employee EmployeeToValidate)  
      {  
        if (EmployeeToValidate.EmployeeName == null)  
        {  
          ModelState.AddModelError("EmployeeName"  
  , "Employee name is required field.");  
        }  
       if (EmployeeToValidate.Department == null)  
        {  
           ModelState.AddModelError("Department"  
  , "Employee Department is required field.");  
        }  
        if (EmployeeToValidate.EmployeeSalary == null)  
        {  
          ModelState.AddModelError("EmployeeSalary"  
  , "Employee Salary is required field.");  
        }  
        if (EmployeeToValidate.Age == null)  
        {  
           ModelState.AddModelError("Age"  
  , "Employee Age is required field.");  
        }  
        if (EmployeeToValidate.Role == null)  
        {  
           ModelState.AddModelError("Role"  
  , "Employee Role is required field.");  
        }  
        if (EmployeeToValidate.Skillset == null)  
        {  
           ModelState.AddModelError("Skillset"  
  , "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.
Code:
newWebClient.Headers.Add("user-agent",   
"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
Steps
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

Code:
//domain url: http://www.htcatalogs.com.au  
//response url: http://www.htcatalogs.com.au/2012/dailylistings/  
WebRequest request =   
WebRequest.Create("http://www.rmwilliams.com.au");  
HttpWebResponse resp = HttpWebResponse)request.GetResponse();  
string ur = resp.ResponseUri.ToString();  
Console.Write(ur); 

Wednesday, March 7, 2012

Add Reference to WPF Merged Resource Dictionary in Window.xaml

1:  <Window.Resources>  
2:   <ResourceDictionary>  
3:     <ResourceDictionary.MergedDictionaries>  
4:      <!--resource dictionary is placed in folder-->  
5:      <ResourceDictionary Source="/ResourceDictionaries/RoundedButton.xaml" />   
6:      <!--dictionary is inside WPF project-->  
7:      <!--<ResourceDictionary Source="RoundedButton.xaml" /> -->   
8:     </ResourceDictionary.MergedDictionaries>  
9:   </ResourceDictionary>      
10:  </Window.Resources>  

Monday, March 5, 2012

Download File using Webrequest w/ Credentials

Code:
  HttpWebRequest request;  
            HttpWebResponse response = null;  
            try  
            {  
              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("\\192.168.3.3\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  
              fs.Close();  
              s.Close();  
              response.Close();  
            }  
            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.