Feb262008

Smarter Visual Studio 2008 IDE and compiler

Visual studio 2008 is really smart :), it catches a lot of things such as never assigned variables, never used varriables, not reachable part of code kinda thinga. However i wish it has one more check that could save my time on debugging a code :) Below is the code, i was struggling, see if u can catch it :)

[code:c#]
public class clsStudent
{
    #region Member Variables
    public int ID_;
    public int ID
    {
        get { return ID; }
        set { ID_=value;}
....
....
}
[/code]
Ok now where is the problem :)), the problem is get{return ID;} instead of get{return ID_}. Ok i admit that it was first of all my mistake to name those 2 variables very familiar, however isnt it obvious that this a deadly endless recursive call that visual studio should catch ? It doesnt catch it and if you run the code you will get a stack overfill error or something like this.

For those who cant see the bug, return ID; is calling get{return ID} again, and it happens again and again......

Anyways if you use automatic properties u wont have this problem, but our servers arent .net 3.5 yet :)



Tags:

E-mail | Permalink | Trackback | Post RSSRSS comment feed 0 Responses

Feb242008

Visual Studio 2008 and Sql Server 2008 Launch

Inland Empire .NET User group will be hosting a launch event for visual studio 2008 and sql server 2008 on March 11. I am one of the presenter for "C# 3.0 New Features". Everybody is invited to our launch event, don't forget Microsoft will give away 5 licences for sql server 2008 and visual studio 2008. For more information : http://www.iedotnetug.org

There is also a conference "SecureIT" from March 4 to March 6. The agenda is pretty heavy, i will be attending to the 3 day seminar, if you will come, let me know :)

 



Tags:

E-mail | Permalink | Trackback | Post RSSRSS comment feed 0 Responses

Feb202008

Visual Studio Code Snippets

I really like using code snippets in visual studio environment; unfortunately i dont have enough money to buy resharper :) so for code completion or code templates code snippets is my only choice. There are lot's of snippets that come with visual studio; they are stored @"D:\Program Files\Microsoft Visual Studio 9.0\VC#\Snippets\1033" depending on your installation folder. As much as there is a lot, i would love to add my code snippets :) . All snippets files are xml files, and it has a structure that you have to learn, eventhough it is relatively easy i dont want to learn it :). I found this great tool that really helps you to create a snippet. You can download it from: http://billmccarthy.com/Projects/Snippet_Editor/ . Dont be mistaken with visual basic title, you can use it for c# too which actually i am using for. So you download this program, and run it, the rest is easy :). To show how it really is simple; lets create a snippet for console.writeline.
A lot of times i use Console.WriteLine("{0}",somevalue) , so why not use a snippet for it.

Run the snippet editor. Fill in the fields as below :

To add the the $param1$, first just write param1, select it with your mouse, right click on it, then select Add replacement. The snippet editor will create a variable, and wrap "param1" with $ and it will be changed to $param1$. This represents a variable in visual studio environment, so whenever you add this snippet, and use the tab key to iterate through your code, visual studio editor will select $param1$. Save this snippet to the code snippet folders of your own. Consuming it is very easy, while you are typing your code; just write consw (which is the shortcut we defined), and hit tab twice.  If you want to see a small flash video, here it is:



Tags:

E-mail | Permalink | Trackback | Post RSSRSS comment feed 2 Responses

Feb182008

var in C# ?!! Anonymous Type

With C# 3.0, the anonymous type is introduced. Keyword "var" helps you to define an anonymous type. Let's start with a simple example.

[code:c#]
int i = 5;
var j = 6;
Console.WriteLine("i is {0}, j is {1}", i, j);
[/code]

As you can see, we did not tell the compiler what "j" is, however the compiler could figure it out from the assignment. Yes, this is a rule, var declerations should be assigned to a variable type to help the compiler understand the type of var. So at the compile time, the compiler changes the type of var to the type that is specified with the assignment. If you compile the above code, and open the ildasm tool to see the il code, you will see that j is an integer.

This also means that you can't have a declaration like:
[code:c#]
var k;
[/code]

"var" is very much usefull in linq, but you dont need to write linq applications to benefit from it, you can use it to simplify your code such as :
[code:c#]
List<int>arrInts = new List<int>(); // means exactly the same thing as below
var arrInts2 = new List<int>();
[/code]

There are some other restrictions upon using var. For example you can't have a global anonymous variable, it has to be local.

There is a very interesting use of var (actually the only time it really makes sense ). Declaring anonymous class types on the fly such as:
[code:c#]
var student = new {FirstName="Joe", LastName="Doe", Age=21, Address="Some Address"};
Console.WriteLine(student.FirstName);
[/code]
So we've just created an object with 4 attributes on the fly, and the compiler could do the type conversions looking at the assignments.



Tags: , ,

E-mail | Permalink | Trackback | Post RSSRSS comment feed 0 Responses

Feb152008

Lambda Expressions

One of the new things that came new with c# 3.0 is lambda expressions. I started to read about them yesterday (yes, shame on me but i was busy ok ??!). It isnt easy to understand the expressions, but while i was reading the apress pro linq book, at chapter 2, i saw a good example :) that i want to share.

Let's say we have a function that accepts an array of integers, and a filter function. It will appy the filter to the array, and returns the integers that passes the filter. The sample function could be something like this:


[code:c#]
public static List<int> FilterArrayOfInts(int[] ints, IntFilter filter)
{
    List<int> arrInts= new List<int>();
    foreach (int i in arrInts)
        if (filter(i))
            arrInts.Add(i);
    return arrInts;
 }
[/code]

So now, if we want to have a filter so that, our function returns only the odd numbers, we could write a function like below:
[code:c#]
public static bool IsOdd(int i)
{
    return ((i & 1) == 1);
}
[/code]

We can easily define a delegate function such as :
[code:c#]
public delegate bool IntFilter(int i);
[/code]

This delegate function can point to functions that takes an integer as a parameter and returns bool. So if want to use this in our main function, we can have a code like this :
[code:c#]
int[] nums = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
List<int> oddNums = FilterArrayOfInts(nums, IsOdd);
[/code]

What we've done is, we passed our IsOdd function as a filter function to get the odd numbers. This is old classical way :). Now with C# 2.0, we have anonymous delegates, which might help our problem. Anonymous delegate are inline functions that dont have a name and they are defined at the point they are called.  Of course one drawback is you can't reuse the anonymous delegates without our evil-devil copy-paste habit. But in this scenario, i dont think that IsOdd is a reusable function so i will rewrite this using anonymous delegate. So lets do this :)
[code:c#]
List<int> oddNums2= FilterArrayOfInts(nums, delegate(int i) { return ((i & 1) == 1); });
[/code]

As you can see above, instead of passing a predefined function as a parameter, we created an anonymous delegate right at the point we need it, and it still returns a bool, and takes an int as a parameter. Simple heh ?!

Last step is using lambda expression instead of anonymous delegates, which will bring a little bit readibility to our function. Sample code is below:
[code:c#]
List<int> oddNumb2 = FilterArrayOfInts(nums, i => (i&1)==1);
[/code]

ohhh what have we done :) . i=> means i goes to. Look what doe i go to ; i goes to (i&1)==1 expression result right ? and, a==b returns either true or false, so it means i goes to a boolean variable. Himm our filterarrayofints function requires a function that returns a bool right ? so that is it :)

You want more lambda expressions ? wait :)



Tags:

E-mail | Permalink | Trackback | Post RSSRSS comment feed 0 Responses

Feb122008

Custom Attribute for XHTML, .NET, Checkbox event in the gridview

I have a gridview and of course a template field. I dont know why, but whenever i drag to a gridview to my page, i always put a template field. Maybe bad design dunno. Anyways, i put a checkbox on the template field and autopostback for the checkbox is true. So what i aim to do, whenever a checkbox is checked in the gridview, handle the checked event, and update some database tables. In order to do this, i need to figure out which checkbox is clicked, so i can get the rowid and from there i can get the data key and go to database ...

Himmm, gridview does not fire rowcommand event when the checkbox is clicked, so i couldnt really figure out which check box is clicked. I looked for a place in the checkbox properties to put the row id somewhere in the rowbound event, so maybe i can read it later ?! I couldnt find any :))

Then i thought of adding a custom attribute to the checkbox, and store the datakey in this custom attribute, and read this datakey in the click event. Himm When you say custom attribute, xhtml, validation; i am sure there is more than just adding the attribute. So my friend Brian, helped me to findout a good article : http://www.alistapart.com/articles/customdtd/ which explains custom dtd attributes. So the first thing i did is handle the rowdatabound event and add the custom attribute as below :

[code:c#]

if (e.Row.RowType == DataControlRowType.DataRow)
{
 CheckBox ckbDisplay = e.Row.FindControl("ckbDisplay") as CheckBox;
 ckbDisplay.Attributes.Add("RowID", gridEvents.DataKeys[e.Row.RowIndex].Value.ToString());
           
}

 [/code] 

And of course there is the checkbox check event :

[code:c#]

protected void ckbDisplay_CheckedChanged(object sender, EventArgs e)
{

CheckBox ckbDisplay = sender as CheckBox;
string sKey = ckbDisplay.Attributes["RowID"];

// do some stuff here....

}

 

[/code]

I run the page, and look at the source code, what .NET framework does is wrapping the input type='checkbox' (which is asp:CheckBox) , with <span RowID='somevalue... . I checked this with different browser, and .NET framework generated the same source code. So i went to my doc type decleration and changed the decleration as follows :

[code:xml]

 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"

[<!ATTLIST span RowID CDATA #IMPLIED>]
>

[/code]

Above, i am telling to the xhtml validator that, my span elements may ( #IMPLIED means may, #REQUIRED means must ) have an attribute RowID.

So, that easy :)



Tags: , , ,

E-mail | Permalink | Trackback | Post RSSRSS comment feed 1 Responses

Feb112008

Facebook Apps

I happen to do some basic application for facebook, to see the capabilities. I dealt a little bit with FABML. The scary part of it is you can see what an application you are installing is capable of.

By default ( and i dont think people change default settings ), all the applications you install to your profile have access to your friends'list photos, profile info such as first name, last name, address, groups u 've joined etc.

The email, inbox, outbox, messaging system is protected. Ahh also people are selling their application database (which has ur and ur friend's info, photos etc ) in the forums

so just watch our for what u r installing ehh  



Tags:

E-mail | Permalink | Trackback | Post RSSRSS comment feed 0 Responses

Feb072008

Reading Writing to Excel Worksheet ADO.NET, C#

One of my friend asked me how he can parse excel sheet, add/read data to excel sheet. The first thing that came to my mind is interop, but then he told me that he would take averages of some columns and group them. Himm, this thing reminds me sql commands :) Of course suddenly my mind changes from interop farmland to ado.net farmland. i start writing the code; however i got some stupid errors, like :

 

  •  if you dont close connection object to your excel file, your writes are in the buffer, and not written to the excel file
  • when you create a new worksheet, DONT use $ at the end of the worksheet name
  • when you read from a worksheet USE $ at the end of the worksheet name, even if u created without $

Anyways here is a very brief code  i used in this small app

[code:c#]

 private string CreateASheet()
{
if (FileName == String.Empty)
return String.Empty;
string connectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;
Data Source=" + FileName + @";Extended Properties=
""Excel 8.0;HDR=YES;""";
string SheetName = DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString() +
DateTime.Now.Hour.ToString() +
DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString();
string CreateCommand = "Create Table " +SheetName+
" (Ticker varchar(255),Average_Price varchar(50), Average_Bid varchar(50));";
OleDbConnection conn = new OleDbConnection(connectionString);
try
{
conn.Open();
OleDbCommand cmd = new OleDbCommand(CreateCommand, conn);
cmd.ExecuteNonQuery();
}

finally
{
conn.Dispose();
}
return SheetName;
}

[/code] 

[code:c#]

if (FileName == String.Empty)

return;

string connectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;

Data Source="+FileName+@";Extended Properties=

""Excel 8.0;HDR=YES;""";

OleDbConnection conn = new OleDbConnection(connectionString);

conn.Open();

OleDbCommand cmd = new OleDbCommand(@"select ticker,avg(prc) as average_price,

avg(bid)as Average_Bid from [051923748$] group by ticker order by ticker", conn);

OleDbDataAdapter adapter = new OleDbDataAdapter(cmd);

DataTable dt = new DataTable();

adapter.Fill(dt);

...

... 

[/code] 



Tags:

E-mail | Permalink | Trackback | Post RSSRSS comment feed 0 Responses

Feb052008

TDD Meeting LADOTNET

I attended the meeting yesterday with 10 minutes delay as somebody decided that she could drive and use her cell phone at the same time, and also hit my car. So the traffic, the accident, 80 miles to drives etc did not scare me :) i got there 10 minutes late. Here is my short notes from the meeting so i will remember what to study for my presentation :)(

  • xunit is new framework for testing, you can get it from http://www.codeplex.com/xunit. Created by the same guys who created nunit.
  • Mock objects, database design should be seperate from ui design or middle layer design. They should'nt be dependent to each other
  • any unit test should not depend on any other unit test, try to run away from testinitialize function as it increases dependency
  • unit test is not integration test, qa test will test the whole app behaviour
  • unit test does not jump boundaries
  • unit tests always automated, always repetable, no dependancy
  • Red, Green, Refactor ( read this more in detail )
  • Scrum
  • pair programming sometimes work, one developer writes the code, the other developer writes the test for the code, and they change the roles
  • Arrange, Act, Assert (AAA)
  • how dou organize and find something in a >1500 tests
  • code coverage. Try to cover %100 of ur code
  • Load testing in vs 2005 simulates browser and connection speed, it also has data binding

 



Tags:

E-mail | Permalink | Trackback | Post RSSRSS comment feed 0 Responses

Feb042008

Test Driven Days

Today, i will do my best to attende the los angeles .net developers user group meeting, to listen Russ Nemhauser  talking about "An introduction to Unit Test, Test-Driven Development and Mock Objects". February 19, i will be attending inland empire .net user group meeting, to listen Tom Opgenorth talking about "Introduction to Test Driven Development". And after after that :), sometime in march, i will be presenting at Inland empire .net user group the new test projects that come with visual studio 2008. So i guess test driven days are waiting for me :))


Tags:

E-mail | Permalink | Trackback | Post RSSRSS comment feed 0 Responses