Monday, December 5, 2011

using Microsoft.VisualBasic DateDiff() in your c# program

long age = Microsoft.VisualBasic.DateAndTime.DateDiff("yyyy",Convert.ToDateTime("1985-04-04"),DateTime.Now); 

Monday, November 21, 2011

How to Decode and encoded URL in .NET

The code below illustrates how to decode an encoded url using HttpUtility.UrlDecode(string url)
  using System.Web;   
  //make sure to add reference to System.Web  
  string temp_url = ""  
        + "mbe%2fut%2fsuivroffrs%2fapercoffr.asp"  
        + "%3fnooffr%3d3053675%26page%3drech%26prov%  
  string url = HttpUtility.UrlDecode(temp_url); 

Wednesday, November 9, 2011

Read or parse XML using XmlElement class and XmlNodelist

Sample xml file:
<?xml version="1.0" encoding="UTF-8"?>
      <title>Payroll Analyst</title>
         <summary>Seeking Payroll Analyst specialists.    
  Great benefits and competitive salary. Must meet all requirements    
  to be considered for assignment.</summary>
   <job />
ListingSource = webclient.DownloadString("your_xmlurl");  
StringReader readString = new System.IOStringReader(ListingSource);  
XmlDocument awesome = new XmlDocument();  
XmlNodeList nodeList = awesome.SelectNodes("//jobs/job");  
foreach (XmlElement element in nodeList)  
    title = element["title"].InnerText.Trim();  
    state_name_text = element["location"]["state"].InnerText.Trim();   
    description = element["description"]["summary"].InnerText.Trim();  

Wednesday, October 26, 2011

Image rendered in browser appears to be corrupt or encrypted

Here is the url that contains the images list:Image List
A sample image url that appears to be encrypted or corrupt: Image File
Solution: Change it's file extension to jpeg.
Image File

(502)Bad Gateway returned from web request

The solutions is to set the default proxy for the web request and assign user agent to it as shown below:
ListURL = String.Format("your_xml_feed_or_API_url_sample");  
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(ListURL);  
request.Timeout = 900000000;  
request.Proxy = HttpWebRequest.DefaultWebProxy;  
request.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)";  
HttpWebResponse response = (HttpWebResponse)request.GetResponse();  
Stream dataStream = response.GetResponseStream();  
dataStream = response.GetResponseStream();  
StreamReader reader = new StreamReader(dataStream);  
ListingSource = reader.ReadToEnd();  
ListingSource = System.Web.HttpUtility.HtmlDecode(ListingSource);

Tuesday, October 25, 2011

invalid expanded name (LINQ to XML)

Assuming I am reading this xml file using XLINQ.
I encountered an error that says invalid expanded name. As i go through
this xml file, i found a node images that contains element tags. The parent
node is also an element tag. Since i don't use the images tag, I simply remove it using string manipulations. Below is the xml file and the solution:
1:  <element>  
2:        <id>2768687195</id>  
3:        <title>Customer Service Representative</title>  
4:        <body>Do you dream of being your own boss and choosing the work you   
5:  do, when you work and who you work for?   
6:        </body>  
7:        <url>http://jobs.myjob.careercenter-servicecrew.html</url>  
8:        <category>  
9:          <id>job/customer_service</id>  
10:          <name>Customer Service &amp; Call Center Jobs</name>  
11:        </category>  
12:        <source>  
13:          <id>www</id>  
14:          <name>Oodle</name>  
15:        </source>  
16:        <location>  
17:          <citycode>can:on:ajax</citycode>  
18:          <name>Ajax</name>  
19:          <state>ON</state>  
20:          <country>CAN</country>  
21:          <latitude>43.8610</latitude>  
22:          <longitude>-79.0292</longitude>  
23:        </location>  
24:        <images>  
25:          <element>  
26:            <src></src>  
27:            <width>100</width>  
28:            <height>75</height>  
29:            <alt>Customer Service Representativ</alt>  
30:            <num>0</num>  
31:            <size>s</size>  
32:          </element>  
33:          <element>  
34:            <src></src>  
35:            <width>144</width>  
36:            <height>108</height>  
37:            <alt>Customer Service Representativ</alt>  
38:            <num>0</num>  
39:            <size>m</size>  
40:          </element>  
41:          <element>  
42:            <src></src>  
43:            <width>208</width>  
44:            <height>156</height>  
45:            <alt>Customer Service Representativ</alt>  
46:            <num>0</num>  
47:            <size>l</size>  
48:          </element>  
49:          <element>  
50:            <src></src>  
51:            <width>100</width>  
52:            <height>100</height>  
53:            <alt>Customer Service Representativ</alt>  
54:            <num>0</num>  
55:            <size>x</size>  
56:          </element>  
57:          <element>  
58:            <src></src>  
59:            <width>100</width>  
60:            <height>100</height>  
61:            <alt>Customer Service Representativ</alt>  
62:            <num>0</num>  
63:            <size>j</size>  
64:          </element>  
65:        </images>  
66:        <ctime>1318626135</ctime>  
67:        <paid>Yes</paid>  
68:        <revenue_score>6</revenue_score>  
69:        <user>  
70:          <id>51527855</id>  
71:          <url></url>  
72:          <name>Arise Virtual Solutions</name>  
73:          <photo></photo>  
74:        </user>  
75:        <attributes>  
76:          <company>Arise Virtual Solutions</company>  
77:          <fee>No</fee>  
78:          <full_time>Full Time</full_time>  
79:          <has_photo>Thumbnail</has_photo>  
80:          <job_title>Customer Service Representative</job_title>  
81:          <user_id>51527855</user_id>  
82:        </attributes>  
83:      </element>  
for (int ctr = 0; ctr < ListingSource.Length; ctr++)  
  if (ListingSource.Contains("<images>"))  
     int length = (ListingSource.IndexOf("
     </images>") + 9) - ListingSource.IndexOf("
     ListingSource = ListingSourceRemove  
     ListingSource.IndexOf("<images>"), length);  

Thursday, October 13, 2011

Read or parse XML using LINQ (XLinq)

XML Content:
    <title>Labor Warehouse Associates - Boston, Massachusetts</title>   
    <description>Hudson Group is the #1 airport retailer operating in over 400    
    retail locations in most major airports, throughout the US and Canada.    
    While we are comprised of many     
    <jobcountry>United States</jobcountry>   
  string url = "your xml or rss link";  
  string xmlsource = client.DownloadString(url);  
  StringReader readString = new System.IOStringReader(xmlsource);  
  XDocument xmlDoc = XDocument.Load(readString);  
  //solution 1  
  var tutorials = from jobfield in xmlDoc.Descendants("item")  
  select new  
    jobtitle = (string) jobfield.Element("title"),  
    joburl = (string) jobfield.Element("link"),  
    desc = (string)jobfield.Element("description"),  
    city = (string)jobfield.Element("joblocation").Element("jobcity"),  
    state = (string)jobfield.Element("joblocation").Element("jobstate"),  
  //solution 2  
  var tutorials = from jobfield in xmlDoc.Descendants("item")  
  select new  
    jobtitle = jobfield.Element("title").Value,  
    joburl = jobfield.Element("link").Value,  
    desc = jobfield.Element("description").Value,  
    city = jobfield.Element("joblocation").Element("jobcity").Value,  
    state = jobfield.Element("joblocation").Element("jobstate").Value,  

Thursday, September 29, 2011

Manipulate object property using Lambda/LINQ

ShowEmployeeDelegate d = () => { tMessage.Text = "Nelson"; };  
Where ShowEmployeeDelegate is a delegate.

Tuesday, September 27, 2011

Remove Open/Close Square Brackets in a sentence:

Data: [Posted Friday September 23 2011]
Output: Posted Friday September 23 2011
string date = Regex.Replace(date, "[\\[\\]]", string.Empty);  
date = Regex.Replace(date, @"[\[\]]", string.Empty);  

Replace character based on specific index

Here's an example snippet that will replace a character
based from a specific index.
Source: DreamInCode
To use it in your program do it like this:
  // Replaces a character in a string with the character specified.  
  void replaceCharWithChar(ref string text, int index, char charToUse)  
    char[] tmpBuffer = text.ToCharArray();  
    buffer[index] = charToUse;  
    text = new string(tmpBuffer);  

  //money has comma, example: $2,000, 4 BR, 180 m²   
  //LandPriceBedroom = "$120, 2 BR, 90 m²";  
  if (LandPriceBedroom.Split(',').Length > 3)   
    int firstIndexComma = LandPriceBedroom.IndexOf(",");  
    replaceCharWithChar(ref LandPriceBedroom, firstIndexComma, ' ');  

Monday, September 12, 2011

Regex remove string with a punctuation beside it in a sentence!

Assuming in a sentence, you want to remove the word apply now in any case. This word has a punctuation beside it.
Apply now!
Apply now.
apply Now!
apply Now.

In a sentence:
We are in need of VB.NET Developers. Apply Now!
We are in need of VB.NET Developers. Apply now!
We are in need of VB.NET Developers. APPLY NOW!
We are in need of VB.NET Developers. apply now!
To remove, just use the code below:
description = Regex.Replace(description, "apply now[!.]",   string.Empty,RegexOptions.IgnoreCase).Trim();

Note: I'm not a Regex expert.

Remove dotted lines or whitespaces in Visual Studio 2010

1. ctrl r+w
2. ctrl e+s

Uncompress gzip response using WebClient

In a scenario where you want to download xml data using webclient, the response from firefox or any browser will display the xml file correctly. However, using a web request/webclient.downloadstring to download the xml file, the response is somewhat corrupted or in hashed form.
The response headers are the following:
1. Content-Type - application/xml
2. Content-Encoding - gzip
As you can see, the content encoding is of type gzip. The solution is to override the web request method to something like this:
class DecompressGzipResponse : WebClient  
      protected override WebRequest GetWebRequest(Uri address)  
        HttpWebRequest request = (HttpWebRequest)base.GetWebRequest(address);  
        request.AutomaticDecompression = DecompressionMethods.GZip   
                 | DecompressionMethods.Deflate;  
        return request;  
//to use this in the program (main function)
DecompressGzipResponse client = new DecompressGzipResponse ();  
ListingSource = client.DownloadString("");

Reference: GZIP and HTTP Response

Thursday, September 8, 2011

Exponent to Decimal Notation

string land_area = "1.21445e-007".ToUpper();  
decimal dec = decimal.Parse(land_area, System.Globalization.NumberStyles.Float); 

Tuesday, September 6, 2011

Count number of string occurrences in C#

int count_li = tempListSource.Split(new string[]{"<li>"},         StringSplitOptions.RemoveEmptyEntries).Length - 1;

Thursday, September 1, 2011

Reset Seed in MySQL Table


Monday, August 22, 2011

.NET Version Checker in you PC

Here's a repost of a .NET Version Checker I found in the internet.
        const string regLocation = "SOFTWARE\\Microsoft\\NET Framework Setup\\NDP";  
        static void Main(string[] args){  
        Console.WriteLine(".NET Framework versions installed");  
        RegistryKey masterKey = Registry.LocalMachine.OpenSubKey(regLocation);  
        RegistryKey tempKey;  
        if (masterKey == null)  
          Console.WriteLine("Null Key!");  
          string[] SubKeyNames = masterKey.GetSubKeyNames();  
          for (int i = 0; i < SubKeyNames.Length; i++)  
            tempKey = Registry.LocalMachine.OpenSubKey  
               (regLocation + "\\" + SubKeyNames[i]);  
            Console.WriteLine("\tVersion = {0}",   

Reference: Check .NET Framework Version Installed

Thursday, August 11, 2011

The Error: 417 "Expectation Failed." during webrequest

System.Net.ServicePointManager.Expect100Continue = false; 

Tuesday, August 2, 2011

Date Insert In MySQL using .NET

To insert date object using in MySQL db,use the code below:
1:  string query = String.Format("Insert into tbllistings(DateRegistered)"  
2:   + "values(DATE_FORMAT({0}, '%Y-%m-%d %h:%m:%s'))",objJobs.DateRegistered); 
The key to the solution is using the MySQL Date format function.

Prevent winforms from being resized at design time

1:  this.MaximumSize = new System.DrawingSize(500, 400);  
2:  this.MinimumSize = new System.DrawingSize(500, 400);

Wednesday, July 13, 2011

MySQL Date Range Query (Using Logical Operators)

Here's another version using logical operators in MySQL.
1:  select date_format(date_purchased,'%m/%d/%Y')as dates,   
2:   url from dbcommerce.tblproducts   
3:    where date_format(date_purchased,'%m/%d/%Y') >= '04/30/2011'  
4:     and date_format(date_purchased,'%m/%d/%Y') <= '05/30/2011'  
5:      order by date_purchased asc;  

MySQL Date Range Query

Here is an example to query MySQL Date Range given the date field is of
type TimeStamp. The date_format() will remove the time part in comparing.
1:  select date_format(date_purchased,'%m/%d/%Y')as dates, url   
2:   from dbCommerce.tblproducts   
3:    where date_format(date_purchased,'%m/%d/%Y')  
4:       between '04/30/2011' and '05/30/2011'  
5:           order by date_purchased asc;  

Tuesday, July 12, 2011

Unable to convert MySQL date/time value to System.DateTime

Solution: Add Allow Zero to your Web.Config or App.Config
1:  <add key="connectionString" value="Database=your_db  
2:  ;Data Source=localhost;User Id=root;  
3:  Password=password;Allow Zero Datetime=True;"/>  
Source: Unable To Convert MySQL DateTime value


Monday, July 11, 2011

Newline for C# equivalent with Environment.Newline

txtOutput.Text = "Select All Nodes" + "\r\n";  
txtOutput.Text = "Select All Nodes" + Environment.Newline; 

Sunday, July 10, 2011

Setup SQL Developer to Connect to a MySQL database!!!

1. Download sql developer from oracle site
2. Copy sql developer to drive C:\
3. Copy msvcr71.dll to %WinDir%\System32 [reference:]
msvcr71.dll is located in: [sqldeveloper\jdk\jre\bin\msvcr71.dll]
4. Download mysql-connector-java-5.0.8-bin.jar zip file from this site: Download MySQL connector Java
5. Extract mysql-connector-java-5.0.8-bin.jar in sql developer lib folder: C:\Users\gnesguerra\Downloads\sqldeveloper-\sqldeveloper\lib
6. Setup sql developer to connect to mysql database using the tutorial from this site: Starting from Setting it Up Paragraph: Configuring SQL Developer for MySQL
   6.1 Click Choose Database button below Port label.
   6.2 Beside the Choose Database button, select the database you want to connect to
from the dropdown control.
   6.3 Zero Date Handling should be set to null
   6.4 Click Connect
7. (Increase Operation Timeout)
   7.1 Tools
   7.2 preferences
   7.3 versioning
      7.3.1 general
      7.3.2 set operation timeout to 1 hour or greater
8. Finished.
You should be able to connect to root username or your mysql db instance
NOTE: I found a small bug running MySQL queries in SQL Developer
When you finished executing a query and you want to execute another query,
the editor returns error message (Query execution was interrupted)
The solution is to delete the persisted settings then switch to Query Builder everytime you create a new query. Then wait for a couple of seconds..Sucks!!!

Wednesday, July 6, 2011

Using Proxy With WebClient

Here is a snippet to use WebProxy. This is useful for scraping or other webrequest activities.
   1:    Dim webclient As New System.Net.WebClient  
   2:    Try  
   3:     'true for bypassOnLocal  
   4:     webclient .Proxy =   
   5:          New System.Net.WebProxy("",true)  
   6:     wc.OpenRead("")  
   7:     lblStatus.Text = "ok"   
   8:    Catch  
   9:     lblStatus.Text = "error proxy"  
  10:    End Try  

Format query result by count() with comma using Format()

I played around with MySQL count() statement. I found it annoying that the count()
will simply return whole numbers. Example: the total record of a table is 32,272.
In MySQL SQL, this will simply return 32272. Below are two sql scripts. The first
one returns whole number,while the second query returns comma separated number.

1:  select count(*) as num_records_notformatted from mytable where name like '%j%';  
2:  Solution:  
3:  select format(count(id),0) as num_records_formatted from mytable   
4:  where name like '%j%';  

Tuesday, July 5, 2011

Scrollbars in WPF Textbox

You can set the scrollbars in a WPF TextBox control using it's properties:
or using the ScrollView class:

Control.InvokeRequired not Found (WPF)

I was doing a little WPF threading recently which involved changing my codes from Winforms to WPF. Surprisingly, I was not able to find the code below in the intellisense:
After googling, I found this link: Why is Dispatcher.CheckAccess() hidden from intellisense?
I wonder why Microsoft hid some features on intellisense. Or it could be a bug.

Wednesday, June 29, 2011

(Webclient) The remote server returned an error: (403) Forbidden.

Using downloadstring of webclient returns an error as stated by the post title. The solution was to add user agent header to the webclient headers. The value of user agent can be found in the mozilla firebug.
  string URL = string.Format(your_url);  
  newWebClient.Headers.Add("user-agent", "Mozilla/5.0 (Windows NT 6.1; rv:2.0)  
                          Gecko/20100101 Firefox/4.0");  
  string pageSource = newWebClient.DownloadString(URL);  
  pageSource = System.Web.HttpUtility.HtmlDecode(pageSource);  

Thursday, June 23, 2011

Show External IP address using C#

I experimented a snippet to get my ISP provided IP address using whatismyip. Using tutorials or code snippets from links, the web request just returned a 404 error. After reading the whatismyip API again,they have changed their automation URL. Below is the code snippet.

  //previous URL present on most tutorials which is not working  
  //string whatIsMyIp = "";   
  //updated URL from whatismyip API  
  string whatIsMyIp = "";  
  WebClient wc = new WebClient();  
  UTF8Encoding utf8 = new UTF8Encoding();  
  string requestHtml = "";  
  requestHtml = utf8.GetString(wc.DownloadData(whatIsMyIp));

Wednesday, June 15, 2011

Convert Epoch Time to DateTime in C#

Me and my fellow developer encountered a scenario to convert epoch time to datetime. The solution can be found in stack overflow.
private void Form1_Load(object sender, EventArgs e)  
     //long tms = 1308139229;  
     long tms = 1308143650;  
     DateTime dt = FromUnixTime(tms);  
public DateTime FromUnixTime(long unixTime)  
   var epoch = new DateTime(1970, 1, 1, 0, 0, 0, 
   return epoch.AddSeconds(unixTime);  

Thursday, June 9, 2011

Sorting List Generic collection (string)

This example uses List generic collection and will sort names in descending order. Names with New will be displayed on top of the list. This is applicable if you will be displaying products names with NEW in it's product name as recently displayed.
  List<string> Names = new List<string>();  
      private void FListSort_Load(object sender, EventArgs e)  
        Names.Add("Thomas New");  
        Names.Add("Fultron New");  
        Names.Add("Joker New");  
        Names.Add("Arthur New");  
        Names.Add("Baby Lee Jones");  
        Names.Add("Caspers New");  
      internal class MyComp  
          public int sort(string x, string y)  
            return x.IndexOf("New").CompareTo(y.IndexOf("New"));  
      private void btnSort_Click(object sender, EventArgs e)  
        MyComp comp = new MyComp();  
        txtSorted.Text = "Sort by Ascending!";  
        //Names.Sort(delegate(string x, string y)   
        //{ return x.IndexOf("New").CompareTo(y.IndexOf("New")); });  
        txtSorted.Text += Environment.NewLine;  
        txtSorted.Text += Environment.NewLine;  
        txtSorted.Text = "Sort by Descending!" ;  
        txtSorted.Text += Environment.NewLine;  
        txtSorted.Text += Environment.NewLine;  
        foreach (string x in Names)  
          txtSorted.Text = txtSorted.Text + x + Environment.NewLine;  

Reference: Developer Fusion Article

Wednesday, June 8, 2011

Posting Data To WebBrowser Control

Basically, it is possible to post data to web browser control. The code below, was referenced from MSDN, but i slightly modified some of it's functionalities.
string url = "";  
string postData = String.Format("city=DC&Page={0:00}",pageNum);  
byte[] Post = Encoding.UTF8.GetBytes(postData );  
string AdditionalHeaders = "Content-Type: application/x-www-form-urlencoded";  
//wbSample is the web browser control  
//the WebNavigate method is just a simple method i created  
//which simply assigns url to the browser, the post data and additional headers  
WebNavigate(wbSample , ListURL, "", Post, AdditionalHeaders);

Sunday, May 22, 2011

JQuery Calculator

The image above is a jquery/javascript calculator developed in ASP.NET 4.0 web template. Here's the functions. I'wont be posting all codes since it will took up space in my post. I'll just post the sqrt() and a number scripts.

The ASPX markup uses plain css for centering and aligning the buttons and html controls. No server controls are involved. For the jquery processing, im using the id selector.
1:  /* show zero to textbox on page load */  
2:  $("#txtCalc").ready(function () {  
3:    $("#txtCalc").val("0");  
4:  });  
5:  //square root  
6:        $("#btnSqrt").click(function () {  
7:          var text = $("#txtCalc").val();  
8:          //if invalid input,do not execute codes below  
9:          if ("Invalid") != -1) {  
10:            return;  
11:          }  
12:          if (text.length == 1) {  
13:            if (text == "0") {  
14:              return;  
15:            }  
16:            else //text is 3  
17:            {  
18:              var x = parseFloat($("#txtCalc").val());  
19:              var str = Math.sqrt(x);  
20:              $("#txtCalc").val(str);  
21:              result = str;  
22:              arrayComputation = "";  
23:              $("#labelArray").val("");  
24:            }  
25:          }  
26:          else { //length is two  
27:            if (text.indexOf("-") != -1) {  
28:              $("#txtCalc").val("Invalid Input");  
29:              return;  
30:            }  
31:            else {  
32:              var x = parseFloat($("#txtCalc").val());  
33:              var str = Math.sqrt(x);  
34:              $("#txtCalc").val(str);  
35:              result = str;  
36:              arrayComputation = "";  
37:              $("#labelArray").val("");  
38:            }  
39:          }  
40:          operatorPressed = "0";  
41:        });  
42:         /* NUMBER BUTTONS */  
43:        $("#btnZero").click(function () {  
44:          //conditions aron mu reset ang input  
45:          //if an operator is typed  
46:          if (operatorPressed == 1) {  
47:            $("#txtCalc").val("");  
48:            operatorPressed = 0;  
49:          }  
50:          var text = $("#txtCalc").val();  
51:          //if invalid input,do not execute codes below  
52:          if ("Invalid") != -1) {  
53:            return;  
54:          }  
55:          if (text.length == 1) {  
56:            if (text != "0") {  
57:              var str = $("#txtCalc").val();  
58:              var newStr = str.concat($("#btnZero").attr("value"));  
59:              $("#txtCalc").val(newStr);  
60:            }  
61:          }  
62:          else { //length is two  
63:            var str = $("#txtCalc").val();  
64:            var newStr = str.concat($("#btnZero").attr("value"));  
65:            $("#txtCalc").val(newStr);  
66:          }  
67:        }); //end click button zero  
Make sure to register your jquery script in your content/master page.
 <asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">  
 <script type="text/javascript" src="Scripts/jquery-1.4.1.js" language="javascript">  

Saturday, May 14, 2011

Random Class not Generating proper X and Y Coordinates

I am creating a snippet to change x and y coordinates upon runtime. However,not as i expected,the generated random numbers does not meet my requirements.
Here is the C# snippet:
  switch (odd_eve)  
   case 0:    
      Random rand = new Random();             
      count = rand.Next(0, 300);  
  case 1:  
      Random rand1 = new Random();   
      count = rand1.Next(310, 600);  
Based from the code above,the random generates a slanting x and y coordinates. The solution i come up came from the idea of a fellow developer to declare one Random object in one class.
Random rand = new Random(); //declared as global variable  
 //function snippet  
 switch (odd_eve)  
  case 0:           
     count = rand.Next(0, 300);  
 case 1:  
     count = rand.Next(310, 600);  
Works like a charm!!!

Tuesday, May 3, 2011

Debug JavaScript Code in Visual Studio 2008/2010

Here are the simple steps to debug js code in your aspx markup.

1. Open Visual Studio 2008/2010
2. Click Tools then options
3. Expand debugging node then click checkboxes Manages,Native,Script.
4. In your web.config file,make sure to set compilation debug to true.
1:  <compilation debug="true">       
2:       <assemblies>  
3:        <add assembly="System.Core, Version=, Culture=neutral,   
4:           PublicKeyToken=B77A5C561934E089"/>  
5:        <add assembly="System.Web.Extensions, Version=,   
6:            Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>  
7:        <add assembly="System.Data.DataSetExtensions, Version=,   
8:           Culture=neutral, PublicKeyToken=B77A5C561934E089"/>  
9:        <add assembly="System.Xml.Linq, Version=, Culture=neutral,   
10:           PublicKeyToken=B77A5C561934E089"/>  
11:       </assemblies>  
12:      </compilation>  
5. Choose IE as default browser by right clicking on the .aspx webpage then choose IE as default browser.
6. Place a breakpoint in your js script, then run your code.
 <script type="text/javascript" language="javascript">  
     function myHello()   
       var x = 5;  
       var y = 6; //place breakpoint here or anywhere in your code  
       alert((x + y));    

Saturday, April 30, 2011

Microsoft SQL Server, Error 14234


I installed an SQL Server 2005 database on my clients server machine,and when i created a database maintenance plan,i got the error as stated:

The specified '@subsystem' is invalid (valid values are returned by sp_enum_sqlagent_subsystems). (Microsoft SQL Server, Error 14234)

The solution is to install SQL Server 2005 Integration Services.

Tuesday, April 26, 2011

"Installation Incomplete - The installer was interrupted before could be installed. (Visual Studio Web Setup Project)

Recently,the software i maintained crashed down and can't be opened by the browsers (IE,Firefox and chrome). I tried different kinds of solutions but they don't work. So,i tried the steps below to re-install the web setup package with the error provided as the title of the post.
Culprit: virus attack[dangerous or high risk worm/trojan]
1. Repair windows xp sp2 (using installer cd) XP Repair Install
Note: I performed only steps 1-6
2. After repairing, I uninstalled the IIS
3. Delete the current Inetpub folder in Drive C:\ [make sure to backup any files in the Inetpub folder]
4. Then restart PC after performing steps 2-3
5. Re-install IIS using windows xp sp2 cd
6. Register 2.0 from command prompt
c:\windows\\framework\v2.0.50727>aspnet_regiis -i
7. Restart PC/Server
8. Continue Installing VS Web Setup Project

Note: This may also apply to Windows 2003 server or new Windows OS.

StringCollections in .NET

After some tiresome work, i decided to visit MSDN. Along the way,i manage to take a grip from System.Collections.Specialized StringCollection class.
I was used to List, ArrayList, and etc. After reading MSDN's documentation,I managed to create a simple example.
  class Program  
      static void Main(string[] args)  
        //defined class  
        StringCollections collections = new StringCollections();  
        //.NET collection class  
        StringCollection netcollection = new StringCollection();  
        string[] names = new string[5];  
        //insert five elements  
        for(int i = 0; i <5; i++)  
          names[i] = "nelson" + (i+1);  
        //store to stringcollection object  
        netcollection = collections.Employees(names);  
        //navigate collection class  
        StringEnumerator enumerator = netcollection.GetEnumerator();  
        while (enumerator.MoveNext())  
    internal sealed class StringCollections  
      public StringCollection Employees(string[] names)  
        StringCollection collections = new StringCollection();  
        catch (Exception ex)  
          throw new Exception(ex.InnerException.Message);  
        return collections;  
The code above,will display the list using Enumerator. You could use foreach or other methods. But I decided the Enumerator object..

Sunday, April 24, 2011

ASP.NET MVC View Model

I recently read an article from Stephen Walther on View Models and gave it a spin. In this example,i created two typed class namely People and address..You may create properties or public fields in there. After that,create a controller with the view model which has List properties. Then in your view,you simply inherit the PersonViewModel.

Below is the Person Controller with the PersonViewModel.
  public class PersonController : Controller  
      public ActionResult Index()  
        // Create list of People  
        var people = new List<People>();  
        people.Add(new People(30, "Nelson G."));  
        people.Add(new People(28, "James Ingram"));  
        // Create list of Address  
        var address = new List<Address>();  
        address.Add(new Address(9000, "Cebu"));  
        address.Add(new Address(6521, "Baybay"));  
        // Return view  
        return View(new PersonViewModel(people, address));  
      public ActionResult Details()  
        // Create list of People  
        var people = new List<People>();  
        people.Add(new People(30, "Nelson G."));  
        people.Add(new People(28, "James Ingram"));  
        // Create list of Address  
        var address = new List<Address>();  
        address.Add(new Address(9000, "Cebu"));  
        address.Add(new Address(6521, "Baybay"));  
        // Return view  
        return View(new PersonViewModel(people, address));  
  // View Model Classes  
    public class PersonViewModel  
      public PersonViewModel(List<People> people, List<Address> address)  
        this.People = people;  
        this.Address = address;  
      public List<People> People { get; private set; }  
      public List<Address> Address { get; private set; }  
Here is the view that will utilize the PersonViewModel.
 <%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master"   
 Inherits="System.Web.Mvc.ViewPage<ViewModelsDemo.Controllers.PersonViewModel>" %>  
 <asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">  
 <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">  
       <%int i = 0; %>  
       <%foreach (var item in Model.People) %>  
       <%{ %>  
         <li> <%=item.Name %> &nbsp; <%= Model.Address[i].completeAdd %> </li>     
          <%i++; %>       
       <%} %>  

Thursday, April 14, 2011

Accessing HttpUtility class in C# Winforms

To use HttpUtility class in C# winforms, do the following:
1. Add reference to System.Web dll
2. Use any methods available in HttpUtility class.

Thursday, April 7, 2011

Using Sessions in .NET Web Services

Lately, i was confronted with a problem on managing state with web services, after reading a book on xml in .NET 2.0, i found a tip on creating and consuming web services with state capabilities.

I followed this link: Using Session State in a Webservice
MSDN: Web Service Session

This idea, is a life saver to some of my web projects.. :D

Visual C# 2010 Express (System.Web Namespace not found)

When you created a winforms project and you would like to use HttpUtilities or other classes found on System.Web, you might notice that when you tried adding reference to System.Web, it is not found on the .NET Tab.

By default, the project is targeted on .NET Compact framework 4.0, so just change it to .NET Framework 4.0. By then,you will be able to add the System.Web namespace in your projects.


Friday, March 25, 2011

Repair a SQL Server 2008 Suspect database after upgrading

Lately, I've installed SQL Server 2008 Developer Edition in my pc and migrated all sql server 2005 databases.

Upon attaching/restoring all databases, some were marked as suspect. Below is the sql script to repair those databases.
1:  EXEC sp_resetstatus 'Test';  
3:    DBCC checkdb('Test')  

But as a precautionary measure,I have back-up plans for each database,as to have another copy when things go wrong.

Test is the database name.

Source: how-to-repair-sql-server-2008-suspect

Saturday, March 19, 2011

Deploying ASP.NET websites using ASP.NET Membership Framework

In my case, i have been experimenting an e-commerce application which uses membership framework. If I run the website using visual studio 2008, it successfully logs in using the users i have created using the built-in website administration tool.
However, if you deploy this on a production server such as IIS, you cant' log-in. The solution is straightforward in this link:
Always set the "applicationName" property when configuring ASP.NET 2.0 Membership and other Providers(Configuring ASP.NET 2.0 Membership)

Friday, March 18, 2011

Clear Sessions after logout button is clicked

Solution I found is on this link: ASP.NET Forum Link

Wednesday, March 16, 2011

Install IIS on Windows 7 Home Premium

Here's the link: Technet Link

Thursday, March 10, 2011

Unable to Open EDMX (Entity Framework in Design View) After Closing

Scenario: You may have recently added an entity framework that maps to an sql server table. After that, you suddenly close it. But when you tried to double click the Entity model, it does not open in the design view.
Solution: Cannot Open .edmx file in the designer

Wednesday, March 2, 2011

Insert Parameter Array in .NET (C# Version)

The first version i created was a version. Here is the C# version:
  myConn objCon = Program.connectionstring;  
        string str = objCon(); //pass delegate to string  
        SqlConnection connection = new SqlConnection(str);  
          List<Patient>patients = new List<Patient>();  
          for(int i = 0; i < 5; i++)  
            Patient patient = new Patient();  
   = "greg" + i;  
            patient.code = i*2;  
          //insert into array  
          StringBuilder query = new StringBuilder();  
          SqlCommand cmd = new SqlCommand();  
          for (int j = 0; j < patients.Count; j++)  
            query.Append(string.Format("Insert into patients  
              values (@names{0},@code{1});",j,j));  
            //declare the parameters  
              ("@names{0}",j), patients[j].name);  
              ("@code{0}",j), patients[j].code);  
          cmd.Connection = connection;  
          cmd.CommandText = query.ToString();  
        catch (Exception exception)  
          throw new Exception(exception.Message);  
        Console.Write("Array successfully saved");  

Tuesday, March 1, 2011

Change Default Browser ASP.NET MVC

To change a default browser for an mvc website to render is not straightforward. However, the steps are just easy:
1. Add a webform or a static html to the application, just leave the default name.
2. Right click on the newly added webform.
3. Click Browse With.
4. Choose the browser like Firefox, IE, or Chrome.
5. Mark it as default.

Thats it!!!

Monday, February 21, 2011

Get gridviewrow selected index in Row Command Event

In your row command event, add a code like this:
int selected_index = Convert.ToInt32(e.CommandArgument);  

Tuesday, February 15, 2011

Cast SQL Money field type to C# Type

Given you have a field called customer_salary which is of type money in sql server, to cast and use it in your c# programs, you cast it to decimal.
decimal Price = Convert.ToDecimal(reader.GetValue(1)); 

Thursday, February 10, 2011

Choosing between ASP.NET MVC and ASP. NET Webforms

I've been playing around mvc just recently, i was really shocked and somewhat struggling with this new framework since i was used to the traditional N-Tier development with As I developed simple examples, mvc is somewhat similar to n-tier development. As such, each layers have been separated to enable designers and coders to work independently with each layer. I have some books in my arsenal but i haven't read them yet.LOL

Basically, I'm still a newbie with this stuff. One tip that i read was choosing between webforms and mvc. This will provide insights on other developers as well.

Choosing between ASP.NET MVC and ASP.NET Webforms

Source: ASP.NET MVC 1.0 Quickly

In general, choosing between ASP.NET MVC and ASP.NET can be based on the
following five criteria:

1. Are you considering test-driven development (TDD)?
TDD enables you to write tests for an application first, after which the
application logic is developed. An ASP.NET Webforms application uses only
one class to display output and handle user input. Automated testing of this
class is complex as you are required to load the full ASP.NET stack into a
separate process (for example, in IIS). The MVC framework allows the testing
of each component separately, without requiring the full ASP.NET stack. For
example, you can test your model separately from your controller without
requiring a view. If you are considering TDD, the ASP.NET MVC framework
will be the better choice.

2. Is there a need for fine control over HTML markup?
ASP.NET Webforms automatically inserts hidden HTML markup, IDs,
JavaScript, and so on, into your page's HTML output because of its
event‑driven architecture and its use of ViewState. The ASP.NET MVC
framework allows for 100% control over the HTML output. If you require full
control over your HTML markup, the ASP.NET MVC framework will be the
better choice.

3. Is the application heavily data-driven?
If you are developing an application that is heavily data-driven and is using
grids or a lot of master-detail editing of data, ASP.NET Webforms may
be the better choice as it provides a lot of controls that will aid you in the
development of these kind of applications. Of course, you can use the
ASP.NET MVC framework for these tasks too, but you will be required to
write more code to achieve the same goal.

4. Is there a need for a Winforms-like development approach?
Does your development team write Winforms code? Is there a need for an
event-driven programming approach? In these cases, consider ASP.NET
Webforms in favor of ASP.NET MVC.

5. Is there a need for a rapid application development (RAD)
development approach?
Does your client expect a quick prototype of an application? Is the use of
drag-and-drop development using pre-created web controls required? If so,
consider ASP.NET Webforms in favor of ASP.NET MVC.

As noted, ASP.NET MVC is not a replacement with ASP.NET WEBFORMS!!!

Sunday, February 6, 2011

Calculate Age in SQL Server

Here is a script to calculate an age of a person using TSQL using Convert().
1:  SELECT FirstName, LastName   
2:    ,CONVERT(Int, DATEDIFF(day, BirthDate,   
3:    GETDATE())/365.25) As Age   
4:  FROM EmployeesDTR  

Source: TSQL Reference

Thursday, February 3, 2011

Login Control Never Redirects to Index or Default page

Working with login control in provides convenient way to apply secured user API with less programming. Since login control is part of .net framework,such classes are provided such as membership, forms authentication and etc..

One weird error i encountered is that, it does not redirect to my index page once login has been successful. I implemented my own validation function to check if a user exists in the database. If the method returns true, redirect to index page. See code below. But the fact is, it does not redirect.
  if (CheckUserInMyDB(Login1.UserName, Login1.Password))  
     e.Authenticated = true;  
     Login1.Visible = false;  
     e.Authenticated = false;  
So the solution i found in was to transfer the Response.Redirect to Logged in method of the login control.

Tuesday, February 1, 2011

Insert Parameter Array in .NET

Here's a snippet to insert a parameter array in .NET:
   1:    ' add a class ex. Patient  
   2:      Public Class Patient  
   3:        Public name As String  
   4:        Public code As Integer  
   5:      End Class  
   6:      ' create a delegate   
   7:      Delegate Function myConn() As String  
   8:      'function to return connstring  
   9:      Private Function connectionstring() As String  
  10:        Dim conn As String = "your_connection_string here"  
  11:        Return conn  
  12:      End Function  
  13:      '--Main Sub  
  14:      ' execute insert array    
  15:      Dim objCon As myConn  
  16:        objCon = New myConn(AddressOf connectionstring)  
  17:        Dim str As String = objCon.Invoke()  
  18:        Dim connection As New SqlConnection(str)  
  19:        Try  
  20:          Dim patients As New List(Of Patient)  
  21:          For i As Integer = 0 To max_count_variable  
  22:            Dim patient As New Patient()  
  23:   = "greg nelson" + i.ToString  
  24:            patient.code = i * 2  
  25:            patients.Add(patient)  
  26:          Next  
  27:          connection.Open()  
  28:          Dim query As New StringBuilder  
  29:          Dim cmd As New SqlCommand  
  30:          For j As Integer = 0 To patients.Count - 1  
  31:            query.Append(String.Format("Insert into patients  
  32:               (PatientName,PatientSexCode)   
  33:               values(@names{0},@code{1});", j, j))  
  34:            'declare the parameters  
  35:            cmd.Parameters.AddWithValue(String.Format  
  36:             ("@names{0}", j), patients(j).name)  
  37:            cmd.Parameters.AddWithValue(String.Format  
  38:             ("@code{0}", j), patients(j).code)  
  39:          Next  
  40:          cmd.Connection = connection  
  41:          cmd.CommandText = query.ToString()  
  42:          cmd.ExecuteNonQuery()  
  43:        Catch ex As ApplicationException  
  44:          Throw New Exception(ex.Message)  
  45:        End Try  
  46:        connection.Close()  
  47:        Console.Write("Array successfully saved")  
  48:        Console.ReadLine()  
  49:      '--end main sub 

Monday, January 24, 2011

Bulk Insert Stored Procedure not returning 0 row(s) affected (Error)


A while ago, a friend of mine sent me a CSV file whose fields are separated by comma. I followed a link from in creating a stored procedure via BULK INSERT. This complex stored procedure inserts rows from a csv file to a database table with a field defined as primary key (identity seed option set).

After changing the script from the website and executed the SP below:
1:  use clientdb  
2:  go  
3:  EXEC Customer_Import 'D:\Csharp progs\Orders\Client.csv', 2  

The message returned in the result pane was: 0 row(s) affected. Wow, how could this happend where in fact, the csv has 50 rows? I've changed other options to the SP but got no luck. The solution i ran into was to re-open the CSV file and save as another file. Ex. (from Client to Client1). So, when i executed the SP above using the other file, it performed perfectly.
 use clientdb  
 EXEC Customer_Import 'D:\Csharp progs\Orders\Client1.csv', 2  

So, I guess there must be a problem with the original file, like corrupt data or incorrect data format.