Blog Home  Home Feed your aggregator (RSS 2.0)  
kevin Mocha - Life | Career
Bookmarks collected from web.
 
 Tuesday, March 09, 2010

http://www.codeproject.com/KB/webservices/Programming_WCF.aspx

The WCF programming model unifies Web Services, .NET Remoting, Distributed Transactions, and Message Queues into a single Service-oriented programming model for distributed computing. WCF uses SOAP messages for communication between two processes, thereby making WCF-based applications interoperable with any other process that communicates via SOAP messages.

A WCF Service is composed of three components parts viz,

1) Service Class - A WCF service class implements some service as a set of methods.

2) Host Environment - A Host environment can be a Console application or a Windows Service or a Windows Forms application or IIS as in case of the normal asmx web service in .NET.

3) Endpoints - All communications with the WCF service will happen via the endpoints. The endpoint is composed of 3 parts (collectively called as ABC's of endpoint) as defines below:

Address: The endpoints specify a Address that defines where the endpoint is hosted.

Contract: The endpoints specify a Contract that defines which methods of the Service class will be accessible via the endpoint; each endpoint may expose a different set of methods.

Binding: The endpoints also define a binding that specifies how a client will communicate with the service and the address where the endpoint is hosted.Various components of the WCF are depicted in the figure below.

Screenshot - WCF_Arch.gif

Who How What

There are three types of contracts namely,

Service Contracts - Describes the operations a service can perform. Maps CLR types to WSDL.
Data Contracts - Describes a data structure. Maps CLR types to XSD.
Messaga Contracts - Defines the structure of the message on the wire. Maps CLR types to SOAP messages.

Bindings can be defined in config file as well as programattically.

Tuesday, March 09, 2010 8:17:35 PM UTC  #    Comments [0]    |   |  Trackback

http://en.wikipedia.org/wiki/Component-oriented_programming

The main idea is separation of concerns;

Software engineers regard components as part of the starting platform for service orientation. Components play this role, for example, in Web Services, and more recently, in Service-Oriented Architecture (SOA) - whereby a component is converted[by whom?] into a service and subsequently inherits further characteristics beyond that of an ordinary component.

An individual component is a software package or a module that encapsulates a set of related functions (or data).

All system processes are placed into separate components so that all of the data and functions inside each component are semantically related (just as with the contents of classes). Because of this principle, it is often said that components are modular and cohesive.

With regard to system-wide co-ordination, components communicate with each other via interfaces. When a component offers services to the rest of the system, it adopts a provided interface which specifies the services that can be utilized by other components and how. This interface can be seen as a signature of the component - the client does not need to know about the inner workings of the component (implementation) in order to make use of it. This principle results in components referred to as encapsulated.

Another important attribute of components is that they are substitutable,

Software components often take the form of objects or collections of objects (from object-oriented programming), in some binary or textual form, adhering to some interface description language (IDL) so that the component may exist autonomously from other components in a computer.

Reusability is an important characteristic of a high-quality software component. A software component should be designed and implemented so that it can be reused in many different programs.

It takes significant effort and awareness to write a software component that is effectively reusable. The component needs to be:

  • fully documented
  • thoroughly tested
    • robust - with comprehensive input-validity checking
    • able to pass back appropriate error messages or return codes
  • designed with an awareness that it will be put to unforeseen uses

Differences from object-oriented programming

Proponents of object-oriented programming (OOP) maintain that software should be written according to a mental model of the actual or imagined objects it represents. OOP and the related disciplines of object-oriented design and object-oriented analysis focus on modeling real-world[citation needed] interactions and attempting to create "verbs" and "nouns" which can be used in intuitive[citation needed] ways, ideally by end users as well as by programmers coding for those end users.

Component-based software engineering, by contrast, makes no such assumptions, and instead states that developers should construct software by gluing together prefabricated components - much like in the fields of electronics or mechanics. Some peers[who?] will even talk of modularizing systems as software components as a new programming paradigm.

 

 

 

Component-based development (CBD) is an extension of object-oriented programming. CBD does away with the language and vendor-specific limitations of OOP, and makes software reuse more practical and accelerates the development process. Event-based programming is the next logical step in CBD, and makes components more reusable due to their decoupled nature. But event-based systems are easier to develop, which means they are cheaper and more reliable than traditional OOP or CBD systems.

Tuesday, March 09, 2010 7:22:24 PM UTC  #    Comments [0]    |   |  Trackback
 Sunday, March 07, 2010

Web 2.0 addresses the new web technologies that are used to bring more interactivity to web
applications.

Additionally, Web 2.0 also includes a behavioral shift on the web, where users are
encouraged to customize their own content on web applications rather than view static/
generic content supplied by an organization.

In addition to the technology and behavior changes, Web 2.0 can also mean the shift
from shrink-wrapped software to software as a service.

 

Another aspect of Web 2.0 are mash-up and plug-in pages. (Personal google page)

 

Injection attacks are based on a single problem that persists in many technologies: namely,
no strict separation exists between program instructions and user data (also referred to as
user input). This problem allows for attackers to sneak program instructions into places
where the developer expected only benign data. By sneaking in program instructions, the
attacker can instruct the program to perform actions of the attacker’s choosing.

 

Input Injection

 

SQL Injection

 

SELECT id FROM user_table WHERE username = '' OR 1=1 -- ' AND password
= PASSWORD('x')

 

Injection attacks are not necessary blind attacks. Many web applications are developed
with open-source tools. To make injection attacks more successful, download free or
evaluation copies of products and set up your own test system. Once you have found an
error in your test system, it is highly probable that the same issue will exist on all web
applications using that tool.

 

Cure: 1. constrain data types, escape user input, prepared statements (the best)

 

XPath Injection

//users[username/text()='admin' and password/text()='' or '1'='1' ]/id/text()

 

Command Injection (Escape)

Directory Transversal Attacks
XXE (XML eXternal Entity) Attacks
(prohibit the external entity in XML parser)

LDAP Injection
whitelisting characters—that is, allow
alphanumeric characters (a–z, A–Z, and 0–9) and deny all other characters.
Buffer Overflows
The injection aspect of buffer overflows is that the attacker injects
machine instructions (called shell code) into some user input. The attacker somewhat needs to
know where the shell code will end up in the memory of the computer running the web
application. Then the attacker overwrites the return address to point to the memory location
of the shell code.

Sunday, March 07, 2010 5:08:42 AM UTC  #    Comments [0]    |   |  Trackback

                                               Security

HTTP offers integrated mechanisms for authenticating users. Collectively referred to as HTTP authentication, these mechanisms provide a way for users to be authenticated without the necessity of any server-side programming logic. This can be especially helpful for restricting access to static resources (such as images or HTML files). Of course, server-side scripts can also implement HTTP authentication, although Web developers often authenticate users in the application logic itself.

There are two basic types of HTTP authentication:

  • Basic authentication

  • Digest authentication

image

image

An elegant solution to these types of problems is SSL, Secure Sockets Layer. In 1994, Netscape released the specification of Secure Sockets Layer. By 1995, version 3.0 of SSL was released, and it has since taken the Web by storm. SSL has dramatically changed the way people use the Web, and it provides a very good solution to many of the Web's shortcomings, most importantly:

  • Data integrity— SSL can help ensure that data (HTTP messages) cannot be changed while in transit.

  • Data confidentiality— SSL provides strong cryptographic techniques used to encrypt HTTP messages.

  • Identification— SSL can offer reasonable assurance as to the identity of a Web server. It can also be used to validate the identity of a client, but this is less common.

A digital certificate is a document that declares that a particular public key is owned by a particular Web site (see Figure 18.3). The CA's role is very similar to a notary whose responsibility is to ensure the correct identity of people signing a legal document.

 

SSL is basically a protocol that employs both symmetric and asymmetric cryptography to protect messages that use TCP as the transport-level protocol. Because of the high performance expense of asymmetric cryptography, it is only used to exchange the randomly generated symmetric key that is then used for the symmetric encryption of the HTTP messages.

 

image

image https on port 443

Whenever a Web browser connects to a Web site over a secure connection, it requires that the SSL certificate the Web server presents meets three main conditions:

  • The domain name on the certificate must match the domain name the Web browser believes itself to be requesting a resource from.

  • The certificate must be valid (not expired).

  • The certificate must be signed by a trusted certificate authority (CA).

Transport Layer Security (TLS) is a formally standardized version of SSL. The biggest difference, in fact, is that TLS is defined and maintained by an international standards body, the Internet Engineering Task Force (IETF). SSL is developed and maintained by Netscape.

 

One of the advantages of the IETF's involvement in TLS is that they also control the HTTP protocol. This situation can possibly be credited for RFC 2817, which describes a method for using the Upgrade general header to upgrade to HTTP over TLS. The significance of this is that it allows for a change in protocol without having to utilize a separate port. Thus, a Web server that supports this technique can implement TLS over port 80. An example of a Web client's request is the following:

GET / HTTP/1.1 
Host: 127.0.0.1 
Upgrade: TLS/1.0 
Connection: Upgrade 

A Web server that accepts this upgrade will issue an HTTP response similar to the following:

HTTP/1.1 101 Switching Protocols 
Upgrade: TLS/1.0, HTTP/1.1 
Connection: Upgrade 

At this point, a typical SSL handshake will take place over the current connection. It is sometimes confusing to consider that the SSL handshake can take place over port 80 at this point while the Web server can still accept normal HTTP requests over the same port. Note that the upgrade only affects the current TCP connection. Just as a Web server does not (barring extremely odd memory collisions) send the wrong HTTP response to the wrong Web client, it can also keep protocol upgrades straight.

Sunday, March 07, 2010 1:06:37 AM UTC  #    Comments [0]    |   |  Trackback
 Saturday, March 06, 2010

Maintaining State

If a unique response per client is desired, something in the HTTP request itself must be unique.

Once a method of state management has been established, you need only to authenticate the user once. Because state management provides a way to identify a Web client, user identification simply requires that you remember which user is associated with which client upon authentication.

When I speak of maintaining state, I am only speaking of client identification, which is accomplished by associating multiple HTTP requests.

Maintaining session, on the other hand, requires two related tasks:

  • Identifying the client (state management)

  • Retaining information about the client

Although cookies are most often described in conversation as if they are entities (for example, "a Web server sends you a cookie"), they are much easier to understand at a functional level if you consider them an extension of the HTTP protocol, which is actually more correct. Cookies can be defined as the addition of two HTTP headers:

  • Set-Cookie response header

  • Cookie request header

image

    A common question seen on mailing lists and discussion forums for Web developers is how to test whether the client is accepting cookies, and many people do not understand the answer. As is evident in Figure 11.3, it is impossible to determine whether the client accepted the cookie until the second request is sent (step 3 in the figure). If the cookie is included in the second request, the client accepted it. If not, the client rejected it.

Some developers choose to force the issue of determining whether the client accepts cookies by redirecting the client to a second URL upon entrance.

Cookies have become a source of privacy concern in recent years. As with most technologies in the computer industry, this reputation has been earned by the misuse of the technology more than the technology itself.

Whether using files or a database to store the session information, there are three basic elements you will want to store for each session's record:

  • Unique identifier

  • Timestamp of last access

  • Client data

image

 

Improve the performance

Caching can refer to many concepts. The general meaning of cache is to store a copy of something to prevent the necessity of retrieving it again. When speaking of Web development, there are three main types of caching:

  • Caching on the server— Storing a complete or partially generated resource on the server to keep from having to regenerate it.

  • Caching on the client— Storing a resource on the client to keep from having to receive the entire resource again.

  • Proxy caching— Storing a resource on a proxy to allow direct replies to an HTTP request rather than having to receive the entire resource from the origin server again.

Although there are many side advantages to caching, there are three core benefits:

  • Improve response time from a user perspective— This is what most Web developers focus on, the user experience.

  • Lessen network load— Many Web developers overlook this metric because bandwidth is often viewed as an expendable resource, where more can be purchased as needed.

  • Lessen server load— This metric is more difficult to overlook, as it directly impacts the user experience in terms of performance and reliability (stressed servers fail more often).

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Saturday, March 06, 2010 8:56:19 PM UTC  #    Comments [0]    |   |  Trackback

It is important to remember that an HTTP response completes the HTTP transaction. Many people new to Web development have a difficult time distinguishing between server-side code (code that executes on the server) and client-side code (code that executes on the client). Scripting languages such as PHP, ColdFusion, and JSP are executed on the server, and their output is included in the HTTP response. In fact, their output is the content of the HTTP response, and most modern Web scripting languages also allow for some manipulation of the HTTP as well, such as altering or adding headers, changing status codes, and so on. Once the Web client receives the HTTP response, the transaction is complete. The Web client will then render the page, execute client-side scripts such as JavaScript, load images (by issuing separate GET requests), and so on.

 

With HTTP/1.1, persistent connections are the default behavior. This means that the Web server will not close the connection after sending the HTTP response unless the client intends to close the connection after receiving it. In this case, the client will include the following header in the HTTP request:

Connection: close 

Alternatively, the server can close the connection upon sending the HTTP response, although it should be polite and include the same header as shown previously so that the Web client expects this action.

 

An HTTP response is broken into the following three logical pieces:

  • Status line

  • HTTP headers

  • Content

An example status line is as follows:

HTTP/1.1 200 OK 

The status line contains three elements:

  • The version of HTTP being used, in the format HTTP/x.x

  • The status code

  • A short description of the status code

There are three types of HTTP headers allowed in a response:

  • General headers

  • Response headers

  • Entity headers

 

Status codes are grouped into the following ranges:

  • Informational (100-199)

  • Successful (200-299)

  • Redirection (300-399)

  • Client error (400-499)

  • Server error (500-599)

 

  • 100 Continue
  • 101 Switching Protocols
  • 200 OK
  • 400 Bad Request
  • 401 Unauthorized
  • 403 Forbidden
  • 404 Not Found
  • 500 Internal Server Error
  • 502 Bad Gateway
  • 503 Service Unavailable

Content-Disposition, combined with a proper Content-Type header, provides the developer absolute control over the interpretation of the resource's media type.

Saturday, March 06, 2010 5:51:07 AM UTC  #    Comments [0]    |   |  Trackback
 Friday, March 05, 2010

Form 2.0 data binding

Binding nameBinding = new Binding("Text", this.raceCarDriver, "Name", true); 
this.nameTextBox.DataBindings.Add(nameBinding);
or 
this.nameTextBox.DataBindings.Add( "Text", this.raceCarDriver, "Name");

The minimum implementation that is considered a list data source by the Windows Forms binding engine is a class that implements the IList interface (from System.Collections).

this.BindingManager.Position = 0; 
RefreshItems();

this.raceCarDriversListBox.DataSource = this.raceCarDrivers;
this.raceCarDriversListBox.DisplayMember = "Name";

void addButton_Click(object sender, EventArgs e) {
  // Add item to list data source directly
  RaceCarDriver raceCarDriver = new RaceCarDriver("Nelson Piquet", 300);
  this.raceCarDrivers.Add(raceCarDriver);

  // Select new item
  this.BindingManager.Position = this.BindingManager.Count - 1;
}

private void deleteButton_Click(object sender, EventArgs e) {
  // Remove item from list data source directly
  this.raceCarDrivers.Remove(
    (RaceCarDriver)this.BindingManager.Current);
}

BindingList<T>->IBindingList->IList
BindingList<T> nicely implements the list management (AllowEdit, AllowNew, AllowRemove, and AddNew) and change notification (SupportsChangeNotification, ListChanged) functional subsets of IBindingList.[5] And because it's generic, it can turn any type into a strongly typed list data source with data-binding-savvy list management and change notification using something like the following code

Two-Way Item Change Synchronization

When the values in a DataGridView row are changed, DataGridView automatically replicates the changes to the bound list data source. Similarly, when changes are made to an item in the list data source of BindingList<T>, an item change notification is broadcast to all bound controls.

 

BindingList<T> allows us to use almost any class to create a data-binding-savvy strongly typed list data source. However, some item classes come already associated with their own collection classes. Although any collection class that implements IList can be used as a list data source, you don't get full-flavor data binding if you don't implement IBindingListnamely, support for two-way list and item change notification.

To gain this support and to avoid the highly involved implementation of IBindingList ourselves, we'd love to be able to "upgrade" an existing IList implementation to IBindingList. The class that performs this upgrade for you is BindingSource.

The BindingSource component (from System.Windows.Forms) consumes either item types or list types and exposes them as IBindingList implementations.

 

if you need to implement a VCR-type control to navigate the items in a data source, you don't have to acquire a BindingManager and you don't have to manually create your own navigation methods. Instead, you simply rely on the BindingSource to manage currency and use its currency-oriented methods as required:

 

void moveFirstButton_Click(object sender, EventArgs e)

{ this.employeesBindingSource.MoveFirst(); RefreshItems(); }

 

Master-Detail binding
image

 

Why [STAThread]

When the STAThreadAttribute is applied, it changes the apartment state of the current thread to be single threaded. Without getting into a huge discussion about COM and threading, this attribute ensures the communication mechanism between the current thread and other threads that may want to talk to it via COM. When you're using Windows Forms, depending on the feature you're using, it may be using COM interop in order to communicate with operating system components. Good examples of this are the Clipboard and the File Dialogs.

SingleInstanceApplication

// SingleInstanceApplication.cs
class SingleInstanceApplication : WindowsFormsApplicationBase
{ ... protected override void OnCreateMainForm() { this.MainForm = new MainForm(); }

Friday, March 05, 2010 8:13:20 PM UTC  #    Comments [0]    |   |  Trackback
 Thursday, March 04, 2010

CLR and .NET Framework

The CLR is the runtime for executing managed code. C# is one of several managed
languages that get compiled into managed code. Managed code is packaged into an
assembly, in the form of either an executable file (an .exe) or a library (a .dll), along
with type information, or metadata.

Managed code is represented in Intermediate Language or IL. When the CLR loads
an assembly, it converts the IL into the native code of the machine, such as x86. This
conversion is done by the CLR’s JIT (Just-In-Time) compiler. An assembly retains

almost all of the original source language constructs, which makes it easy to inspect
and even generate code dynamically.

The CLR performs as a host for numerous runtime services. Examples of these services
include memory management, the loading of libraries, and security services.
The CLR is language-neutral, allowing developers to build applications in multiple
languages (e.g., C#, Visual Basic .NET, Managed C++, Delphi.NET, Chrome .NET,
and J#).

 

 

How the Garbage Collector Works:

The GC begins with its root object references, and walks the object graph, marking
all the objects it touches as reachable. Once this process is complete, all objects that
have not been marked are considered unused, and are subject to garbage collection.
Unused objects without finalizers are immediately discarded; unused objects with
finalizers are enqueued for processing on the finalizer thread after the GC is complete.
These objects then become eligible for collection in the next GC for the object’s
generation (unless resurrected).

 

The remaining “live” objects are then shifted to the start of the heap (compacted),
freeing space for more objects. This compaction serves two purposes: it avoids

memory fragmentation, and it allows the GC to employ a very simple strategy when
allocating new objects, which is to always allocate memory at the end of the heap.
This avoids the potentially time-consuming task of maintaining a list of free memory
segments.

 

If there is insufficient space to allocate memory for a new object after garbage
collection, and the operating system is unable to grant further memory, an
OutOfMemoryException is thrown.

 

Generational collection
The most important optimization is that the GC is generational. This takes advantage
of the fact that although many objects are allocated and discarded rapidly, certain
objects are long-lived and thus don’t need to be traced during every collection.
Basically, the GC divides the managed heap into three generations. Objects that have
just been allocated are in Gen0 and objects that have survived one collection cycle
are in Gen1; all other objects are in Gen2.

 

The large object heap
The GC uses a separate heap called the Large Object Heap (LOH) for objects larger
than a certain threshold (currently 85,000 bytes). This avoids excessive Gen0
collections—without the LOH, allocating a series of 16 MB objects might trigger a
Gen0 collection after every allocation.

The LOH is not subject to compaction, because moving large blocks of memory
during garbage collection would be prohibitively expensive. This has two
consequences:

1. Allocations can be slower
2. The LOH is subject to fragmentation

The large object heap is also nongenerational: all objects are treated as Gen2.

 

Concurrent and background collection

The GC must freeze (block) your execution threads for periods during a collection.
This includes the entire period during which a Gen0 or Gen1 collection takes place.
The GC makes a special attempt, though, at allowing threads to run during a Gen2
collection

 

Forcing Garbage Collection (not recommend)

GC.Collect()

 

A good guideline is to implement IDisposable yourself if any field in your class is assigned an object that implements IDisposable. (Such as System.Timers.Timer)(System.Threading.Timer is different)

 

Monitor the memory leaks: long memoryUsed = GC.GetTotalMemory (true);

 

Occasionally, it’s useful to hold a reference to an object that’s “invisible” to the GC
in terms of keeping the object alive. This is called a weak reference, and is implemented
by the System.WeakReference class.

 

One use for WeakReference is to cache large object graphs.
http://www.shafqatahmed.com/2008/01/weakreference-b.html

 

 

Asynchronous Methods

asynchronous programming model or APM

An asynchronous method aims never to block any thread, instead using a pattern of
returning with a callback.

 

The end goal of the APM is thread economy.

The purpose of asynchronous methods isn’t to
provide a convenient mechanism for executing a method in parallel with the caller;
it’s to optimize thread resources.

 

Here’s the golden rule of the APM: Make good use of the CPU, or exit with a callback!

 

The primary use for asynchronous methods is handling many potentially longrunning
concurrent requests—typically over slow network connections.

 

IAsyncResult BeginXXX (in/ref-args, AsyncCallback callback, object state);
return-type EndXXX (out/ref-args, IAsyncResult asyncResult);
public delegate void AsyncCallback (IAsyncResult ar);

 

To avoid blocking, you will nearly always call the EndXXX method from inside the
callback method. Callbacks always run on pooled threads.

 

image

 

http://en.csharp-online.net/CSharp_Delegates_and_Events%E2%80%94Asynchronous_method_calls
http://msdn.microsoft.com/en-us/library/h80ttd5f.aspx

Collections

ICollection Properties

image

image

IComparer
Copmare method

IEqualityComparer
GetHashCode, Equals

SortedList calss is a dictionary.

Race conditions and deadlocks

http://support.microsoft.com/kb/317723

A race condition occurs when two threads access a shared variable at the same time. The first thread reads the variable, and the second thread reads the same value from the variable. Then the first thread and second thread perform their operations on the value, and they race to see which thread can write the value last to the shared variable. The value of the thread that writes its value last is preserved, because the thread is writing over the value that the previous thread wrote.

A deadlock occurs when two threads each lock a different variable at the same time and then try to lock the variable that the other thread already locked. As a result, each thread stops executing and waits for the other thread to release the variable. Because each thread is holding the variable that the other thread wants, nothing occurs, and the threads remain deadlocked.

Thursday, March 04, 2010 7:57:29 PM UTC  #    Comments [0]    |   |  Trackback
 Wednesday, December 02, 2009
Copyright © 2010 Kevin Mocha. All rights reserved.
DasBlog 'Portal' theme by Johnny Hughes.
Pick a theme: