Brian's Blog

items I see across my tribes

“how to prefix class member”

February 27
by briancarter 27. February 2010 14:06

This post isn't meant to start one of those good-old-fashioned-programmer-discussion-wars.  Standards and/or Best Practices when dealing with class member variables. 

I know some developers out there don't like to prefix class member variables because they think it's a holdover from long ago developers.  I know developers who state you must use just _ or m_.  I know developers who state you must use pascalCase.

Taking a fresh look at it: Looking at “Auto-Implemented Properties” (automatic properties), is this argument dead? 

Start VS.Net.  Create a class.  Type prop - - hit tab twice – magic of VS will fill in the properties.  Looking at a sample Person class:

image

Add a method.  Old arguments stated that _ was necessary to avoid using “this.”… gone.  Old argument stated if using camel case – hard to tell what was parameter – property – class member variable… gone. 

image

When the C# compiler encounters an empty get/set property implementation like above, it will now automatically generate a private class member variable for you within your class, and implement a public getter and setter property implementation to it.  The benefit of this is that from a type-contract perspective, the class looks exactly like it did with our more verbose implementation (shown later). 

Making it more concise - DRY?  With the C# compiler you can now take advantage of a great language feature called "object Initializers" that allows code like:

Person p = new Person { FirstName = "Brian", LastName = "Carter" };

Object Initializers are great, and make it much easier to concisely add objects to collections.  For example, if I wanted to add a person to a generics-based List collection of type "Person", I could write the below code:

List<Person> people = new List<Person>();           
people.Add( new Person { FirstName = "Brian", LastName = "Carter"} );

The C# compiler allows you to go even further and also supports "collection initializers" that allow us to avoid having multiple Add statements, very DRY:

List<Person> people = new List<Person> {
new Person { FirstName = "Brian", LastName = "Carter" },
new Person { FirstName = "Dev", LastName = "X" } };

So there you have it.  One may ask, how did Microsoft implement the private class members variables for you?  Did they use _ behind the scenes?  Next post I will dig into the dll and see.

----------------------------------

Some thoughts around old arguments:

Camel case or underscore?

 

image

View from drop downs:

image

Views from the class:

image

Should we even be concerned any longer?

Categories: Development

var -- Using Implicitly Typed locals

February 27
by briancarter 27. February 2010 11:49

I’ve been using the beta of ReSharper 5 as an initial peer review.  The tool offers good advice on ways to improve your code.  I also like to see the “green” light in the upper right corner :-)

With version 4, some people are complaining about numerous suggestions to convert explicit type to "var" keyword.

image

Local variables can be given an inferred "type" of var instead of an explicit type. The var keyword instructs the compiler to infer the type of the variable from the expression on the right side of the initialization statement.  As shown above, the complier knows the type because of the information provided on the right hand side. 

It is important to understand that the var keyword does not mean “variant” and does not indicate that the variable is loosely typed, or late-bound. It just means that the compiler determines and assigns the most appropriate type.

I’ve been trying to keep my solutions DRY (Don't Repeat Yourself).  Using var allows me to keep the DRY principal and invoke var usage wherever possible.  This style allows me to do a code read much quicker:

using (var fileStream = new FileStream(

There are many sides to this discussion, for me, it removes code noise.  It reduces the amount of text I need to read, or rather skip.  I don’t need to specify the type twice – which really helps when using generics. 

Of course, you can hide this suggestion in ReSharper by using Options / Code Inspection / Inspection Severity, or by using Alt-Enter and selecting "Change severity" option.

Thank You for listening.

Categories: Development

Be a Better Developer

February 26
by briancarter 26. February 2010 08:40

Michael Wood gave a great session “Be a Better Developer” last night at the .Net User Group.  The room at the Duthie Center for Engineering was full of attention, listening, and questions. 

Michael’s blog has the elements – but listening and interacting with such topics as:

  • Stop being a Code Monkey
  • Being a Student
  • Being a Janitor
  • Being a Researcher
  • Begin a Plumber

was informative for many roles.  One topic that was covered -  I find myself and others asking - “Should I be a generalist or specialize in a given area?”  Like I found on my trail to research, I must go deep into a subject – there I do what only I can do – and I provide value.   

Michael – Thank You for sharing!  Read more at his blog: http://mvwood.com/blog/beabetterdev.

local copy of Michael’s Slides.

Categories:

Enjoy the Code

February 21
by briancarter 21. February 2010 09:24

Winter   Footsteps Stock ImageSoftware development, I’ve worked on more platforms and applications than I do care to count.  Creating an application is like anything in life.  It is fun, challenging, disappointing, time consuming, learning, exploration, and many more permutations.  The evolution of an idea into something is very rewarding.

Writing papers/journals has a similar trait.  I sit back and say wow… that is great.  Then the critics come along.  Constructive criticism is worthwhile.  “Help me to improve” X.  A fresh set of eyes – maybe a different perspective.  My adrenaline is flowing.

Of coarse, you always get the critic whom has not engaged or has not invested in the creation.  You burn your time getting them up to speed.  Then you will get the critics who just like to poke holes – see the group crash.  Watch out, many people have alternative motives; especially those who have nothing invested.  You will find the coat-tail riders.  Getting on board when they see something may come out of your hard work. 

In the end, whether its a paper or an app, enjoy your travel along the trail.  If you enjoy each step, then whatever happens, you can reflect with positive experiences and growth.  If you are carrying a load for someone else, being taken advantage of, make sure you find the positives for yourself.  Papers get rejected, apps get shelved, and your time will never return.  Enjoy the trip and enjoy each step – enjoy the code – enjoy the writing, and you may find enjoyment no matter the ending.   

Categories:

SQL Server: Row Count for Large Tables

February 21
by briancarter 21. February 2010 08:56

When working on tables with a large number of records, one must be careful using a simple statements like SELECT COUNT(*) FROM[Table_Name]; especially when you are bulk inserting items into a table and want to get a count. 

The simple count statement takes forever to return row count on large tables. Its because it uses full table scan to count number of rows. A better approach to get the row count on any table is to query new Dynamic Management Views (DMV) in SQL Server 2005+ sys.dm_db_partition_stats. DMV contains row count and page counts for any table including all the partitions. Please note that if you did not create partitions for your table, your table still going to be created on single default partition; so you are using partitions.

The statement below will provide the total number of rows – very quickly:

SELECT
  Total_Rows= SUM(st.row_count)
FROM
  sys.dm_db_partition_stats st
WHERE
  object_name(object_id) = '!!YOUR TABLE!!'
  and (index_id <2)

Categories:

SSMS SQLCMD for VS.Net DB projects

February 13
by briancarter 13. February 2010 18:31

When using VS.Net database projects, the tool will gen your scripts needed for deployment.  The tool uses SQL Command scripts.  By default SSMS doesn’t turn this option on.

 

To successfully run the generated scripts, you must:

SSMS 2008 –> Tools –> Options -> Check “Open in CMD mode”

SSMS Options

While adding support for SQLCMD syntax to Query Editor, the development team envisioned two primary scenarios. One scenario is to make Query Editor more powerful by supporting new commands in addition to GO. The other one is to enable writing and debugging SQLCMD scripts in Query Editor so that they can be executed later from batch files with the SQLCMD.EXE command line tool.

Now you can try using this mode to author and execute in Query Editor a simple query that selects all columns from a table whose name is specified by a SQLCMD variable.

Create a new query window and connect to AdventureWorks. Turn on the SQLCMD mode. After that, type the following in the text editor area of the query window:

:setvar tablename HumanResources.Department
go
select * from $(tablename)
go

Please note the same rules apply as if we were working in console mode, that is, the command should be the first statement on the line.

Notice that the line containing the :setvar SQLCMD command is highlighted. All recognized SQLCMD commands are highlighted this way so that it is clear that the command is not part of T-SQL syntax.

Now you can use the power of the commands created from the VS tool.  Try the tool on a few databases – it provides some great examples for using the power of SQL.

TY Sudheer for getting this documented.

Categories: Development

SQL Server default Values for columns

February 08
by briancarter 8. February 2010 08:57

Running backend jobs, set the
CreatedBy to user_name()
CreatedOn to getdate()

Front-end – pass in CreatedBy

Categories: Development

C# data type Refresher with Financial Issue

February 07
by briancarter 7. February 2010 11:03

We all need a refresher on the basics.  I’ve covered data types before, but the hierarchy below sums it up in a clear diagram:

The C# type hierarchy.

 

At the leafs, the float vs Integral is clearly shown.  Integrals (Integer) are viewed as subset of the real numbers, they are numbers that can be written without a fractional or decimal component. For example, 65, 7, and −756 are integers; 1.6 and 1½ are not integers. The set of all integers is often denoted by a boldface Z.

The C# standard only lists double and float as floating points available (those being the C# shorthand for System.Double and System.Single), but strictly speaking the decimal type (shorthand for System.Decimal) is also a floating point type.

The decimal type is just another form of floating point number - but unlike float and double, the base used is 10.  Compared to floating-point types, the decimal type has more precision and a smaller range, which makes it appropriate for financial and monetary calculations.

image

 

Financial Issue Testing

Let’s review financial situations. Say we are using floats to track the money. 

123,456.78 + 123.45 = $123,580.2  --> should calculate to $123,580.23

What happen – float only can support 7 digits, so C# converted number to 123456.8 + 123.45 – since last digit is 5 or less – it rounded down.  If the number would of ended in a 6 or above – it would of rounded up.  Lost $0.03 – do this to many times in your shopping cart and it will add up.

Do you have financial reports for month/year end? 

float x1 = float.Parse("1234567890.12");  //1.234568E+9
x1.ToString();  //"1.234568E+09"

oops… off by over $110 bucks.  Use decimal type for financial fields.

 

Stress testing float – double - decimal

--------- Show limits of float  ----------------

123.4567
float = 123.4567, double = 123.4567, decimal = 123.4567

123.45678
float = 123.4568, double = 123.45678, decimal = 123.45678

--------- Show limits of double  ----------------

123.456789012345
float = 123.4568, double = 123.456789012345, decimal = 123.456789012345

123.4567890123456
float = 123.4568, double = 123.456789012346,
decimal = 123.4567890123456

--------- Show limits of decimal  ----------------

123.45678901234567890123456789
float = 123.4568, double = 123.456789012346, decimal = 123.45678901234567890123456789

123.456789012345678901234567899
float = 123.4568, double = 123.456789012346, decimal = 123.45678901234567890123456790

Categories: Development

INSERT INTO for SQL 08

January 23
by briancarter 23. January 2010 08:46

In SQL Server 2008, a new insert feature is available which will make inserting of values easier. 

How do you insert multiple rows in SQL with using only one SELECT statement:

 

SQL Server 2008 Method of Row Construction:
INSERT INTO MyTable (FirstCol, SecondCol)
VALUES ('First',1),
('Second',2),
('Third',3),
('Fourth',4),
('Fifth',5)

Previous method 1:
INSERT INTO MyTable (FirstCol, SecondCol)
VALUES ('First',1);
INSERT INTO MyTable (FirstCol, SecondCol)
VALUES ('Second',2);
INSERT INTO MyTable (FirstCol, SecondCol)
VALUES ('Third',3);
INSERT INTO MyTable (FirstCol, SecondCol)
VALUES ('Fourth',4);
INSERT INTO MyTable (FirstCol, SecondCol)
VALUES ('Fifth',5);
GO


Previous method 2:
INSERT INTO MyTable (FirstCol, SecondCol)
SELECT 'First' ,1
UNION ALL
SELECT 'Second' ,2
UNION ALL
SELECT 'Third' ,3
UNION ALL
SELECT 'Fourth' ,4
UNION ALL
SELECT 'Fifth' ,5
GO

Using SQL Server 2000, no problem.  Get a test db on SQL Server 2008 – do your updates – then use a tool to script out the inserts.  I use SSMS Tools Pack: http://www.ssmstoolspack.com/

Categories: Development

Refresher: SQL Server 2000 Limitations

January 20
by briancarter 20. January 2010 17:30

Limitations of SQL Server 2000

·         Varchar 8,000 characters

·         NVarchar 4,000 characters

·         Row max characters = 8,000 for all columns, NVarchar count for 2 each char

 

(This is not an issue with SQL 2005 & 2008 - limit is 2GB.)

 

Categories: Development


 Questions or Feedback, my contact information is located on my About page.


The opinions, thoughts, and comments made in these blog posts are solely my own (unless otherwise stated). They do not reflect the opinions, thoughts or practices of my employer, my universities, my family, or anyone else. Also, I retain the right to change my mind about anything I publish here without having to go back and edit posts that occurred in the past. 

These are my opinions, or just as likely, someone else's opinions that I leveraged for my own.