Monday, January 28, 2013

Factory Design Pattern

Define an interface for creating an object, but let sub-classes decide which class to instantiate. Factory Method lets a class defer instantiation to sub-classes.
1. Its a creational pattern.
2. As its name say its to construct some thing.



Problems those solved by this pattern
1. So much of new keywords.
2. Client aware always about all concrete classes.
3. If we need to add / remove a concrete class then client should know about it, code updation required in client code.

Switch(invoiceType)
{
Case : 1
{
objInvoice = new invoiceWithHeader();
}
Case : 2
{
objInvoice = new invoiceWithFooter();
}
:
:
}

Benefits:
1. Reduces no. of new keywords.
2. Client just know about Factory and interface(that is implemented by all concrete classes) only.
3. No changes required at client whenever need to add a new concrete class or need to remove a concrete class.

Conclusion:

When you design an application just think if you really need it a factory to create objects. Maybe using it will bring unnecessary complexity in your application. If you have many objects of the same base type and you manipulate them mostly casted to abstract types, then you need a factory.


Code:
namespace FactoryPatternConsole

{
    //Invoice interface
    public interface IInvoice
    {
        void PrintInvoice();
    }
}

namespace FactoryPatternConsole
{   //Invoice factory
    class InvoiceFactory
    {
        public IInvoice GetInvoice(int invoiceType)
        {
            switch (invoiceType)
            {
                case 1:
                    return new clsInvoiceWithHeader();
                case 2 :
                    return new clsInvoiceWithFooter();
                default :
                    return null;
            }
        }
    }
}

namespace FactoryPatternConsole
{
    //Client
    class Program
    {
        static void Main(string[] args)
        {
            InvoiceFactory objFactory = new InvoiceFactory();
            //Here client just need to pass invoice type code to get required invoice
            IInvoice objInvoice = objFactory.GetInvoice(2);
            objInvoice.PrintInvoice();
            Console.ReadLine();
        }
    }
}

namespace FactoryPatternConsole
{
    //Concrete class invoice with header
    class clsInvoiceWithHeader : IInvoice
    {
        public void PrintInvoice()
        {
            Console.WriteLine("This is an invoice with header.");
        }
    }
}


namespace FactoryPatternConsole
{
    //Concrete class invoice with footer
    class clsInvoiceWithFooter : IInvoice
    {
        public void PrintInvoice()
        {
            Console.WriteLine("This is an invoice with footer.");
        }
    }
}

Benefits

  • Decouples object creation logic
  • Centralizes creation (easy to change later)
  • Supports adding new types easily


🧠 Real Uses in .NET Core

  1. Dependency Injection Container (built-in factory)

    • When you call builder.Services.AddTransient<IMyService, MyService>(),
      the DI container acts as a factory, creating MyService instances as needed.

  2. LoggerFactory

    ILoggerFactory loggerFactory = LoggerFactory.Create(builder => {     builder.AddConsole();

    });

    var logger = loggerFactory.CreateLogger<Program>();

  3. DbContextFactory (EF Core 5+)

    var factory = new PooledDbContextFactory<AppDbContext>();

    using var context = factory.CreateDbContext();

Tuesday, January 22, 2013

Session State Management Strategies

There are two types of session state management strategy
  1. In Process
  2. out of process
In process – Stores session data on the same server.
Out of process – Stores data on other server like sql server, state server.


1. In process
Its best to choose when requests to come to same physical server rather than split to multiple IIS machines.
Its very fast and easy to implement because it runs in process.
Its wrong choice if your session state data is expensive to rebuild because when ever ASP.Net worker process or IIS restarts data flushes and rebuilds.
In case of multiple server its unsuitable until you implement some form of servers affinity like ‘network load balancing’.
2. Out of process
A. State Server – Its relies on a windows service, which remains stopped by default. You can start it from administrative tools / services / ASP.Net state service.
You can run it on same web server or can have a different ‘state server’ associated with your web server. It runs separately from IIS.
Beneficial is that you can restart IIS your session state data will not loss.
It require plenty of RAM because it runs separately from IIS.
Losses session state data on restart of server.
B. Sql Server - Stores data in table.
Its more reliable and flexible option than other.
You can restart server without losing data, you can even backup session state data.
Its also most expensive to build and maintain.

Saturday, January 12, 2013

IEnumerable and IEnumerator


IEnumerable and IEnumerator are used to iterate over non generic collection.
IEnumerable exposes an enumerator.

IEnumerator has a property 'Current' that returns value of list item at current cursor position.
It has 2 methods
MoveNext() - Moves cursor to next item.
Reset() -  Reset cursor and send it to first item.

You can type cast a collection to IEnumerable or IEnumerator like list, array, array list.

List<int> myCol = List<int>();
mycol.add(5);
mycol.add(15);
mycol.add(20);

IEnumerable<int> ienmb = (IEnumerable<int>) myCol ;
IEnumerator<int> ienmr = (IEnumerator<int>) myCol ;

Now you can use these objects to iterate like this
Itration of IEnumerable
foreach(int i in ienmb) console.writeline(i);

Itration of IEnumerator
while(ienmr.MoveNext()) Console.Writeline(ienmr.Current.tostring());

You can also get enumrator object from enumrable object
IEnumerator<int> IEnumrObject = ienmb.GetEnumerator();

Differance b\w IEnumerable and IEnumerator
IEnumerable actually uses IEnumrator internally.
IEnumerator remember it's state, means it knows where is it's cursor position currently.
Syntactically IEnumerable easy to use.
If there is not any requirement that your collection object know about it's state than you can use IEnumerable.

Tuesday, January 1, 2013

SDLC


SDLC phases
1. Preliminary Analysis: The objective of phase 1 is to conduct a preliminary analysis, propose alternative solutions, describe costs and benefits and submit a preliminary plan with recommendations.
The 1st stage of SDLC is the investigation phase (Feasibility study). During this stage, business opportunities and problems are identified, and information technology solutions are discussed. Multiple alternative projects may be suggested and their feasibility analyzed. Operational feasibility is assessed, and it is determined whether or not the project fits with the current business environment, and to what degree it addresses business objectives. In addition, an economic feasibility investigation is conducted to judge the costs and benefits of the project. Technical feasibility must also be analyzed to determine if the available hardware and software resources are sufficient to meet expected specifications. A legal feasibility study is important to discover any potential legal ramification. The results of the feasibility study can then be compiled into a report, along with preliminary specifications. When the investigation stage ends, a decision whether or not to move forward with the project should be made. If it is decided to move ahead, a proposal should have been produced that outlines the general specifications of the project.
Conduct the preliminary analysis: in this step, you need to find out the organization's objectives and the nature and scope of the problem under study. Even if a problem refers only to a small segment of the organization itself then you need to find out what the objectives of the organization itself are. Then you need to see how the problem being studied fits in with them.
Propose alternative solutions: In digging into the organization's objectives and specific problems, you may have already covered some solutions. Alternate proposals may come from interviewing employees, clients , suppliers, and/or consultants. You can also study what competitors are doing. With this data, you will have three choices: leave the system as is, improve it, or develop a new system.
Goal of this phase is to prepare BRS (Business Resource specification) or URS (User Resource specification) or CRS (Customer Resource specification). It is good practice if BRS is prepared by company owner that describes what is his business, so analyst can decide and suggest appropriate solution for the business.
Describe the costs and benefits.

2. Systems analysis, requirements definition:
Defines project goals into defined functions and operation of the intended application. Analyzes end-user information needs.
Goal of this phase is to prepare SRS (System Requirement Specification).

3. Systems design:
Describes desired features and operations in detail, including screen layouts, business rules, process diagrams, pseudo-code and other documentation.
Goal of this phase is to prepare HLD (High Level Document) / Architectural Design and LLD (Low Level Design).

4. Development: The real code is written here. Goal of this phase is to prepare code for divided modules and unit testing (N unit).

5. Integration and testing: Brings all the pieces together into a special testing environment, then checks for errors, bugs and interoperability. Goal of this phase is to integrate different prepared modules from coding phase and testing of integrated module (Product).

6. Acceptance, installation, deployment: The final stage of initial development, where the software is put into production and runs actual business.

7. Maintenance: What happens during the rest of the software's life: changes, correction, additions, moves to a different computing platform and more. This is often the longest of the stages.


Waterfall Model


V & V - Validation and Varification

Friday, November 9, 2012

Some new features of .net Framework 4.0

1. Named parameters - you can pass parameter to any function with name in any sequence.
Ex. Private void Shape(string Name, int Height, int Width)
you can call the function like
Shape(Height : 10, Name : "Rectangle", Width : 20)

2. Optional parameters - You just need to assign value to parameter at definition, then at the time of calling that parameter will be optional.
Ex. Private void Shape(string Name, int Height, int Width = 50)
you can call the function like
Shape(Height : 10, Name : "Rectangle")

3. Dynamic keyword - It represent an object and it's operations resolved at run time.
Ex. private void Shape(dynamic A)
{
A.CircleShap();
}
You can pass any type of object here that have a function CircleShap().

4. Co-Varience and Contravariance - If you create a delegate and assign a method to delegate then it required that signature of method and delegate should be match. Co-Varience and Contravariance changes this need little bit.
Covariance - It allows a more derived return type method to be assign than delegate’s return type.
Contravariance - it allows less derived parameters type method to be assign than delegate’s parameter’s type.

5. Generate from usage - If you write code for usage of any object then you can generate the object by right clicking and clicking on generate.
Ex.
[TestMethod]
public void TransferFundsTest()
{
Account source = new Account() {Balance = 300.0};
Account destination = new Account() {Balance = 100.0};
var xferService = new XferService();

xferService.Transfer(source, destination, 50.0);

Assert.AreEqual(250, source.Balance);
Assert.AreEqual(150, destination.Balance);
}
Right-click on the one of the "Account" instances and select "Generate" and then "Class". Visual Studio generates a simple Account class with no members. Now right-click on one of the "Balance" references and select "Generate" and then "Property". Our Account class now has a simple get/set Balance field. Repeat these same steps with XferService and the Transfer method. Without too much work, we’ve got the following code generated from our unit tests:
class Account
{
public double Balance { get; set; }
}

class XferService
{
internal void Transfer(Account source, Account destination, double p)
{
throw new NotImplementedException();
}
}

6. Reference highlighting - If you select any word in IDE window all same words in window become selected. Now you can navigate to those selected words by clicking ctrl+shift+down arrow and ctrl+shift+ up arrow.

Wednesday, September 26, 2012

SQL Injection

What is Sql injection
A SQL Injection attack is a form of attack that comes from user input that has not been checked to see that it is valid. The objective is to fool the database system into running malicious code that will reveal sensitive information.


Two types of Sql injection attacks -
First order attack - Attacker harm the DB immediately, when attacker passes some malicious query via any web application to DB.
Example 1 -
User id ->   hi' or 1=1;--
Password ->  hello' or 1=1;--
This will enter the user in.
Example 2 - If web application displaying some data in three columns with some filter criteria. If attacker type below given string in criteria then it will show name, type and id of sysobject table with application data.
' UNION SELECT name, type, id FROM sysobjects;--
Now attacker can type below given string, it will show columns and their lenths of a perticular table of given id.
' UNION SELECT name, '', length FROM syscolumns WHERE id = 1845581613;--
Now attacker have enough information to destory your DB. Now below given string can be passed to criteria, it will provide admin user details.
' UNION SELECT UserName, Password, IsAdmin FROM Users;--

Thursday, August 16, 2012

Trigger in Sql

A trigger is a special kind of stored procedure, that is executed automatically when a specified event fired on database server.

There are three types of triggers DML trigger, DDL trigger and Logon trigger.
1. DML trigger - A DML trigger can be created on a table or view, its executes when a user tries to update data through DML operations (insert / update / delete), trigger fires regardless of whether or not data is updated.
DML triggers have two types of nature 'After' and 'Instead of'
After - Trigger with after fires after execution of specified event for that triger is created. We use keyword FOR or AFTER for it, both are same.
Instead Of - Trigger with instead of option fires instead of executing specified event. Trigger of this nature overrides specified event or triggering statement with statements defined in body of trigger.
Instead of option can't be used with DDL or Logon triggers.
Syntax - 

CREATE TRIGGER trigger_name
ON { table | view }
{ FOR | AFTER | INSTEAD OF }
{ [ INSERT ] [ , ] [ UPDATE ] [ , ] [ DELETE ] }
AS { sql_statement }

Ex.
This trigger enforces a business rule when user try to insert an employee record in employee table, that protect the table from inserting bonus out of the range that company has specified.

create trigger trgEmpSalary
on tbl_employee
for Insert
AS
begin
if exists (select * from tbl_employee where bonus between 1000 and 10000)
begin
raiserror('Bonus range in company is 1000 to 10000',10,1)
rollback transaction
end
end

Monday, August 13, 2012

LLD (Low level design document)

At start of LLD (Low level design document) mention customer name, project name, list of authors and name and signature of the person who approve the document. After that index and then according to below content

Revision History - Should be a table with fields version number, date of release, author, history of changes and approver.        
1.      Introduction - General description.
1.1              Brief system description - Brief description of system.                          
1.2              Glossary - Vocabulary list, describe terms used in document.
1.3              References - Mention references, given in document if any.
2.      Low Level Design
2.1              Physical Database Design - Describe database structure, with all objects, relations etc.
2.2              Database Engineering - Include data access methods, optimization techniques, query
   construction techniques.
2.3              User Interface Design - Describe UI of project.
2.4              Data Inflows & Outflows - Create end to end data flow diagram from login to last
   operations.

Friday, August 3, 2012

Stored Procedure in Sql

A stored procedure is a group of Transact-Sql statement compiled into a single execution plan. Its faster than ordinary sql statements because they will undergone in a sequence of steps to execute.
By default SPs stored in DB in compiled form, but if we need to create SP that compile each time it runs than we can add 'with recompile' at the time of creation.

Simple syntax -
create procedure procedureName
[@param1 datatype, @param2 datatype, [@param3 datatype out,]...]
[with RECOMPILE]
as
Begin
--Sql statements
End

A procedure can take multiple parameters, and can return -
1. Data like single int or string value.
2. Can return a local or global cursor.
3. Can return a result set for all select statement(and/or stored procedure) contained in SP.

Wednesday, August 1, 2012

Cursor in Sql

A cursor is a database object, having set of rows with a pointer that identify current row. So one can manipulate data row by row basis. Its like recordset in .net.

A cursor can be declared as forward only or scroll. It can be declared as read only.
A Static cursor has a separate copy of data in tempdb and serve all request from there so changes made to DB does not affect result of cursor, It does not allow modifications.
A Local cursor has scope in area where it is declared like in trigger or in stored procedure, while a Global cursor name have scope throughout the connection.
A Fast_forward cursor specifies forward_only, read_only cursor with performance optimization.

Ex.
declare @emp varchar(10), @sal money
declare myCursor cursor for
select empname, salary from tbl_employee

open mycursor
fetch next from mycursor into @emp, @sal
print @emp + ' getting salary ' + cast(@sal as varchar(10))
while @@FETCH_STATUS = 0
begin
fetch next from mycursor into @emp,@sal
print @emp + ' getting salary ' + cast(@sal as varchar(10))
end
close mycursor
deallocate mycursor

Using PIVOT and UNPIVOT in sql

PIVOT rotates a table-valued expression by turning the unique values from one column in the expression into multiple columns in the output, and performs aggregations where they are required on any remaining column values that are wanted in the final output. UNPIVOT performs the opposite operation to PIVOT by rotating columns of a table-valued expression into column values.

Ex. Table Pivot_Test has data given below

Sales Person
Product
Sales Amount
Bob
Pickles
100
Sue
Oranges
50
Bob
Pickles
25
Bob
Oranges
300
Sue
Oranges
500
Due
Mangoes
800



SELECT SalesPerson, [Oranges] AS Oranges, [Pickles] AS Pickles
FROM
(SELECT SalesPerson, Product, SalesAmount
FROM Pivot_Test ) ps
PIVOT
(
SUM (SalesAmount)
FOR Product IN
( [Oranges], [Pickles])
) AS pvt


Output
Sales Person
Oranges
Pickles
Bob
300
125
Due
NULL
NULL
Sue
550
NULL


So how does this work?
There are three pieces that need to be understood in order to construct the query.
1. The SELECT statement
    SELECT SalesPerson, [Oranges] AS Oranges, [Pickles] AS Pickles
    This portion of the query selects the three columns for the final result set (SalesPerson, Oranges,      Pickles)
2. The query that pulls the raw data to be prepared
    (SELECT SalesPerson, Product, SalesAmount FROM Pivot_Test) ps
    This query pulls all the rows of data that we need to create the cross-tab results.  The (ps) after the                  query is creating a temporary table of the results that can then be used to satisfy the query for step 1.
3. The PIVOT expression
    PIVOT (SUM (SalesAmount) FOR Product IN ( [Oranges], [Pickles]) ) AS pvt
    This query does the actual summarization and puts the results into a temporary table called pvt

Another key thing to notice in here is the use of the square brackets [ ] around the column names in both the SELECT in part (1) and the IN in part (3).  These are key, because the pivot operation is treating the values in these columns as column names and this is how the breaking and grouping is done to display the data.

Tuesday, July 31, 2012

Sql UDFs

A User defined function is a transact-sql or CLR routine that accepts parameters, performs some action and returns result of action as a value, returned value can either be a scalar(single) value or a table.
When can be used
1. Replacing stored procedure.
2. To parameterize a view.
3. In T-sql like select statement.
4. Inside another UDF.
5. In applications calling the function.

Types of UDFs
1. Scalar functions
2. Inline table-valued functions
3. Multi-statement table-valued functions

1. Scalar function - Returns single value.
Ex.
create function ProjectEstimation(@developmentDays int, @testingDays int)
returns int
as
begin
declare @totalDays int;
select @totalDays = @developmentDays + @testingDays;
return @totalDays
end
--calling 
select ProjectEstimation(50, 26)

2. Inline table-valued function - Returns a table as result, no need to declare table structure.
Ex.
create function EmpWiseCityCollection(@emp varchar(20))
returns table as
return
(
select city, sum(Collection) [Collection] from tbl_employee where empName = @emp group by city
);
--calling 
select * from EmpWiseCityCollection('mark')

3. Multi-statement table-valued functions - Returns a table as result, need to declare table structure.
Ex.
CREATE FUNCTION SalesByPerson(@sales_ID int)
RETURNS @SalesData TABLE
(
[CustomerID] int,
[SalesAmount] int,
[SalesDate] date
)
AS
BEGIN
INSERT INTO @SalesData
SELECT Sales.CustomerID, Sales.SalesAmount, Sales.SalesDate from Sales
Where Sales.Sales_ID = @sales_ID
RETURN
END
--calling select * from  SalesByPerson (1002)


Why use multi-statement table-valued functions instead of inline table-valued functions?
1) Generally, we use multi-statement table-valued functions when we need to perform further operations (for example, inserts, updates, or deletes) on the contents of the table variable before returning a result set.
2) We would also use them if we need to perform more complex logic or additional processing on the input parameters of the function before invoking the query to populate the table variable.

Friday, July 13, 2012

EXCEPT and INTERSECT

Except - It returns data from left side query expression that is not in the data by right side query expression.
Ex.
A - data that is not in right side query result
B - data that is not in left side query result
C - data that is common in both results

Except returns A.
 

Intersect
- It returns data that is common in left and right side query expressions.
Intersect returns C.

Syntax -
{ <query_specification> | ( <query_expression> ) } 
{ EXCEPT | INTERSECT }
{ <query_specification> | ( <query_expression> ) }

Friday, June 8, 2012

Indexes in Sql server

Indexes are database objects can be created on one or more columns of a table(Max 16 columns).
Database Index is like book index that make easy to find out specific record. Creating index on table increase performance to fetch data but add some overhead for DML(Insert, Update, Delete) operations.
Clustered Index - When we create primary key database read the column values and creates Clustered Index for it. It can be only one for one table.



Select * from Customer where customerid = 103
Select * from Customer where customerid = 100

Without indexing these queries will return the result after 100+ comparisons.

With indexing, execution of first query will return value at first comparison. Execution of second query will return the value at the third comparison. See below example for second query:

For query no. 2
Compare 100 vs 103 : Move to left node
Compare 100 vs 101 : Move to left node
Compare 100 vs 100 : Matched, return the record

Non Clustered index - Its useful to create on columns those have repetitive values, like those have thousands records but unique are 10-20.

Monday, May 28, 2012

C# Vs VB.net

1. 'Using' keyword of C# is used to release unused resources of an object.
Font myFont = new Font("Times New Roman", 8.0f);
            using (myFont) // not recommended
            {
                // use myFont
            }
After execution of inside statement of the braces resources used by myFont will be released. Class where you use 'Using' must to implement IDisposable interface.

2. C# is case sensitive.
3. Optional parameters to functions is not supported in C#.
4. C# doesn't have 'with' keyword that used to manipulate properties of an object in a single block.
With myObject
.Height = 20
.ForeColor = System.Drawing.Color.Green
.Text = "Hello..."
End With

5. Unstructured error handling not supported in C#. (On Error GOTO) is not supported in C#.
6. There is a concept of function Hiding in c# its called Hiding and in VB.Net its called Shadowing. We can have same name function in derived class that exist in base class that hides existence of that base class function in derived class.  In c# we mark it 'New' and in VB.Net we mark it 'Shadow'. Difference is that in C#, both the functions must have same signature while vb.net allow to change signature function.
7. In VB.Net we can call function by passing parameter with extra bracket that is not support by C#.
Dim y As Integer = 8
Dim z As Integer
z = Add(y) //This will set both Y and Z to 7.
z = Add((y)) //This will set Z to 7 but Value of Y will not be change, as we have included extra parentheses while calling.
             
The Subtract function:
Public Function Subtract(ByRef x As Integer) As Integer
x = x - 1
Return x
End Function

Saturday, May 26, 2012

Value and Reference types

All the types are derived from System.Object base type.

Value type - contain actual value on its memory location. Its allocated to stack.
Reference type - contains a new memory location address on its memory location. Its allocated to heap.
Changing value of a reference type can effect some other objects those are referring that reference type.

Value types ex. - All numeric types, Datetime, Boolean, Char, Structure, Enumeration.
Reference types ex. - String, Array, Delegate, Class.

* Structure and Enumeration are value types even they contain reference type members.
* String, Array are reference types even they contain value types.

Types of JIT compiler

Pre JIT - Compiles whole code in a single cycle.

Econo JIT - Compiles code part by part when required. It means compiles methods those called at runtime, and then remove those compiled code when not required. That means called code compiles, serves and then frees.

Normal JIT - Compiles code part by part as Econo but only once when any code part called first time, then it put that code to cache and if required later, then serves from cache that part.

Thursday, April 26, 2012

Page Life Cycle Satges

When an user requests for a page from browser then ASP.Net serves the page to the client/user during this service page passes via some stages this cycle of page processing is called Asp.Net Page Life Cycle.
All stages of page life cycle performed for partial page processing request also.(Like to process update panel.)

1. Page request - Page request raised before page life cycle started. Here Asp.net determines that a cached page can be served or need to compile and parse the page. If cached page not served then page life cycle is started.

2. Start - At this stage Request and response properties of page are set. Page determines that is it a postback then Ispostback property of page is set, also set UIculture property of page at this stage.

3. Initialization - At this stage controls of page are available, Unique Id property is set here for all controls of page. Master page and themes also applied to the page if applicable.

4. Load - At this stage properties of controls are initialize by values picked from View State and Control state, if page is postback.

5. Postback event handling - If page is postback then event handlers of controls are called. After that Validate method of all validation controls are called and IsValid property of validation controls and page is set.(An exception to this sequence is) Event handler that caused validation called after validation.

6. Render - At this stage View state is saved. Page calls Render method of all controls, with providing TextWriter so that out put is written to OutputStream object of Response property of page.

7. Unload - This stage occurred when page is fully rendered and sent to client. Response and request properties and other properties of page are unloaded and dispose is performed for all.

Thursday, April 19, 2012

Silverlight For Beginners

What is Silverlight?

Silverlight applications are based on XAML, so first learn something about XAML.
 
1. XAML(eXtensible Application Markup Language) is a declarative language to create UI, such as controls, shapes, text and other contents presented on the screen.
Its like HTML but more powerful, uses elements and attributes.

2. XAML is just a procedural code but easier.
<Button Width="60" Height="30">Click Me</Button>
In code behind we can do this like 
Button myButton = new Button();
myButton.Width = 60;
myButton.Height = 30;
myButton.Content = "Click Me";
LayoutRoot.Children.Add(myButton);

3. Attributes and Elements - Fill is an attribute assigned a color and Rectangle is an element.
<Rectangle Fill="Red">
OR
<Rectangle>
  <Rectangle.Fill>
    <SolidColorBrush Color="Red" />
  </Rectangle.Fill>  
</Rectangle>

Wednesday, April 4, 2012

Model-View-Controller (MVC)

The Model-View-Controller (MVC) pattern separates the modeling of the domain, the presentation, and the actions based on user input into three separate classes.
MVC is not just a design pattern while its an architecture because its responsible for whole application not a part of application.

How is it beneficial?
1. User interface may change frequently, and if user interface and business logic combined in single object then every time you need to modify an object that contains business logic, this can introduce errors and require retesting of all business logic every time user interface changes.
2. In some cases application displays same data in different ways at same time, like a analyst may like spreadsheet view while management prefer charts(bar/pie/column) view, and If user updates one view then application must update all other views automatically.
3. UI design requires different skill set than developing business logic, rarely a person have both skill set, so its required to separate these to parts.
4. UI code is more device dependent than business logic. If you need to make a application mobile enabled then it require much UI design changes while business logic has no effects, a clean separation of these two parts accelerates the migration and minimize the risk of introducing errors in business logic.
5. Creating automated testing interfaces for UI is more difficult than business logic. So reducing the code that is tied with UI enhances the testability of UI (and application).  

Wednesday, March 14, 2012

Understanding XML Schema - XSD

XML Schema - An XML schema describes the structure of an XML document.
XML schema language also referred as XML schema definition(XSD).
XSD is XML based alternative of DTD(Data Type Definition).

Basics
1. Defines elements of document.
2. Defines attributes of document.
3. Defines which elements are child elements.
4. Defines no. of child elements and order of child elements.
5. Defines an element is empty or can have text.
6. Defines data types for elements and attributes.
7. Defines Default and fixed values for elements and attributes.
8. W3C recommendation.

XSDs are successor of DTDs because
1. XSDs are richer, more powerful and extensible in future.
2. Written in XML.
3. Support data types.
4. Support namespaces.

Why XSDs are recommended
1. XML format - Platform independent.
2. Extensible - Own data types can be created based on standard data types, other schemas can be referenced in a schema, a document can have references of multiple schemas.
3. Support data types - Can be define allowable contents, makes data type conversion easy.
4. Secure data communication - Both ends having data structure.

Example

Simple XML document

<?xml version="1.0"?>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>

Friday, March 2, 2012

Understanding XPath

XPath is a language to find information in an XML document.



* XPath is a syntax for defining parts of an XML document
* XPath uses path expressions to navigate in XML documents
* XPath contains a library of standard functions
* XPath is a major element in XSLT
* XPath is a W3C recommendation

Understanding XSLT

XSLT(eXtensible style sheet language transformations) is a language to transform a XML document into XHTML document or other XML document.

CSS = Style sheet for HTML document
XSL = Style sheet for XML document

When we open XML document in any browser it opens as it is in text form. Because XML has user defined tags (not predefined) and browser don't know how to display that.
We can create XSLT for any XML document so with the help of XSLT browser understand how to display given XML.

* XSLT stands for XSL Transformations
* XSLT is the most important part of XSL
* XSLT transforms an XML document into another XML document
* XSLT uses XPath to navigate in XML documents
* XSLT is a W3C Recommendation

Thursday, March 1, 2012

Understanding XML

XML is hardware and software independent tool to store and transport data.
XML stands for eXtensible markup language.
XML is a W3c consortium recommendation.
XML is a markup language much like HTML.
XML designed to store and carry data not to display data.
XML designed to be self-descriptive.
XML tags are not predefined, you must define your own tags.

Example
<?xml version="1.0" encoding="ISO-8859-1"?>
<note>
<to>Lucky</to>
<from>Mukesh</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>

FACTS about XML

1. XML is designed to store and transport data and HTML designed for displaying data.
2. XML doesn't do anything its just designed for structure, store and transport data.

Sunday, February 26, 2012

Override and New keywords

Abstract or virtual members(method/events/indexer) of base class can be redefined in derived class, this is called overriding. An Abstract member is implicitly Virtual.

The method you are overriding must have same signature with overridden method. An overridden method of base class also can be overridden in derived class, because override shows that method exist in some upper class in inheritance hierarchy.

You can't use static, new or virtual to modify method with override.

Reasons
-
With Static - Static makes a method common for all instances, static method is not an instance method so it can't take part in inheritance.

With New - You can have same signature method in derived class compare to base class method with keyword Override or New. Override makes sense that you are redefining a base class method in derived class. New makes sense that it is a fresh new method not having any connection with base class method, it hides existence of base class method in derive class it called Hiding (or Shadowing in VB.Net), Use of New is not recommended because it breaks rules of OOP.

With Virtual - Because we can override a method that is already Virtual.
Some examples to understand it -

Below examples showing Runtime/Dynamic polymorphism.

How runtime calls methods in these scenarios?

First CLR checks runtime type of object, then starts searching last derived form of called method from variable type(compile time type) class to the runtime type class, and calls the last derived form of the called method in between this path.  

Thursday, February 16, 2012

New Features in Sql Server 2008

New In Sql Server for SSIS
1. Introduced VSTA - Introduced Visual Studio Tools for Applications(VSTA) for writing 'Script tasks' and 'Script components'. Earlier VSA(Visual Studio for Applications) was used in Sql 2005 for writing Script tasks and components, by using VB Script as language. In Sql 2008 now its become more functional and secure, now C# and Vb.net can also be used as scripting language. All main features of visual studio added in VSTA like intellisence, build, debug, .net assemblies references, COM components, adding web services etc..  You can create Script task by Open a new or existing Integration Services package in Business Intelligence Development Studio (BIDS). Read article with details on http://www.sql-server-performance.com/2009/ssis-new-features-in-sql-server-2008-part5/ and http://msdn.microsoft.com/en-us/library/ms135952.aspx



Thursday, February 9, 2012

New features in Visual Studio 2008

1.  Multi targeting support - We can develope, build and debug 2.0, 3.0 and 3.5 applications.
2.  Linq support - Efficient way to work with queries. Benefits compile time error checking and step by step query debugging.


Monday, January 30, 2012

Anonymous Functions

An anonymous function is an "inline" statement or expression that can be used wherever a delegate type is expected. You can use it to initialize a named delegate or pass it instead of a named delegate type as a method parameter.

In C# 1.0, you created an instance of a delegate by explicitly initializing it with a method that was defined elsewhere in the code. C# 2.0 introduced the concept of anonymous methods as a way to write unnamed inline statement blocks that can be executed in a delegate invocation. C# 3.0 introduced lambda expressions, which are similar in concept to anonymous methods but more expressive and concise. These two features are known collectively as anonymous functions. In general, applications that target version 3.5 and later of the .NET Framework should use lambda expressions.
The following example demonstrates the evolution of delegate creation from C# 1.0 to C# 3.0:

class Test
{
    delegate void TestDelegate(string s);
    static void M(string s)
    {
        Console.WriteLine(s);
    }

    static void Main(string[] args)
    {
        // Original delegate syntax required 
        // initialization with a named method.
        TestDelegate testDelA = new TestDelegate(M);

        // C# 2.0: A delegate can be initialized with
        // inline code, called an "anonymous method." This
        // method takes a string as an input parameter.
        TestDelegate testDelB = delegate(string s) { Console.WriteLine(s); };

        // C# 3.0. A delegate can be initialized with
        // a lambda expression. The lambda also takes a string
        // as an input parameter (x). The type of x is inferred by the compiler.
        TestDelegate testDelC = (x) => { Console.WriteLine(x); };

        // Invoke the delegates.
        testDelA("Hello. My name is M and I write lines.");
        testDelB("That's nothing. I'm anonymous and ");
        testDelC("I'm a famous author.");

        // Keep console window open in debug mode.
        Console.WriteLine("Press any key to exit.");
        Console.ReadKey();
    }
}
/* Output:
    Hello. My name is M and I write lines.
    That's nothing. I'm anonymous and
    I'm a famous author.
    Press any key to exit.
 */

Monday, January 23, 2012

Structure

A Struct is a value type typically used to encapsulate small group of related variables.
A structure can have fields, properties, constants, operators, events, methods, constructors, indexers, nested types etc.
A struct can't have parameter less constructor, because CLR initializes all types of struct to their default values by own, so having explicit parameter less constructor will be overhead on performance, and CLR also not guarantees that the constructor will be called.         
Ex.
public struct Book
{
public string author;
public string name;
public string publisher;
public decimal price;
}
Structure Vs Class
A struct is like a class but having some differences -
A. Class is reference type and struct is value type.
B. Class created on heap while struct created on stack.
C. Class can be inherited but struct can't be inherited, A struct can't be a base of any class or struct, because they are sealed by default.
D. Using struct is recommended if having small group of members, because any where we
pass struct a copy of struct passes, so it will be performance overhead if having big size. While class with big group of members is efficient because it's reference passes.
public struct strEx
{
public int x;
}
public class clsEx
{
public int x;
}
public class clsMain
{
public static void main()
{
strEx ObjStr = new strEx();
clsEx ObjCls = new clsEx();

ObjStr.x = 225;
ObjCls.x = 225;

AssignStr(ObjStr); //A copy of object is passing to method
AssignCls(ObjCls); //Refrence of object is passing to method

Console.WriteLine("Value of x of struct is :{0}", ObjStr.x);
Console.WriteLine("Value of x of class is :{0}", ObjCls.x);
}

public static void AssignCls(clsEx cls)
{
cls.x = 500;
}
public static void AssignStr(strEx str)
{
str.x = 500;
}
}
Output -
Value of x of struct is  225
Value of x of class is 500

Sunday, January 22, 2012

Indexers

Indexers allows client code to access a collection item of a class (or interface or structure) by
using object of class as an array.
Syntax -
public int this[int x]  
{
       //  get and set accessors
}

Terminology -
A. Indexers defined by using this keyword, denotes current instance.
B. Indexer must have a parameter of any data type, else compiler will through the error.
C. Object of class behave like an array for indexer.
D. Indexer can't be static it always be the instance member.
E. Indexer can be overloaded, you can have multiple indexers with different signatures.
F. Provides syntactical benefit.
G. Indexers can be used with structures same as used with classes.
H. Indexers declared in an interface enforces to implement same signature(parameter and return type, not access modifier) indexers in Classes those implement that interface.
I. Syntax of indexer in an interface, its not have access modifier because they are public by default and do not have body of accessors because interface only declares members not defines.
int this[int index]
    {
        get;
        set;
    }


Example -
class Indexers
{
        public Indexers()
        { }

//Temprature taken at different time
float[] Temp = new float[]{56.2F, 56.7F, 56.5F, 56.9F, 58.8F,
61.3F, 65.9F, 62.1F, 59.2F, 57.5F};
public float this[int index]
{
get
{
        return Temp[index];
}
set
{
        Temp[index] = value;
}
}

//Weekdays
string[] days = new string[] { "Sun", "Mon", "Tues", "Wed", "Thurs", "Fri", "Sat" };
private string Getday(string gday)
{
    foreach (string tDay in days)
    {
        if (tDay == gday) return tDay;
    }
    return "Invalid day";
}
public string this[string day] //Overloading of indexers
{
    get
    {
        return Getday(day);
    }
}
}
public class CallIndexers
{
    public static void Main()
    {
        Indexers ObjIndexers = new Indexers();
        Console.WriteLine(ObjIndexers["Wed"]); //Output : Wed

        Console.WriteLine(ObjIndexers[2]); //Output : 56.5F
        ObjIndexers[5] = 60.02F;
        Console.WriteLine(ObjIndexers[5]); //Output : 60.02F
    }
}

Tuesday, January 10, 2012

Boxing and Unboxing

Boxing and Unboxing is act like a bridge between value types and reference type.


Boxing - Storing value type to System.Object type or any interface type that implimented by this value type is called Boxing.
Boxing is implicit, Explicit Boxing also possible but its never required.
Compiler copies value of value type variable to object type and stores it in managed heap by GC.

Unboxing - Copying object type value or an interface type value that this value type implements to a value type variable is called UnBoxing. Unboxing is explicit.

Unboxing consists two steps -
I Checking that object containing value is boxed value of given variable type.
II Copying Object containg value to value type variable.



int i = 123;
object o = i; //Boxing
int j = (int)o; //Unboxing


Wednesday, November 16, 2011

Object oriented programming (OOP)

Namespace
A name space is a logical grouping of classes and other data structures.
Ex. Animals
namespace animals
{
}

Class
A class is definition of a real life object.
Ex. Dogs
class dogs
{
public int AgeOfDog = 30;

public virtual void bark()
{
Console.WriteLine("Dogs bark.");
}
}

Object
An object is an instance of a class.
Ex. Jimmy
dogs jimmy = new dogs();

Access modifiers
Private A member that can be accessible only in the class where it declared.
Protected A member that can be accessible in same class and derived class.
Public A member that can be accessible any where, normally by using object of the class.
Internal A member that can be accessible inside the assembly, also called friend or Assembly member.

Inheritance
Inheritance is a technique that allows a class to acquire attributes of its base type.
Its an ability to create new classes based on existing classes. Inheritance referred as second pillar of OOPs.   

A derived type can access all the protected, internal(if derive type in same assembly) and public members of base type.
It can overload a method of base type, can redefine (override) a virtual method of base type

class dabaurman : dogs //dabaurman inheriting dogs
{
AgeOfDog = 12;
public override void bark() //Overriding bark function of dogs class
{
Console.WriteLine("Daburmans looks ready to bark always, max age of them is " + AgeOfDog.Tostring());
}
}

Abstraction (Data hiding)
Abstraction means to show only the necessary details to the client of the object. Do you know the inner details of the Monitor of your PC? What happen when you switch ON Monitor? Does this matter to you what is happening inside the Monitor? No Right, Important thing for you is weather Monitor is ON or NOT.
Let’s say you have a method "CalculateSalary" in your Employee class, which takes EmployeeId as parameter and returns the salary of the employee for the current month as an integer value. Now if someone wants to use that method. He does not need to care about how Employee object calculates the salary? An only thing he needs to be concern is name of the method, its input parameters and format of resulting member, Right?
We use thousands of methods provided by .net library without having knowledge of internal process of methods, like Math.Round(decimal d), how this function rounds the number we don't know but we can use it, this is an example of Abstraction.

Encapsulation (Data binding)
Encapsulation is process of binding data with code in a single entity. This keeps the data safe from outside interface and misuse.
Encapsulation is a protective wrapper that prevent data from being arbitrary accessed by other code.
Encapsulation referred as first pillar of OOPs.  
Variables of a class can hold data, we can give access to outside code over this type of members according us, like read only, write only or read write.

Accidental modification can happen to the public variables.
public int AgeOfDog = 30;
Putting data with related functions inside class is called Encapsulation.
Encapsulation is a process of binding or wrapping the data and the codes that operates on the data into a single entity. This keeps the data safe from outside interface and misuse. one way to think about encapsulation is as a protective wrapper that prevents code and data from being arbitrarily accessed by other code defined outside the wrapper.

Now question is that How Encapsulation hide data? 

Class Customer
{
    private int _age; //private member

    public int getAge(){return _age;}
    //OR 
    //public int Age
    // {
    //    get{return _age;}
    //    set{_age = value;}         
    // }
}
1. We can have read-only, write-only or read-write access to a member(_age) by having get, set or get and set both respectively .
2. We can validate data before setting value(in property or method).
3. We can audit or log data before setting value(in property or method).

Polymorphism
Its a technique in that a object can take multiple forms.
A base type variable can hold object of any of its drive type. Polymorphism referred as third pillar of OOPs.    

Types of Polymorphism -
1. Static Polymorphism(Compile time Polymorphism)
Ex. Function overloading, operator overloading

2. Dynamic Polymorphism(Run time Polymorphism)
Ex. Function overriding

How runtime calls methods in these scenarios? 
First CLR checks runtime type of object, then starts searching last derived form of called method from variable type(compile time type) class to the runtime type class, and calls the last derived form of the called method in between this path. 


namespace Animals
{
    class Humans
    {
        public virtual void walk()
        {
           Console.writeline("Human can walk.");
        }

    class Indians : Humans
    {
        public override void walk()
        {
            Console.writeline("Indians can walk fast.");
        }
    }
}

class mainclass
{
    void main()
    {
        Humans ObjHumans;
     
        ObjHumans = new Indians();
        ObjHumans.Walk(); // will call Indians' walk function

        ObjHumans = new Humans();
        ObjHumans.Walk(); // will call Human's walk function
    }
}

Refer http://gstomar.blogspot.in/2012/02/overriding-and-new-keywords.html

If you want your derived member to have the same name as a member in a base class, but you do not want it to participate in virtual invocation, you can use the new keyword. The newkeyword is put before the return type of a class member that is being replaced. The following code provides an example:
public class BaseClass
{
public void DoWork() { WorkField++; }
public int WorkField;
public int WorkProperty
{
get { return 0; }
}
}
public class DerivedClass : BaseClass
{
public new void DoWork() { WorkField++; }
public new int WorkField;
public new int WorkProperty
{
get { return 0; }
}
}
Hidden base class members can still be accessed from client code by casting the instance of the derived class to an instance of the base class. For example:
DerivedClass B = new DerivedClass();
B.DoWork(); // Calls the new method.
BaseClass A = (BaseClass)B;
A.DoWork(); // Calls the old method.

Function overloading
It’s a technique that enables a function name to accept different nos. and types of parameters. In other word we can create a no. of functions in a class of same name with different no. and different type of parameters.
Function overloading can be performed by
1. Different no. of parameters
2. Different type of parameters
3. Different sequence of parameters
Benefits \ Requirement
1. Makes consistency of interface.
2. No need to remember a no. of functions.
Return type can be changed of different overloaded methods.
Only change of return type can not overload a method, compiler will fire an error “you cannot overload a method by changing only return type
Ex.
Public class Words
{
Private string Getword()
{
// Will return first word of entered string
}
Private string Getword(int index)
{
// Will return word, searching by index from entered string
}
Private string Getword(string word)
{
// Will return word, by searching passed word from entered string
}
}

Function overriding 
A good article on overriding given on Code project
http://www.codeproject.com/KB/cs/cs_methodoverride.aspx

A method of base class can be re-defined in derived class this technique is called function overriding.
In other words if you want a method of base class behave something different for drive class then you can re-define it in derived class.

Method should be marked virtual (overridable in VB) in base class.
When you override it in derived class it will mark override (overrides in VB).

Signature (return type and parameters) of base and overridden methods must be same.
Access modifier of base and overridden methods must be same.
Static or non virtual method can’t be overridden.
An overridden method can’t be marked virtual, abstract or static.
It can be marked sealed so that you can stop it to overriden in further drived calsses.

Class Shapes
{
Public class Square
{
Public double x;
Public square(double x) //constructor
{
this.x = x;
}
Public virtual double area()
{
Return x * x;
}
}

Class Cube : Square
{
Public double x;

public cube(double x) //constructor
{
this.x = x;
}

public override double area()
{
return 6 * x* x;
}

}
Public static void main()
{
Double x = 2.6;
Square S = new Square(x);
Square C = new Cube(x);
Response.write(“Area of Square:” + S.area().tostring());
Response.write(“Area of Cube:” + C.area().tostring());
}
}

CI/CD - Safe DB Changes/Migrations

Safe DB Migrations means updating your database schema without breaking the running application and without downtime . In real systems (A...