Total Pageviews

Thursday, August 9, 2012

Strings vs string Builder

Defining Verbatim Strings

When you prefix a string literal with the
@ symbol, you have created what is termed a verbatim
string
. Using verbatim strings, you disable the processing of a literal’s escape characters and print
out a
string as is. This can be most useful when working with strings representing directory and
network paths. Therefore, rather than making use of
\\ escape characters, you can simply write the
following:
// The following string is printed verbatim
// thus, all escape characters are displayed.
Console.WriteLine(@"C:\MyApp\bin\Debug");

Strings: Strings are immutable , that is when you are manipulating the strings every time a new object is created, and the old one is garbage collected.
the
string type can be inefficient and result in bloated code if misused, especially when performing string concatenation. If you need to represent basic character data such as a US Social Security number (SSN), first or last names, or simple string literals used within your application, the string data type is the perfect choice.However, if you are building an application that makes heavy use of textual data (such as a word processing program), it would be a very bad idea to represent the word processing data using string types, as you will most certainly (and often indirectly) end up making unnecessary copies of string data. 

Strings use System.String Namespace.

String Builder;
What is unique about the
StringBuilder is that when you call members of this type, you are
directly modifying the object’s internal character data (and is thus more efficient), not obtaining a
copy of the data in a modified format. When you create an instance of the
StringBuilder, you cansupply the object’s initial startup values via one of many
constructors.
By default, a
StringBuilder is only able to hold a string of 16 characters or less;
however, this initial value can be changed via an additional constructor argument:
// Make a StringBuilder with an initial size of 256.
StringBuilder sb = new StringBuilder("**** Fantastic Games ****", 256);
If you append more characters than the specified limit, the
StringBuilder object will copy itsdata into a new instance and grow the buffer by the specified limit.

Declaring Variables

Local Variables when declared must be initialized before they are used, otherwise a compile time error will be raised.

“New-ing” Intrinsic Data Types
All intrinsic data types support what is known as a
default constructor. In a nutshell,
this feature allows you to create a variable using the
new keyword, which automatically sets the variable to its default value:
Although it is more cumbersome to use the
new keyword when creating a basic data type variable,
the following is syntactically well-formed C# code and more advisable.
static void NewingDataTypes()
{
Console.WriteLine("=> Using new to create intrinsic data types:");
bool b = new bool(); // Set to false.
int i = new int(); // Set to 0.
double d = new double(); // Set to 0.
DateTime dt = new DateTime(); // Set to 1/1/0001 12:00:00 AM
Console.WriteLine("{0}, {1}, {2}, {3}", b, i, d, dt);
Console.WriteLine();
}

Tuesday, August 7, 2012

the Main() Method

the class that defines the
Main() method is termed the application object
.
While it is possible for a single executable application to have more than one application object
(which can be useful when performing unit tests), you must informthe compiler which
Main()
method should be used as the entry point via the
/main option of the command-line compiler.
Note that the signature of
Main() is adorned with the static keyword, implies that static members are scoped to the class level (rather than the object level) and can thus be invoked without the need to first create a new class instance.
In addition to the
static keyword, this Main() method has a single parameter, which happens
to be an array of strings (
string[] args). Although you are not currently bothering to process this
array, this parameter may contain any number of incoming command-line arguments (you’ll see
how to access them momentarily). Finally, this
Main() method has been set up with a void return
value, meaning we do not explicitly define a return value using the
return keyword before exiting
the method scope.
The logic of
Program is within Main() itself. Here, you make use of the Console class, which is
defined within the
System namespace. Among its set of members is the static WriteLine() which, asyou might assume, pumps a text string and carriage return to the standard output.

While a vast majority of your
Main() methods will return void as the return value, the ability to
return an
int from Main() keeps C# consistent with other C-based languages. By convention,
returning the value
0 indicates the program has terminated successfully, while another value (such
as
-1) represents an error condition (do be aware that the value 0 is automatically returned, even ifyou construct a
Main() method prototyped to return void).
Processing Command-Line Arguments
Now that you better understand the return value of the
Main() method, let’s examine the incoming
array of
string data. Assume that you now wish to update your application to process any possiblecommand-line parameters.

One way to do so is using a C# for loop
As an alternative to the standard
for loop, you may iterate over an incoming string array usingthe C#
foreach keyword.
Finally, you are also able to access command-line arguments using the static
GetCommandLineArgs()
method of the System.Environment type. The return value of this method is
an array of
strings. The first index identifies the name of the application itself, while the remaining
elements in the array contain the individual command-line arguments (note that when using this
approach, it is no longer necessary to define
Main() as taking a string array as the input parameter,
although there is no harm in doing so):
static int Main(string[] args)
{
...
// Get arguments using System.Environment.
string[] theArgs = Environment.GetCommandLineArgs();
foreach(string arg in theArgs)
Console.WriteLine("Arg: {0}", arg);
Console.ReadLine();
return -1;
}



Some Additional Members of
the System.Environment Class
Environment.GetLogicalDrives()
Environment.OSVersion

ExitCode
Gets or sets the exit code anywhere within the application
MachineName
Gets the name of the current machine
NewLine
Gets the newline symbol for the current environment
StackTrace
Gets the current stack trace information for the application
SystemDirectory
Returns the full path to the system directoryUserName Returns the name of the user that started this application

what are the features of C#

core C# features that are found in all versions of the language:
• No pointers required! C# programs typically have no need for direct pointer manipulation
(although you are free to drop down to that level if absolutely necessary).
• Automatic memory management through garbage collection. Given this, C# does not support
a
delete keyword.
• Formal syntactic constructs for classes, interfaces, structures, enumerations, and delegates.
• The C++-like ability to overload operators for a custom type, without the complexity (e.g.,
making sure to “return
*this to allow chaining” is not your problem).
• Support for attribute-based programming. This brand of development allows you to annotate
types and their members to further qualify their behavior.
• The ability to build generic types and generic members. Using generics, you are able to build
very efficient and type-safe code that defines numerous “placeholders” specified at the time
you interact with the generic item.
• Support for anonymous methods, which allow you to supply an inline function anywhere a
delegate type is required.
• Numerous simplifications to the delegate/event model, including covariance, contravariance,
and method group conversion.
• The ability to define a single type across multiple code files (or if necessary, as an in-memory
representation) using the
partial keyword.
• Support for strongly typed queries (a la LINQ, or Language Integrated Query) used to interact
with various forms of data
• Support for anonymous types, which allow you to model the “shape” of a type rather than its
behavior
• The ability to extend the functionality of an existing type using extension methods
• Inclusion of a lambda operator (
=>), which even further simplifies working with .NET delegate
types
• A new object initialization syntax, which allows you to set property values at the time of
object creation

Thursday, August 2, 2012

ViewBag

The ViewBag is a dynamic object that provides a convenient late-bound way to pass information to a view.
ASP.NET MVC also provides the ability to pass strongly typed data or objects to a view template. This strongly typed approach enables better compile-time checking of your code and richer IntelliSense in the Visual Web Developer editor. We're using this approach with the MoviesController class and Index.cshtml view template.

Test Driven Development


TDD shortens the programming feedback loop whereas AMDD shortens the modeling feedback loop.
TDD provides detailed specification (tests) whereas AMDD is better for thinking through bigger issues.
TDD promotes the development of high-quality code whereas AMDD promotes high-quality communication with your stakeholders and other developers.
TDD provides concrete evidence that your software works whereas AMDD supports your team, including stakeholders, in working toward a common understanding.
TDD “speaks” to programmers whereas AMDD speaks to business analysts, stakeholders, and data professionals.
TDD is provides very finely grained concrete feedback on the order of minutes whereas AMDD enables verbal feedback on the order minutes (concrete feedback requires developers to follow the practice Prove It With Code and thus becomes dependent on non-AM techniques).
TDD helps to ensure that your design is clean by focusing on creation of operations that are callable and testable whereas AMDD provides an opportunity to think through larger design/architectural issues before you code.
TDD is non-visually oriented whereas AMDD is visually oriented.

Threads overview

Threads are the operating system construct used by the common language runtime to execute code. At run time, all managed code is loaded into an application domain and is run by a managed thread.
There is not a one-to-one correlation between application domains and threads. Several threads can be executing in a single application domain at any given time and a particular thread is not confined to a single application domain. That is, threads are free to cross application domain boundaries; a new thread is not created for each application domain.

At any given time, every thread is executing in an application domain. Zero, one, or more than one thread might be executing in any given application domain. The run time keeps track of which threads are running in which application domains. You can locate the domain in which a thread is executing at any time by calling the GetDomain method.
You can attach a CultureInfo object to a thread. However, to prevent malicious code from entering other application domains, the CultureInfo object is automatically set to read-only when its thread crosses an application domain boundary.

using System;
  using System.Threading;
 
  class Test
  {
      static void Main()
      {
          Thread newThread = new Thread(new ThreadStart(ThreadMethod));
          newThread.Start();
      }
 
      static void ThreadMethod()
      {
          Console.WriteLine(
              "Thread {0} started in {1} with AppDomainID = {2}.",
              AppDomain.GetCurrentThreadId().ToString(),
              Thread.GetDomain().FriendlyName,
              Thread.GetDomainID().ToString());
      }
  }