Friday, February 18, 2011
Grouping items in Order By Statement
...
ORDER BY
CASE WHEN column = 'this' THEN 2 ELSE 1 END asc,
othercolumn asc,
another column desc
...
to group items separately and then apply a secondary sorting within each group...
Thursday, March 20, 2008
OOP Concepts
1. POLYMORPHISM: In object-oriented programming, polymorphism (from the Greek meaning "having multiple forms") is the characteristic of being able to assign a different meaning or usage to something in different contexts - specifically, to allow an entity such as a variable, a function, or an object to have more than one form.
2.ENCAPSULATION: Conceptually, encapsulation means hiding the internal details of a class's operation.Goal of encapsulation: use an object without understanding or depending on its internal details.
3.INHERITANCE: Inheritance is used to establish hierarchical class relationships.In inheritance, one class (the subclass) adopts (inherits) the features of another class (the superclass).
4.ABSTRACTION:In object technology, determining the essential characteristics of an object. Abstraction is one of the basic principles of object-oriented design, which allows for creating user-defined data types, known as objects.
Wednesday, March 19, 2008
Dispose(), Destructor/Finalizer
Not the best place to put cleanup code.
Ex: open a database connection and put the cleanup code in the Destructor. That DB connection might stay open for the life of the entire application. Not good!
Dispose() method:
A better place to put cleanup code.
Mostly used to cleanup unmanaged resources.
using{} statement automatically calls the Dispose() before exiting.
Recommended to be called only if the object is resource intensive.
References:
http://www.dotnetspider.com/qa/Question1450.aspx
Access Modifiers (public, private, ...)
classes: internal by default. (can be internal or public, can NOT be private, protected or protected internal)
interfaces & enumerations: always public, no access modifier needed or allowed.
namespaces: always public
Struct members: private by default. (can be public, private, internal)
public: accessible from instance & derived classes
private: NOT accessible from instance nor derived classes
protected: NOT accessible from instance but accessible from derived classes
internal: accessible from instance & derived classes WITHIN THE SAME ASSEMBLY ONLY.
protected internal: NOT accessible from instance but accessible from derived classes of the same assembly.
So, if a member is marked as protected, then it is accessible from derived classes of the SAME assembly or other assemblies.
Tuesday, March 18, 2008
Reference & Value Types and Primitive Types
All numeric data types
Boolean, Char, and Date
All structures, even if their members are reference types
Enumerations, since their underlying type is always Byte, Short, Integer, or Long
Reference types:
String
All arrays, even if their elements are value types
Class types, such as Form
Delegates
Primitive types:
Some of the data types are used very frequently during programming. To ease coding using these data types, compilers allow us to usesimplified syntax.
So, the data types supported directly by the compiler are called primitive types and these types map to the types in the Base Class Library (BCL).
For instance, instead of initializing an integer like this;
System.Int32 i = new System.Int32(10); //Throws compiler error
we can easily initialize it using below line of code:
int i =5;
So, the primitive type "int" maps to "System.Int32" type in the BCL.
string maps to System.String.
object maps to System.Object.
...
Boxing & Unboxing:
Boxing refers to the operation of converting a value type to a reference type.
Int32 v = 5; // Create an unboxed value type variable
Object o = v; // o refers to a boxed version of v
v = 123;
-----------------------------------------------------------
public static void Main() {
Int32 v = 5; // Create an unboxed value type variable
// When compiling the following line, v is boxed 3 times
// wasting heap memory and CPU time
Console.WriteLine(v + ", " + v + ", " + v);
// The lines below use less memory and run faster
Object o = v; // Manually box v (just once)
// No boxing occurs to compile the following line
Console.WriteLine(o + ", " + o + ", " + o);
}
default Keyword in Generic Code:
This is an issue with the generics concept in .NET 2.0.
public class GenericList
{
}
When we do not know in advance,
whether the type T is a value or a reference type
and if it is a value type whether is it a numeric value or a struct
we can use the default keyword.
T theTypeInstance= default(T);
This initializes theTypeInstance;
to null if T is a reference type,
to 0 if numeric,
the references types of the struct to null & the numeric types of the struct to 0.
References:
http://msdn2.microsoft.com/en-us/magazine/cc301569.aspx
http://msdn2.microsoft.com/en-us/magazine/bb984984.aspx
http://msdn2.microsoft.com/en-us/library/xwth0h0d(VS.80).aspx
Monday, March 17, 2008
C# indexer
public
Example:
public string this [int theIndex]
Sample C# Use:
using System;
//Indexer Class Declaration
class MyIntIndexer
{
private string[] theData;
public MyIntIndexer(int size)
{
theData= new string[size];
//Initialize
for (int i=0; i < size; i++)
{
theData[i] = "nothing";
}
}
public string this[int position]
{
get
{
return theData[position];
}
set
{
theData[position] = value;
}
}
static void Main(string[] args)
{
int size = 5;
MyIntIndexer myIndexer = new MyIntIndexer(size);
myIndexer[3] = "str3";
myIndexer[1] = "str1";
myIndexer[5] = "str5";
}
}
Monday, March 10, 2008
const vs readonly
a readonly member's value can be set at runtime as well as compile time.
static means the member is not tied to the instances of the class. There exists only one copy of the static member regardless of the number of instances.
Thursday, December 27, 2007
Design Patterns
Creational:
Abstract Factory: Creates concrete instances of classes.Singleton:
Creates a single instance of a class and ensures there is only one instance in the system.
Class contruction: Keep a private member in the class and let the constructor initialize it only if that member is null.
Application: System resources; there is only one printer in the system and we must access it thru singleton pattern.
Structural:
Facade: Represents an entire system of subclasses.
Proxy: Not the real object itself, just represents the real object.
Behavioral:
Command:
A command request is encapsulated as an object.
Observer:
Notifies changes to classes.
Application: Error logging.
Web Design specific:
MVC (Model-View-Controller):
Complete separation of the;
model (database),
view (page view) and
controller (business logic).
Thursday, November 29, 2007
.NET Framework 3.5 Released!!
Along with that .NET Framework 3.5 was also available as a Beta version and as of 19th of November 2007, .NET Framework's 3.5 version has officially been released!
A new toy for us programmers to play around isn't it?! :)
So with this version it's been about two years know after .NET Framework 2.0' release in 2005.
Here are the direct links to download from Microsoft - for those who wanna skip to the download right away!
Download Microsoft .NET Framework 3.5
I'd suggest to download the express version of Visual Web Developer 2008 along with the new framework:
Download Visual Web Developer 2008 Express
Download Visual C# 2008 Express
Find the rest of the 2008 Express Series by clicking here.
I played around little bit with the VWD 2008 Express. Three things that came to my sudden interest:
- Microsoft's recent popular keywords: Controls for AJAX, Silverlight & LINQ are available in the toolbox.
- CSS Properties & Manage Styles tabs saying "hello!" from the left border of the VWD.
- "Split" design mode in addition to 'HTML' and normal 'Design' mode. Was available in Frontpage. Good to see it now in VWD or Visual Studio let's say for those who are lucky to start developing in the 2008 version of Visual Studio! :)
Will keep sharing my experiences with .NET Framework 3.5 and Visual Web Developer!
Please gimme your comments on this and make me happy :)
Tuesday, October 30, 2007
Assembly References
Even if you are preparing for an interview question or doing the actual programming, you have to know you need to create an assembly reference in .net so that your compiler can compile the program.
An example to this mistake: The programmer includes the below code to the top of the C# class file.
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;
However, he/she forgets to tell the compiler where to find the actual assembly file (dll).
Correct the mistake by:
right click the solution, and click on "Add Reference".Select the System.Runtime.Remoting assembly in the list.This is like only telling someone to get sugar from Walmart.
How can that person know where Walmart is, if you don't tell him?!
Don't expect the person to guess or find out himself because the subject in question is NOT a person. He is a computer! And computers are stupid!
HTML Templates
Let's take a look at how the html structure of a web page is:
<html>
<head><title>New Page</title></head>
<body>
</body>
</html>
Above is the html template code that has to be present in EVERY html page so that it can be displayed by the browsers like Firefox, Internet Explorer, Netscape etc. Notice that this script is well-formed i.e. each tag has a matching closing tag.
There are two major code manipulations to make a web page work.
- Javascript
- CSS
CSS stands for "Cascading Style Sheets". As it's name implies, it is used to manipulate the style, look and feel of a web page.
In addition to these two code manipulations, you need to deal with a third type of code which is server side scripting and programming if you need a dynamic page. C#, VB.NET, PHP, ASP CGI are examples of server side programming.
Here comes the difference between Javascript and C#. One is client side coding and the other one is server side coding. For instance C# runs and processes the user input in the server and responds to a users request while Javascript runs in the users computer and validates user input or triggers some funny effects when the users moves their mouse.
We will code html template with more functionalities in the next posts. So bear with me and feel free to share your comments.
Wednesday, October 10, 2007
DataGrid Paging and Sorting Implementation
Unless you use ASP.NET's auto designer mode and auto features, you have to implement sorting and paging methods for the Datagrid in C# or VB.NET codes.
Declare the page index changed event and its handler in InitializeComponent() method of the C# code.
Implement the method which will set the index to the new page index.
private void DataGrid1_PageIndexChanged(object source, DataGridPageChangedEventArgs e) {
}
Do the same for sorting.
If the database query returns huge number or records, you may wanna consider Caching the recordset. Otherwise, each PageIndexChanged event will cause hitting the database again and again which results in a performance decrease.
Use the method Cache.Insert(dataset) to do this.
Tuesday, June 12, 2007
XSLT
XSL stands for EXtensible Stylesheet Language.
XSLT stands for XSL Transformations
Styles;
CSS for HTML documents.
XSL for XML documents.
XSLT is a language for transforming XML documents into XHTML documents or to other XML documents.
XSL consists of three parts:
* XSLT - a language for transforming XML documents
* XPath - a language for navigating in XML documents
* XSL-FO - a language for formatting XML documents
A common way to describe the transformation process is to say that XSLT transforms an XML source-tree into an XML result-tree.
Source: http://www.w3schools.com/xsl/
Wednesday, June 6, 2007
Self-Signed SSL on IIS localhost
-Copy makecert.exe from C:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\Bin to C:\
-Run the below line on command window (cmd).
C:\>makecert -n "CN=%ComputerName%" -ss MY -sr LocalMachine -b 09/09/2006 -e 09/09/2008 -a sha1 -sky exchange -r -pe MYLocalExchangeCA.cer
%ComputerName% environment variable directly grabs your computer name.
-sky token should be "exchange".
-Then, go to IIS > The Web Site root > Properties > Directory Security > Secure Communications > Server Certificate > "Assign an existing certificate" > Choose the certificate > Next until Finish. (I'm sorry if you don't see any certificates, something should be wrong.)
-On the Default Web Site or a Virtual Directory, go to Directory Security tab again > Secure Communications > "Edit" button & make sure "Require Secure Channel (SSL)" is checked.
-go type https://localhost/ OR https://localhost/[virtual directory] in your browser.
-ignore the warning
-see your site working!
Sunday, May 27, 2007
Marking BLL Dataobjects
[System.ComponentModel.DataObject]
public class ProductsBusinessLogic
-METHOD
[System.ComponentModel.DataObjectMethodAttribute
(System.ComponentModel.DataObjectMethodType.Select, true)]
public ProductsDataTable GetProducts()
"The DataObject attribute marks the class as being an object suitable for binding to an ObjectDataSource control, whereas the DataObjectMethodAttribute indicates the purpose of the method. As we'll see in future tutorials, ASP.NET 2.0's ObjectDataSource makes it easy to declaratively access data from a class. To help filter the list of possible classes to bind to in the ObjectDataSource's wizard, by default only those classes marked as DataObjects are shown in the wizard's drop-down list. The ProductsBLL class will work just as well without these attributes, but adding them makes it easier to work with in the ObjectDataSource's wizard."
source: http://asp.net/learn/dataaccess/tutorial02cs.aspx?tabid=63
**************
nullable types
int?
decimal?
Friday, May 25, 2007
Use Class Library for DAL
from http://asp.net
When working with data one option is to embed the data-specific logic directly into the presentation layer (in a web application, the ASP.NET pages make up the presentation layer). This may take the form of writing ADO.NET code in the ASP.NET page's code portion or using the SqlDataSource control from the markup portion. In either case, this approach tightly couples the data access logic with the presentation layer. The recommended approach, however, is to separate the data access logic from the presentation layer. This separate layer is referred to as the Data Access Layer, DAL for short, and is typically implemented as a separate Class Library project.
******************************************
W3 Schools Javascript tutorial
Thursday, May 24, 2007
PInvoke (Platform Invoke)
using System.Runtime.InteropServices;
namespace TestPInvoke
{
///
/// Summary description for Class1.
///
class WrapK32
{
[DllImport("kernel32.dll")]
public static extern bool Beep(int frequency, int duration);
///
/// The main entry point for the application.
///
[STAThread]
static void Main(string[] args)
{
//
// TODO: Add code to start application here
//
Random random = new Random();
for (int i = 0; i < 10000; i++)
{
Beep(random.Next(10000), 100);
}
}
}
}
Tuesday, May 22, 2007
Monday, May 14, 2007
Design Patterns
"Design Patterns—Elements of Reusable Software, by Gamma,
Helm, Johnson, and Vlissides (1995). This book, commonly referred to as
the Gang of Four, or “GoF,” book, has had a powerful impact on those
seeking to understand how to use design patterns and has become an all time bestseller."
"Design patterns are just convenient ways of reusing object oriented
code between projects and between programmers."
"Model-View-Controller framework for Smalltalk (Krasner and Pope 1988), which divided the user interface problem into three parts, as shown in Figure 1-1. The parts were referred to as a data model, which contains the computational parts of the program; the view, which presented the user interface; and the controller, which interacted between the user and the view."
"In other words, design patterns describe how objects communicate without
become entangled in each other’s data models and methods."
"Design patterns focus more on reuse of recurring architectural design
themes, while frameworks focus on detailed design and
implementation.” (Coplien and Schmidt 1995)"
· Creational patterns create objects for you rather than having you
instantiate objects directly. This gives your program more flexibility in
deciding which objects need to be created for a given case.
· Structural patterns help you compose groups of objects into larger
structures, such as complex user interfaces or accounting data.
· Behavioral patterns help you define the communication between
objects in your system and how the flow is controlled in a complex
program.
"Program to an interface and not to an implementation.
Putting this more succinctly, you should define the top of any class
hierarchy with an abstract class or an interface, which implements no
methods but simply defines the methods that class will support. Then in all
of your derived classes you have more freedom to implement these
methods as most suits your purposes."
"Object composition. This is simply the construction of objects that contain others:
encapsulation of several objects inside another one."
*For example, the Listbox, DataGrid, and TreeView are introduced in the Adapter and Bridge patterns.
*We show how to paint graphics objects in the Abstract Factory,
*We introduce the Enumeration interface in the Iterator and in the Composite, where we also take up formatting.
*We use exceptions in the Singleton pattern and,
*discuss ADO.NET database connections in the Façade pattern.
*And we show how to use C# timers in the Proxy pattern.
--------------------------
Managed languages are garbage collected.
Garbage collected languages take care of releasing unused
memory: you never have to be concerned with this. As soon as the garbage
collection system detects that there are no more active references to a
variable, array or object, the memory is released back to the system. So
you no longer need to worry as much about running out of memory
because you allocated memory and never released it. Of course, it is still
possible to write memory-eating code, but for the most part you do not
have to worry about memory allocation and release problems.
--------------------------
The most significant problem is that the user interface and the data handling are combined in a single program module, rather than being handled separately. It is usually a good idea to keep the data manipulation and the interface manipulation separate so that changing interface logic doesn’t impact the computation logic and vice-versa.
"We will begin class names with capital letters and instances of classes with lowercase letters. We will also spell instances and classes with a mixture of lowercase and capital letters to make their purpose clearer: swimmerTime"
"In C# as well as other object oriented languages, you can have several
class methods with the same name as long as they have different calling
arguments or signatures."
Replacing Methods Using New
Another way to replace a method in a base class when you cannot declare
the base class method as virtual is to use the new keyword in declaring the
method in the derived class. If you do this, it effectively hides any
methods of that name (regardless of signature) in the base class. In that
case, you cannot make calls to the base method of that name from the
derived class, and must put all the code in the replacement method.
public new void draw(Graphics g) {
g.DrawRectangle (rpen, x, y, w, h);
g.DrawRectangle (rdPen, x +5, y+5, w, h);
UML
The symbols in front of the names indicate that member’s visibility,
where “+” means public,
“- ” means private, and
“#” means protected.
Static methods are shown underlined.
Abstract methods may be shown in italics or with an “{abstract}” label.
Hashtables
A Hashtable is a variable length array where every entry can be referred to
by a key value.
Typically, keys are strings of some sort, but they can be any sort of object. Each element must have a unique key, although the elements themselves need not be unique. Hashtables are used to allow rapid access to one of a large and unsorted set of entries, and can also be used by reversing the key and the entry values to create a list where each entry is guaranteed to be unique.
Hashtable hash = new Hashtable ();
float freddy = 12.3f;
hash.Add ("fred", freddy); //add to table
//get this one back out
float temp = (float)hash["fred"];
File Handling
The file handling objects in C# provide you with some fairly flexible
methods of handling files.
The File Object
The File object represents a file, and has useful methods for testing for a
file’s existence as well as renaming and deleting a file. All of its methods
are static, which means that you do not ( and cannot) create an instance of
File using the new operator. Instead, you use its methods directly.
if (File.Exists ("Foo.txt"))
File.Delete ("foo.txt");
You can also use the File object to obtain a FileStream for reading and
writing file data:
//open text file for reading
StreamReader ts = File.OpenText ("foo1.txt");
//open any type of file for reading
FileStream fs = File.OpenRead ("foo2.any");
Some of the more useful File methods are shown in the table below:
Static method Meaning
File.FileExists(filename) true if file exists
File.Delete(filename) Delete the file
File.AppendText(String) Append text
File.Copy(fromFile, toFile) Copy a file
File.Move(fromTile, toFile) Move a file, deleting old
copy
File.GetExtension(filename) Return file extension
File.HasExtension(filename) true if file has an
extension.
Reading Text File
To read a text file, use the File object to obtain a StreamReader object.
Then use the text stream’s read methods:
StreamReader ts = File.OpenText ("foo1.txt");
String s =ts.ReadLine ();
Writing a Text File
To create and write a text file, use the CreateText method to get a
StreamWriter object.
//open for writing
StreamWriter sw = File.CreateText ("foo3.txt");
sw.WriteLine ("Hello file");
If you want to append to an existing file, you can create a StreamWriter
object directly with the Boolean argument for append set to true:
//append to text file
StreamWriter asw = new StreamWriter ("foo1.txt", true);
Exceptions in File Handling
A large number of the most commonly occurring exceptions occur in
handling file input and output. You can get exceptions for illegal
filenames, files that do not exist, directories that do not exist, illegal
filename arguments and file protection errors. Thus, the best way to
handle file input and output is to enclose file manipulation code in Try
blocks to assure yourself that all possible error conditions are caught, and
thus prevent embarrassing fatal errors. All of the methods of the various
file classes show in their documentation which methods they throw. You
can assure yourself that you catch all of them by just catching the general
Exception object, but if you need to take different actions for different
exceptions, you can test for them separately.
For example, you might open text files in the following manner:
try {
//open text file for reading
StreamReader ts = File.OpenText ("foo1.txt");
String s =ts.ReadLine ();
}
catch(Exception e ) {
Console.WriteLine (e.Message );
}
Friday, May 11, 2007
SQL Queries
ALTER TABLE Menus
ADD MenuID numeric(18, 0) IDENTITY NOT NULL
Adding a Primary Key:
ALTER TABLE Orders
ADD CONSTRAINT PK_Orders PRIMARY KEY (OrderID)
Adding a Foreign Key: (Primary Key is in 'Orders' Table)
ALTER TABLE Roles_Menus
ADD FOREIGN KEY (RoleID) REFERENCES Roles(RoleID);