dropdownstyle: dropdownlist autocompletemode: append autocompletesource: listtiems
http://msdn.microsoft.com/en-us/library/bb335710.aspx // Lambda expression as executable code.
Func<int, bool> deleg = i => i < 5;
// Invoke the delegate and display the output.
Console.WriteLine("deleg(4) = {0}", deleg(4));
// Lambda expression as data in the form of an expression tree.
System.Linq.Expressions.Expression<Func<int, bool>> expr = i => i < 5;
// Compile the expression tree into executable code.
Func<int, bool> deleg2 = expr.Compile();
// Invoke the method and print the output.
Console.WriteLine("deleg2(4) = {0}", deleg2(4));
/* This code produces the following output:
deleg(4) = True
deleg2(4) = True
*/
public IPrintableDisplayableDocument CreateReport(BillSummaryReportData reportData)
{
Word2007ReportWriter writer = new Word2007ReportWriter(reportData, ResourceTransform.BillSummaryReport);
Word2007Document document = writer.CreateReport();
using (var stream = new MemoryStream())
{
stream.Write(document.Content, 0, document.Content.Length);
// insert bill summary rtf chunk
var wordDoc = WordprocessingDocument.Open(stream, true);
Stream streamImportRtf =
new MemoryStream(UTF8Encoding.Default.GetBytes(reportData.BillSummaryReportBody.BillSummary));
AlternativeFormatImportPart chunkRtf =
wordDoc.MainDocumentPart.AddAlternativeFormatImportPart(AlternativeFormatImportPartType.Rtf,
"BillSummaryRtfChunk");
chunkRtf.FeedData(streamImportRtf);
wordDoc.Close();
document.Content = stream.ToArray();
}
return document;
}
http://www.albahari.com/threading/part2.aspx Passing Data to a Thread
The easiest way to pass arguments to a thread’s target method is to execute a lambda expression that calls the method with the desired arguments:
static void Main() { Thread t = new Thread ( () => Print ("Hello from t!") ); t.Start(); }
static void Print (string message) { Console.WriteLine (message); }
With this approach, you can pass in any number of arguments to the method. You can even wrap the entire implementation in a multistatement lambda:
new Thread (() => { Console.WriteLine ("I'm running on another thread!"); Console.WriteLine ("This is so easy!"); }).Start();
You can do the same thing almost as easily in C# 2.0 with anonymous methods:
new Thread (delegate() { ... }).Start();
Another technique is to pass an argument into Thread’s Start method: static void Main() { Thread t = new Thread (Print); t.Start ("Hello from t!"); } static void Print (object messageObj) { string message = (string) messageObj; // We need to cast here Console.WriteLine (message); }
This works because Thread’s constructor is overloaded to accept either of two delegates:
public delegate void ThreadStart(); public delegate void ParameterizedThreadStart (object obj);
The limitation of ParameterizedThreadStart is that it accepts only one argument. And because it’s of type object, it usually needs to be cast. Foreground and Background Threads When a process terminates in this manner, any finally blocks in the execution stack of background threads are circumvented. This is a problem if your program employs finally (or using) blocks to perform cleanup work such as releasing resources or deleting temporary files. To avoid this, you can explicitly wait out such background threads upon exiting an application. There are two ways to accomplish this:
• If you’ve created the thread yourself, call Join on the thread. • If you’re on a pooled thread (see “Thread Pooling” on page 800) use an event wait handle (see “Signaling with Event Wait Handles” on page 832). Thread Pooling There are a number of ways to enter the thread pool: • Via the Task Parallel Library or PLINQ (from Framework 4.0) • By calling ThreadPool.QueueUserWorkItem • Via asynchronous delegates • Via BackgroundWorker Here’s how you start a worker task via an asynchronous delegate: 1. Instantiate a delegate targeting the method you want to run in parallel (typically one of the predefined Func delegates). 2. Call BeginInvoke on the delegate, saving its IAsyncResult return value. BeginInvoke returns immediately to the caller. You can then perform other activities while the pooled thread is working. 3. When you need the results, call EndInvoke on the delegate, passing in the saved IAsyncResult object. Don’t confuse asynchronous delegates with asynchronous methods (methods starting with Begin or End, such as File.BeginRead/File.EndRead). Asynchronous methods follow a similar protocol outwardly, but they exist to solve a much more difficult problem, which we describe in Chapter 23. Synchronization Nonblocking Synchronization The following implicitly generate full fences: • C#’s lock statement (Monitor.Enter/Monitor.Exit) • All methods on the Interlocked class (we’ll cover these soon) • Asynchronous callbacks that use the thread pool—these include asynchronous delegates, APM callbacks (Chapter 23), and Task continuations (Chapter 22) • Setting and waiting on a signaling construct • Anything that relies on signaling, such as starting or waiting on a Task Memory barriers and locking
C#'s lock statement is in fact a syntactic shortcut for a call to the methods Monitor.Enter and Monitor.Exit, with a try-finally block. Here's what's actually happening within the Go method of the preceding example: Monitor.Enter (locker);
try
{
if (val2 != 0) Console.WriteLine (val1 / val2);
val2 = 0;
}
finally { Monitor.Exit (locker);
As we said earlier, Monitor.Enter and Monitor.Exit both generate full fences. So if we ignore a lock’s mutual exclusion guarantee, we could say that this:
lock (someField) { ... }
is equivalent to this:
Thread.MemoryBarrier(); { ... } Thread.MemoryBarrier();
A Mutex is like a C# lock, but it can work across multiple processes. In other words, Mutex can be computer-wide as well as application-wide.
With a Mutex class, you call the WaitOne method to lock and ReleaseMutex to unlock. Just as with the lock statement, a Mutex can be released only from the same thread that obtained it. A common use for a cross-process Mutex is to ensure that only one instance of a program can run at a time.
A Semaphore is like a nightclub: it has a certain capacity, enforced by a bouncer. Once it's full, no more people can enter and a queue builds up outside. Then, for each person that leaves, one person enters from the head of the queue. The constructor requires a minimum of two arguments: the number of places currently available in the nightclub and the club's total capacity.
A Semaphore with a capacity of one is similar to a Mutex or lock, except that the Semaphore has no "owner"—it's thread-agnostic. Any thread can call Release on a Semaphore, whereas with Mutex and lock, only the thread that obtained the lock can release it.
Semaphores can be useful in limiting concurrency—preventing too many threads from executing a particular piece of code at once. In the following example, five threads try to enter a nightclub that allows only three threads in at once:
Interlocked
Interlocked.Increment (ref _sum); Interlocked.Decrement (ref _sum);
Interlocked’s mathematical operations are restricted to Increment, Decrement, and Add.
Signaling with Event Wait Handles
class BasicWaitHandle
{
static EventWaitHandle wh = new AutoResetEvent (false);
static void Main( )
{
new Thread (Waiter).Start( );
Thread.Sleep (1000); // Pause for a second...
wh.Set( ); // Wake up the Waiter.
}
static void Waiter( )
{
Console.WriteLine ("Waiting...");
wh.WaitOne( ); // Wait for notification
Console.WriteLine ("Notified");
}
}
Thread.Interrupt and Abort
Calling Interrupt on a blocked thread forcibly releases it, throwing a ThreadInterruptedException Interrupting a thread does not cause the thread to end, unless the ThreadInterruptedException is unhandled.
The big difference between Interrupt and Abort is what happens when it's called on a thread that is not blocked. Whereas Interrupt waits until the thread next blocks before doing anything, Abort throws an exception on the thread right where it's executing (unmanaged code excepted). This is a problem because .NET Framework code might be aborted; code that is not abort-safe. This rules out using Abort in almost any nontrivial context.
An alternative to aborting another thread is to implement a pattern whereby the worker periodically checks a cancel flag, exiting if the flag is true. To abort, the instigator simply sets the flag, and then waits for the worker to comply.
BackgroundWorker
BackgroundWorker is a helper class in the System.ComponentModel namespace for managing a worker thread. It provides the following features:
-
A cancel flag for signaling a worker to end without using Abort
-
A standard protocol for reporting progress, completion, and cancellation
-
An implementation of IComponent allowing it be sited in Visual Studio's designer
-
Exception handling on the worker thread
-
The ability to update Windows Forms or WPF controls in response to worker progress or completion bw = new BackgroundWorker( );
bw.WorkerReportsProgress = true;
bw.WorkerSupportsCancellation = true;
bw.DoWork += bw_DoWork;
bw.ProgressChanged += bw_ProgressChanged;
bw.RunWorkerCompleted += bw_RunWorkerCompleted;
bw.RunWorkerAsync ("Hello to worker");
ReadWRiterLockSlim
With both classes, there are two basic kinds of lock—a read lock and a write lock:
So, a thread holding a write lock blocks all other threads trying to obtain a read or write lock (and vice versa). But if no thread holds a write lock, any number of threads may concurrently obtain a read lock.
ReaderWriterLockSlim defines the following methods for obtaining and releasing read/write locks: public void EnterReadLock( );
public void ExitReadLock( );
public void EnterWriteLock( );
public void ExitWriteLock( ); Timer
The .NET Framework provides four timers. Two of these are general-purpose multithreaded timers:
-
System.Threading.Timer
-
System.Timers.Timer
The other two are special-purpose single-threaded timers:
Both are like System.Timers.Timer in the members that they expose (Interval, Tick, Start, and Stop) and are used in a similar manner. However, they differ in how they work internally. Instead of using the thread pool to generate timer events, the Windows Forms and WPF timers rely on the message pumping mechanism of their underlying user interface model. This means that the Tick event always fires on the same thread that originally created the timer—which, in a normal application, is the same thread used to manage all user interface elements and controls. This has a number of benefits:
-
You can forget about thread safety.
-
A fresh Tick will never fire until the previous Tick has finished processing.
-
You can update user interface elements and controls directly from Tick event handling code, without calling Control.Invoke or Dispatcher.Invoke.
Anonymous Methods
Anonymous methods are a C# 2.0 feature that has been subsumed largely by C# 3.0 lambda expressions. An anonymous method is like a lambda expression, but it lacks the following features: • Implicitly typed parameters • Expression syntax (an anonymous method must always be a statement block) • The ability to compile to an expression tree, by assigning to Expression<T>
To write an anonymous method, you include the delegate keyword followed (optionally) by a parameter declaration and then a method body. For example, given this delegate:
delegate int Transformer (int i);
we could write and call an anonymous method as follows:
Transformer sqr = delegate (int x) {return x * x;}; Console.WriteLine (sqr(3)); // 9
The first line is semantically equivalent to the following lambda expression:
Transformer sqr = (int x) => {return x * x;};
Or simply:
Transformer sqr = x => x * x;
A unique feature of anonymous methods is that you can omit the parameter declaration entirely—even if the delegate expects them. This can be useful in declaring events with a default empty handler:
public event EventHandler Clicked = delegate { };
This avoids the need for a null check before firing the event. The following is also legal:
Clicked += delegate { Console.WriteLine ("clicked"); }; // No parameters
Anonymous methods capture outer variables in the same way lambda expressions do.
Below is a picture of the HTTP Request Pipeline and its three replaceable component types: HttpHandler, HttpApplication, and HttpModule. As requests come in, they are queued up and assigned to a worker thread that then processes the request by interacting with each of these component types. Figure 2-4: The HTTP Request Pipeline allows developers to replace components such as HttpHandler, HttpApplication, and HttpModule. The ultimate destination of any request is the endpoint, which is modeled in the HTTP Request Pipeline by using an HttpHandler class, which implements the IHttpHandler interface. As a developer, you can create a custom HttpHandler component and plug it into the HTTP Request Pipeline by adding configuration elements to the web.config file. The HTTP Request Pipeline places an HttpApplication component in front of the HttpHandler. On an application-wide basis, incoming requests are always routed through the HttpApplication before they reach the target HttpHandler, thus giving the HttpApplication the ability to pre-process any request no matter which HttpHandler it is being routed to. This preprocessing stage is handled through a series of events that are defined inside the HttpApplication class such as BeginRequest, AuthenticateRequest, and AuthorizeRequest. In situations when you don’t want to use a custom HttpApplication component, the ASP.NET Framework initializes the HTTP Request Pipeline with a standard HttpApplication object that provides default behavior. However, you can replace this standard component by creating a file named global.asax and placing it in the root directory of the hosting ASP.NET application. For example, you can create a global.asax that looks like the following: <%@ Application Language="C#" %>
<script runat="server">
protected void Application_AuthenticateRequest(object sender, EventArgs e) {
// your code goes here for request authentication
}
protected void Application_AuthorizeRequest(object sender, EventArgs e) {
// your code goes here for request authorization
}
</script>
The third replaceable component type in the HTTP Request Pipeline is the HttpModule. The HttpModule is similar to the HttpApplication component in that it is designed to handle events defined by the HttpApplication class and is processed before control is passed to any HttpHandler classes. For example, you can create a custom HttpModule component to handle request-level events such as BeginRequest, AuthenticateRequest, and AuthorizeRequest. As with the HttpHandler, an HttpModule class is defined with an interface. You can create a class that implements the IHttpModule interface and plug it into the HTTP Request Pipeline by adding configuration elements to the web.config file.
Whereas custom HttpApplication components can be defined as simple text files with an .asax extension, custom HttpModule components are always compiled as classes within assembly DLLs. To add a custom HttpModule component into the HTTP Request Pipeline, you then add entries into a web.config file.
While an HttpApplication component and an HttpModule component are similar in what they do, the HttpModule contains a few noteworthy differences. First, you are not limited to one HttpModule per application as you are with the HttpApplication components. The web.config file for an ASP.NET application can add in several different HttpModule components. Second, HttpModule components can be configured at the machine level. In fact, the ASP.NET Framework ships with several different HttpModule components that are automatically configured at the machine level to provide ASP.NET functionality for things such as Windows authentication, Forms authentication, and output caching.
The final component that we want to discuss with respect to the HTTP Request Pipeline is HttpContext. As ASP.NET initializes a request to send to the HTTP Request Pipeline, it creates an object from the HttpContext class and initializes it with important contextual information.
From a timing perspective, it’s important to see that ASP.NET creates this object before any custom code inside the HTTP Request Pipeline has a chance to begin execution. This means that you can always program against the HttpContext object and the child objects that it contains, such as Request, User, and Response. Whenever you are authoring a component that is to execute within the HTTP Request Pipeline, you can write code that looks like the following: HttpContext currentContext = HttpContext.Current;
string incomingUrl = currentContext.Request.Url;
string currentUser = currentContext.User.Identity.Name;
currentContext.Response.Write("Hello world");
From C# 3.0 in Nutshell (lulu: Use toArray() to force immediate execution) An important feature of most query operators is that they execute not when constructed, but when enumerated (in other words, when MoveNext is called on its enumerator). Consider the following query: var numbers = new List<int>( );
numbers.Add (1);
IEnumerable<int> query = numbers.Select (n => n * 10); // Build query
numbers.Add (2); // Sneak in an extra element
foreach (int n in query)
Console.Write (n + "|"); // 10|20|
The extra number that we sneaked into the list after constructing the query is included in the result, because it's not until the foreach statement runs that any filtering or sorting takes place. This is called deferred or lazy evaluation. All standard query operators provide deferred execution, with the following exceptions:
-
Operators that return a single element or scalar value, such as First or Count
-
The following conversion operators: ToArray, ToList, ToDictionary, ToLookup
These operators cause immediate query execution because their result types have no mechanism for providing deferred execution. The Count method, for instance, returns a simple integer, which doesn't then get enumerated. The following query is executed immediately: int matches = numbers.Where (n => n < 2).Count( ); // 1
Deferred execution is important because it decouples query construction from query execution. This allows you to construct a query in several steps, as well as making LINQ to SQL queries possible.
1: using System; 2: using Kellerman.Business; //Reference to class to test 3: using NUnit.Framework; //This must be included to do the asserts 4: 5: namespace Kellerman.BusinessTest 6: { 7: //Tests for the Invoice Business Object 8: [TestFixture] 9: [Category("Optional Category Attribute"), Description("Optional Description")] 10: public class InvoiceTest 11: { 12: private Invoice _invoice = null; 13: //Code that is run before each test 14: [SetUp] 15: public void Initialize() 16: { 17: _invoice = new Invoice(); 18: } 19: //Code that is run after each test 20: [TearDown] 21: public void Cleanup() 22: { 23: } 24: //Example test and asserts 25: [Test, Description("Property Tests")] 26: public void InvoiceIdTest() 27: { 28: int expected = 7; 29: _invoice.InvoiceId = expected; 30: Assert.AreEqual(expected, 31: _invoice.InvoiceId, 32: "Kellerman.Business.Invoice.InvoiceId not set correctly"); 33: //Other example Asserts 34: Assert.IsTrue(true); 35: Assert.IsFalse(false); 36: Assert.IsNull(null); 37: Assert.IsNotNull(_invoice); 38: Assert.IsEmpty(string.Empty); 39: Assert.IsNotEmpty("This string is not empty"); 40: Assert.Fail("This is a failure message"); 41: } 42: //Expected Exception Test 43: [Test] 44: [ExpectedException(typeof(System.Security.SecurityException))] 45: public void DeleteTestNoRights() 46: { 47: _invoice.Delete(); 48: } 49: //Not Implemented Test 50: [Test] 51: [Ignore("Please implement")] 52: public void UpdateTestNoRights() 53: { 54: } 55: } 56: }
In broadcaster 1. Declare a event member. 2. fire the event somewhere public class PriceChangedEventArgs : System.EventArgs
{
public readonly decimal LastPrice;
public readonly decimal NewPrice;
public PriceChangedEventArgs (decimal lastPrice, decimal newPrice)
{
LastPrice = lastPrice;
NewPrice = newPrice;
}
}
public class Stock
{
...
public event EventHandler<PriceChangedEventArgs> PriceChanged;
protected virtual void OnPriceChanged (PriceChangedEventArgs e)
{
if (PriceChanged != null) PriceChanged (this, e);
}
}
class Test
{
static void Main( )
{
Stock stock = new Stock ("THPW");
stock.Price = 27.10M;
// register with the PriceChanged event
stock.PriceChanged += stock_PriceChanged;
stock.Price = 31.59M;
}
static void stock_PriceChanged (object sender, PriceChangedEventArgs e)
{
if ((e.NewPrice - e.LastPrice) / e.LastPrice > 0.1M)
Console.WriteLine ("Alert, 10% stock price increase!");
}
}
More information, please refer to http://www.akadia.com/services/dotnet_delegates_and_events.html
A example of delegate using System;
namespace Akadia.SimpleDelegate
{
// Delegate Specification
public class MyClass
{
// Declare a delegate that takes a single string parameter
// and has no return type.
public delegate void LogHandler(string message);
// The use of the delegate is just like calling a function directly,
// though we need to add a check to see if the delegate is null
// (that is, not pointing to a function) before calling the function.
public void Process(LogHandler logHandler)
{
if (logHandler != null)
{
logHandler("Process() begin");
}
if (logHandler != null)
{
logHandler ("Process() end");
}
}
}
// Test Application to use the defined Delegate
public class TestApplication
{
// Static Function: To which is used in the Delegate. To call the Process()
// function, we need to declare a logging function: Logger() that matches
// the signature of the delegate.
static void Logger(string s)
{
Console.WriteLine(s);
}
static void Main(string[] args)
{
MyClass myClass = new MyClass();
// Crate an instance of the delegate, pointing to the logging function.
// This delegate will then be passed to the Process() function.
MyClass.LogHandler myLogger = new MyClass.LogHandler(Logger);
myClass.Process(myLogger);
}
}
}
An application domain is a logical container that allows multiple assemblies to run within a single process but prevents them from directly accessing other assemblies’ memories. Application domains offer many of the features of a process, such as separate memory spaces and access to resources. However, application domains are more efficient than processes, enabling multiple assemblies to be run in separate application domains without the overhead of launching separate processes. Figure 8-1 shows how a single process can contain multiple application domains.
The best example of application domains in use is Internet Information Services (IIS) 5.0’s ASP.NET worker process, implemented by Aspnet_wp.exe. If 10 people visit an ASP.NET Web site simultaneously, ASP.NET will create a separate application domain for each user. Essentially, ASP.NET runs 10 separate instances of the assembly. Each instance of the assembly can store a property called userName without any concern that other instances will be able to access or overwrite the contents of the property. This same effect could be achieved by launching the same assembly in 10 separate processes, but switching between the processes would consume processor time, thus decreasing performance. Most of the time, you will rely on the existing run-time hosts to automatically create application domains for your assemblies. Examples of run-time hosts built into Microsoft Windows are ASP.NET, Internet Explorer (which creates a single application domain for all assemblies from a specific Web site), and the operating system. You can configure the behavior of these application domains by using friendly tools such as the Internet Information Services Manager and the .NET Framework Configuration tool. However, just as Aspnet_wp.exe creates application domains to isolate multiple instances of an assembly, you can create your own application domains to call assemblies with little risk that the assembly will take any action or access any resources that you have not specifically permitted. Figure 8-2 shows how an assembly can host application domains.
From book “Code leader using people tools and processes to build successful software” The trickiest part of the MVP design process is the View. It must represent all of the interaction you will have with your user, using display-agnostic data types. The View, in essence, forms your application’s contract with what is ‘‘on the glass’’ or visible to the user on their monitor. If you are following a TDD development process, your View is likely to change and evolve during the course of development, as requirements become more apparent. That should be easy to do if the proper separation between View and Presenter is maintained, although a little refactoring along the way never hurt anyone. In most languages, it is easiest to represent your View as an interface. The concrete class directly responsible for display will implement the View interface. When you write your test code, you can create another implementation of the View interface for testing purposes that has no actual user interface elements associated with it. There is one major decision to make before starting work on your View interface. Will your View expose events directly? Or will it call the Presenter to report user activity? This is often debated when starting an MVP project, and there are adherents in both camps. To put the cards on the table up front, I personally favor the former from an architectural perspective. It offers the cleanest separation between View and Presenter because the View need know nothing at all about the Presenter. It only receives data pushed to it and fires events that represent user actions. From a practical standpoint, however, there are cons. Using events may be difficult in some implementation environments. Specifically in a web application, it may be difficult for your server ‘‘page’’ to fire events, and just as difficult for your Presenter to subscribe to them. It can be much easier in such an application to provide the View with direct access to the Presenter so that user events can be reported directly as method calls. That potentially makes it easier to deal with the issue of display-agnostic data types as well. If your View’s user interface element (a button, say) fires events, and the View has to catch those events, translate from display data types to neutral data types, and then fire a second event, the code could become quite cumbersome.
Method 1 1: public interface ISurveyView 2: { 3: List<string> Users { get; set; } 4: bool Question1 { get; set; } 5: string Question2 { get; set; } 6: } 7: public class SurveyPresenter 8: { 9: private static Dictionary<ISurveyView, SurveyPresenter> _presenters = 10: new Dictionary<ISurveyView, SurveyPresenter>(); 11: private static readonly object lockObject = new object(); 12: public static SurveyPresenter Instance(ISurveyView view) 13: { 14: lock (lockObject) 15: { 16: if (!_presenters.ContainsKey(view)) 17: _presenters[view] = new SurveyPresenter(view); 18: return _presenters[view]; 19: } 20: } 21: ISurveyView _view; 22: private SurveyPresenter(ISurveyView view) 23: { 24: _view = view; 25: } 26: public void OnLoad() 27: { 28: //this is where you would go to the 29: //model for data, but we’ll cheat 30: List<string> users = new List<string>(new string[] i 31: { "Fred", "Bob", "Patty" }); 32: _view.Users = users; 33: } 34: public void SelectedIndexChanged(int index) 35: { 36: //go to the model and get answers for questions 37: //we’ll make it up 38: //this is also where the answers to the previous 39: //questions would be saved back to the model 40: _view.Question1 = true; 41: _view.Question2 = string.Format("{0} is cool!", _view.Users[index]); 42: } 43: } 44: 45: public partial class MvpMain : Form, ISurveyView 46: { 47: public MvpMain() 48: { 49: InitializeComponent(); 50: } 51: private SurveyPresenter _presenter; 52: #region ISurveyView Members 53: public List<string> Users 54: { 55: get 56: { 57: List<string> users = new List<string>(); 58: foreach (object item in userList.Items) 59: { 60: users.Add((string)item); 61: } 62: return users; 63: } 64: set 65: { 66: userList.Items.Clear(); 67: foreach (string user in value) 68: { 69: userList.Items.Add(user); 70: } 71: } 72: } 73: public bool Question1 74: { 75: get 76: { 77: if (yesButton.Checked) 78: return true; 79: else 80: return false; 81: } 82: set 83: { 84: if (value) 85: { 86: yesButton.Checked = true; 87: noButton.Checked = false; 88: } 89: else 90: { 91: yesButton.Checked = false; 92: noButton.Checked = true; 93: } 94: } 95: } 96: public string Question2 97: { 98: get 99: { 100: return question2Box.Text; 101: } 102: set 103: { 104: question2Box.Text = value; 105: } 106: } 107: #endregion 108: private void MvpMain_Load(object sender, EventArgs e) 109: { 110: _presenter = SurveyPresenter.Instance(this); 111: _presenter.OnLoad(); 112: } 113: private void userList_SelectedIndexChanged(object sender, EventArgs e) 114: { 115: _presenter.SelectedIndexChanged(userList.SelectedIndex); 116: } 117: }
Method 2
1: public interface ISurveyView 2: { 3: List<string> Users { get; set; } 4: bool Question1 { get; set; } 5: string Question2 { get; set; } 6: event SelectionChangedDelegate SelectionChanged; 7: event OnLoadDelegate OnLoad; 8: } 9: public delegate void SelectionChangedDelegate(int index); 10: public delegate void OnLoadDelegate(); 11: 12: public class SurveyPresenter 13: { 14: ISurveyView _view; 15: public SurveyPresenter(ISurveyView view) 16: { 17: _view = view; 18: _view.OnLoad += new OnLoadDelegate(OnLoad); 19: _view.SelectionChanged += new i 20: SelectionChangedDelegate(SelectedIndexChanged); 21: } 22: public void OnLoad() 23: { 24: //this is where you would go to the 25: //model for data, but we’ll cheat 26: List<string> users = new List<string>(new string[] i 27: { "Fred", "Bob", "Patty" }); 28: _view.Users = users; 29: } 30: public void SelectedIndexChanged(int index) 31: { 32: //go to the model and get answers for questions 33: //we’ll make it up 34: //This is also where the answers to the previous 35: //questions would be saved back to the model. 36: _view.Question1 = true; 37: _view.Question2 = string.Format("{0} is cool!", _view.Users[index]); 38: } 39: } 40: public partial class MvpMain : Form, ISurveyView 41: { 42: public MvpMain() 43: { 44: InitializeComponent(); 45: _presenter = new SurveyPresenter(this); 46: } 47: private SurveyPresenter _presenter; 48: #region ISurveyView Members 49: public List<string> Users 50: { 51: get 52: { 53: List<string> users = new List<string>(); 54: foreach (object item in userList.Items) 55: { 56: users.Add((string)item); 57: } 58: return users; 59: } 60: set 61: { 62: userList.Items.Clear(); 63: foreach (string user in value) 64: { 65: userList.Items.Add(user); 66: } 67: } 68: } 69: public bool Question1 70: { 71: get 72: { 73: if (yesButton.Checked) 74: return true; 75: else 76: return false; 77: } 78: set 79: { 80: if (value) 81: { 82: yesButton.Checked = true; 83: noButton.Checked = false; 84: } 85: else 86: { 87: yesButton.Checked = false; 88: noButton.Checked = true; 89: } 90: } 91: } 92: public string Question2 93: { 94: get 95: { 96: return question2Box.Text; 97: } 98: set 99: { 100: question2Box.Text = value; 101: } 102: } 103: public event OnLoadDelegate OnLoad; 104: public event SelectionChangedDelegate SelectionChanged; 105: #endregion 106: private void MvpMain_Load(object sender, EventArgs e) 107: { 108: if (OnLoad != null) 109: OnLoad(); 110: } 111: private void userList_SelectedIndexChanged(object sender, EventArgs e) 112: { 113: if (SelectionChanged != null) 114: SelectionChanged(userList.SelectedIndex); 115: } 116: }
http://msdn.microsoft.com/en-us/magazine/dd419663.aspx M-V-VM pattern The PM pattern is similar to MVP in that it separates a view from its behavior and state. The interesting part of the PM pattern is that an abstraction of a view is created, called the Presentation Model. A view, then, becomes merely a rendering of a Presentation Model. In Fowler's explanation, he shows that the Presentation Model frequently updates its View, so that the two stay in sync with each other. That synchronization logic exists as code in the Presentation Model classes. Unlike the Presenter in MVP, a ViewModel does not need a reference to a view. The view binds to properties on a ViewModel, which, in turn, exposes data contained in model objects and other state specific to the view. The bindings between view and ViewModel are simple to construct because a ViewModel object is set as the DataContext of a view. If property values in the ViewModel change, those new values automatically propagate to the view via data binding. When the user clicks a button in the View, a command on the ViewModel executes to perform the requested action. The ViewModel, never the View, performs all modifications made to the model data. The single most important aspect of WPF that makes MVVM a great pattern to use is the data binding infrastructure. By binding properties of a view to a ViewModel, you get loose coupling between the two and entirely remove the need for writing code in a ViewModel that directly updates a view. The data binding system also supports input validation, which provides a standardized way of transmitting validation errors to a view. Two other features of WPF that make this pattern so usable are data templates and the resource system. Data templates apply Views to ViewModel objects shown in the user interface. You can declare templates in XAML and let the resource system automatically locate and apply those templates for you at run time. You can learn more about binding and data templates in my July 2008 article, "Data and WPF: Customize Data Display with Data Binding and WPF." If it were not for the support for commands in WPF, the MVVM pattern would be much less powerful. In this article, I will show you how a ViewModel can expose commands to a View, thus allowing the view to consume its functionality. If you aren't familiar with commanding, I recommend that you read Brian Noyes's comprehensive article, "Advanced WPF: Understanding Routed Events and Commands in WPF," from the September 2008 issue. In addition to the WPF (and Silverlight 2) features that make MVVM a natural way to structure an application, the pattern is also popular because ViewModel classes are easy to unit test. When an application's interaction logic lives in a set of ViewModel classes, you can easily write code that tests it. In a sense, Views and unit tests are just two different types of ViewModel consumers. Having a suite of tests for an application's ViewModels provides free and fast regression testing, which helps reduce the cost of maintaining an application over time. In addition to promoting the creation of automated regression tests, the testability of ViewModel classes can assist in properly designing user interfaces that are easy to skin. When you are designing an application, you can often decide whether something should be in the view or the ViewModel by imagining that you want to write a unit test to consume the ViewModel. If you can write unit tests for the ViewModel without creating any UI objects, you can also completely skin the ViewModel because it has no dependencies on specific visual elements. Lastly, for developers who work with visual designers, using MVVM makes it much easier to create a smooth designer/developer workflow. Since a view is just an arbitrary consumer of a ViewModel, it is easy to just rip one view out and drop in a new view to render a ViewModel. This simple step allows for rapid prototyping and evaluation of user interfaces made by the designers. The development team can focus on creating robust ViewModel classes, and the design team can focus on making user-friendly Views. Connecting the output of both teams can involve little more than ensuring that the correct bindings exist in a view's XAML file. Relaying Command Logic Every view in the app has an empty codebehind file, except for the standard boilerplate code that calls InitializeComponent in the class's constructor. In fact, you could remove the views' codebehind files from the project and the application would still compile and run correctly. Despite the lack of event handling methods in the views, when the user clicks on buttons, the application reacts and satisfies the user's requests. This works because of bindings that were established on the Command property of Hyperlink, Button, and MenuItem controls displayed in the UI. Those bindings ensure that when the user clicks on the controls, ICommand objects exposed by the ViewModel execute. You can think of the command object as an adapter that makes it easy to consume a ViewModel's functionality from a view declared in XAML. When a ViewModel exposes an instance property of type ICommand, the command object typically uses that ViewModel object to get its job done. One possible implementation pattern is to create a private nested class within the ViewModel class, so that the command has access to private members of its containing ViewModel and does not pollute the namespace. That nested class implements the ICommand interface, and a reference to the containing ViewModel object is injected into its constructor. However, creating a nested class that implements ICommand for each command exposed by a ViewModel can bloat the size of the ViewModel class. More code means a greater potential for bugs. In the demo application, the RelayCommand class solves this problem. RelayCommand allows you to inject the command's logic via delegates passed into its constructor. This approach allows for terse, concise command implementation in ViewModel classes. RelayCommand is a simplified variation of the DelegateCommand found in the Microsoft Composite Application Library. Data-binding in WPF http://www.nbdtech.com/Free/WpfBinding.pdf

It is possible to set a minumum length e.g. string.format("{0,10:s}",12345"); will return a string 10 chars long with right alignment
string.format("{0,10:s}",12345"); will return a string 10 chars long with left alignment
Well-designed databases can pose a problem for developers. In the data world, a database is designed for maintainability, security, efficiency, and scalability. Its data is organized in a way that satisfies the demands of a good database administrator, yet provides challenges for the developer who needs to access that data. The EDM follows this concept, but in the Entity Framework, it moves the modeling into XML files that different programming models can use. The primary XML file contains the conceptual model, which is the actual EDM. A second XML file contains a representation of the database and a third, the mapping between the first two. At design time, all three files are bundled into a single EDMX file. The build process splits the EDMX out into the three metadata files that are used at runtime. The Entity Framework then provides a framework that allows developers to write .NET applications based on this model. As long as the EDM provides the conceptual schema, a representation of the database, a mapping file, and access to an Entity Framework-aware ADO.NET provider for the target database, the Entity Framework doesn't care what database is being targeted. It provides a common means of interacting with the database, common query syntax, and a common method for sending changes back to the database. Although the Entity Framework provides a very rich set of features for developers, its most important capabilities are the following: -
It automatically generates classes from the model and updates those classes dynamically anytime the model changes. -
It takes care of all of the database connectivity so that developers are not burdened by having to write lots of code for interacting with the database. -
It provides common query syntax for querying the model, not the database, and then translates these queries into queries that the database can understand. -
It provides a mechanism for tracking changes to the model's objects as they are being used in applications, and handles the updates to the database. In addition, because the model's classes are dynamically generated, minor changes to the model need not have a major impact on your application. Furthermore, modifying the model is much simpler than modifying your objects and the data access code on which they rely. Navigation properties are pointers to related entities. An Entity Set is a container for a collection of entities of a single type. Cleaning up the entity, property, and association names is a step that you should consider performing immediately after you create a new model with the ADO.NET Entity Data Model Wizard. In this way, as you begin to code against the model, the names of the objects will be logical. Additionally, if you change these names after you have begun to code, you will have to modify your code to reflect the changes. The EDMX file is composed of two main sections: the runtime information and the Designer information. The runtime section comprises three additional sections: one each for storage models, conceptual models, and mappings. The Designer section specifies where the various model elements should be placed visually in the Designer.
Why use the storage layer to represent the data store when you have the actual data store to work with? There are a number of reasons to use this piece of the model. The most important reason is that this provides loose coupling to the database; not every object in the database needs to be in the mode Although the entire model is contained in a single file at design time, when the project is compiled it will create three separate files—one for each of these sections. The conceptual layer is saved to a file with a .csdl extension, which stands for Conceptual Schema Definition Language. The storage layer is saved to a file with an .ssdl extension (which stands for Store Schema Definition Language) and the mapping layer is saved to a file with an .msl extension (which stands for Mapping Specification Language). These files are used at runtime, which is why they are contained in a section called edmx:Runtime in the model. Although it makes sense to have a container for an entity because you could have many contact entities to work with, how would there be a collection of associations? When you are working with entity objects, the associations between the entities are also objects. If you have a single contact with multiple addresses in memory, there would be one FK_Address_Contact association object for each relationship. Figure 2-14 shows two association objects that are used to define relationships between a single contact and two addresses. <NavigationProperty Name="Contact" Relationship="ProgrammingEFDB1Model.FK_Address_Contact" FromRole="Address" ToRole="Contact" /> The collection that is exposed in the Addresses navigation property is not a collection from the System.Collections namespace, but rather an EntityCollection. The EntityCollection is a completely unique class in the Entity Framework.
The ReferentialConstraint element serves a number of purposes. It specifies the direction of the relationship using the Principal and Dependent role elements. In the example, Address is dependent upon Contact. This also translates to defining the primary key/foreign key relationship, and we finally see the foreign key in the Address table identified: it is the ContactID. This is another piece of the puzzle of how the association and the navigation property work in the conceptual model. The ContactID property doesn't exist anywhere in the CSDL, but it is specified here in the SSDL. The MSL will show us how they are linked. The last purpose of the ReferentialConstraint element is to stipulate that a row in the Address table cannot exist without a reference to a row in the People table. If you check back at the CSDL's association in Example 2-2, you will see that this ReferentialConstraint doesn't exist. The CSDL enforces that constraint in a different way. The multiplicity for the Person entity type in that relationship is "1", not "0..1". Designer's Mapping Details window Open the model in the XML Editor again and expand the <edmx:Mappings> section; you'll see that there is one big difference in how the mapping is described under the covers. The mapping, as shown in Example 2-4, is being made from the EntitySet, not the actual entity. When you add inherited types into the mix, you may also be mapping Customers who are a type of Contact. When you map the EntitySet you cover all of the entity types in an inheritance hierarchy. Therefore, the mapping needs to be done to the EntitySet, not a specific entity. The Entity Framework automatically creates a set of classes from the model. These classes are what you will work with when you query the model, and objects will be returned that are based on these classes. Each time a change is made to the model and the model is then saved, the Entity Framework's code generator kicks in and the classes are re-created. IQueryable is a LINQ query type. At design time, the compiler recognizes the LINQ query and does its best to tell you its return type. The compiler doesn't realize that because it is a LINQ to Entities query, it will be processed by the Entity Framework and will result in an ObjectQuery. ObjectQuery implements IQueryable, so the two are very closely related. IQueryable contains metadata about the query, such as the query expression and the provider being used. ObjectQuery is an IQueryable with additional query details that are specific to Entity Framework queries. The results are described as an "enumerable type," based on the class IEnumerable, which is similar to a Collection. An IEnumerable allows you to enumerate or iterate through each item in the collection as you did in the preceding code sample (i.e., in For Each/foreach). A Collection is an enhanced IEnumerable. Whereas an IEnumerable is read-only, the more familiar Collection class allows you to perform additional actions, such as adding or removing items from the group. EntityClient: The Lowest-Level Method for Returning Streamed Data Through EDM Queries //add new entities //insert new parents and children You can divide the core functionality of Object Services into seven areas: At a high level, query processing in the Entity Framework involves translating the LINQ or Entity SQL queries into queries that the data store can process. At a lower level, it first parses your query into a command tree of LINQ or Entity SQL query operators and functions, combined with the necessary entities and properties of your model. The command tree is a format that the various providers that have been designed to work with the Entity Framework will be expecting. Next, the provider API (Oracle, SQL Server, MySQL, etc.) transforms this tree into a new expression tree composed of the provider's operators and functions and the database's tables and columns. This tree is finally passed to the database. LINQ starts its journey in the LINQ APIs and is then passed to the Object Services API. When you create a LINQ to Entities query, you are using syntax that is built into Visual Basic and C# that has enhancements that the Entity Framework has added. LINQ converts this query into a LINQ expression tree, which deconstructs the query into its common operators and functions. The LINQ expression tree is then passed to Object Services, which converts the expression tree to a command tree. Customizing Entity Data Models In object-oriented programming, when one object is a type of another object, you can use inheritance to share properties so that the properties of a base type (e.g., Contact) are exposed directly in a derived type (e.g., Customer). The EDM supports inheritance as well. The inheritance mapping used to allow Customer to derive from Contact and absorb Contact's properties is called Table per Type inheritance. Let's investigate this one first, and modify the model to simplify working with customers. Entity splitting, also referred to as vertical splitting, allows you to map a single entity to more than one table. You can use entity splitting when tables share a common key; for example, if a contact's personal and business information is stored in separate tables. You can use entity splitting as long as the primary keys in the two database tables match. (Entity splitting can solve this problem very easily, by mapping both the Customer table and the ContactPersonalInfo table to the Customer entity.) Conditional mapping places a permanent filter on an entity by defining that an entity will be mapped to data in the database under only certain conditions. Another type of inheritance that the EDM supports is Table per Hierarchy (TPH). TPH inheritance depends on conditional mapping. Rather than including only records that match the condition, the condition is used to define records as different types. Creating Complex Types to Encapsulate Sets of Properties QueryView is a mapping that allows you to override the default mapping for an entity set and return read-only data. QueryView is something you need to enter manually in the XML, and it belongs in the mapping layer. A QueryView is a query that is expressed using Entity SQL syntax. However, rather than creating the Entity SQL expression against the conceptual layer of the model, the target of the expression is the store (SSDL) layer. In other words, when you construct the Entity SQL for a QueryView, the query is written against the elements of the SSDL. Although QueryView returns read-only entities, if you want to use QueryView for some of its other benefits, you can force the entity to be updatable. Entities that are mapped with QueryView are still change-tracked by the ObjectContext. However, the Entity Framework is not able to automatically generate Insert, Update, and Delete commands for these entities. Instead, you can always create function mappings, as you did for the Payment entity. Then the entity that came from a QueryView will be affected by the call to SaveChanges. In addition to returning read-only entities, another benefit of QueryView is that you can overcome the limitations of conditional mapping. As you saw earlier, conditional mapping lets you filter using =, Is Null, and Is Not Null. Using a QueryView you can filter with a much wider variety of operators, including > and <. However, because QueryView returns read-only data, if you need the entity that results to be updatable, you can still achieve this by mapping stored procedures to the entity that results.
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.
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. Services have behaviors that control their concurrency, throttling, transactions, security, and other system semantics. Metadata in WCF refers to the information that describes precisely how to communicate with a service. Clients can request metadata from a running service to learn about their endpoints and the message formats that they require. At design time, clients send a request message defined by the WS-MetadataExchange standard and receive WSDL in return. The WSDL can be used by the client to define a proxy class and configuration file that will later be used at runtime to communicate with the service. Figure 1.4 shows this interaction. Use svcutil.exe to generate the proxy code
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
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(); }
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.
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 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.
Setting the value will force future processes in that space to use the specified .NET runtime, like: set COMPLUS_Version = v3.5
That would force everything to run in .NET 3.5. http://www.cookcomputing.com/blog/archives/000597.html It is not necessary to rebuild NUnit. I discovered that if you add the following to the relevant NUnit application config file you can run a test dll built for .NET 4.0. Under <configuration> add: <startup>
<requiredRuntime version="v4.0.20506" />
</startup>
and under <runtime> add: <loadFromRemoteSources enabled="true" />
(By Eric Evan) Chapter 1 What Is Domain-Driven Design When we begin a software project, we should focus on the domain it is operating in. The entire purpose of the software is to enhance a specific domain. How can we make the software fit harmoniously with the domain? The best way to do it is to make software a reflection of the domain. The model is our internal representation of the target domain, and it is very necessary throughout the design and the development process. There are different approaches to software design. One is the waterfall design method. This method involves a number of stages. The business experts put up a set of requirements which are communicated to the business analysts. The analysts create a model based on those requirements, and pass the results to the developers, who start coding based on what they have received. It’s a one way flow of knowledge. While this has been a traditional approach in software design, and has been used with a certain level of success over the years, it has its flaws and limits. The main problem is that there is no feedback from the analysts to the business experts or from the developers to the analysts. Another approach is the Agile methodologies, such as Extreme Programming (XP). These methodologies are a collective movement against the waterfall approach, resulting from the difficulties of trying to come up with all the requirements upfront, particularly in light of requirements change. It’s really hard to create a complete model which covers all aspects of a domain upfront. It takes a lot of thinking, and often you just cannot see all the issues involved from the beginning, nor can you foresee some of the negative side effects or mistakes of your design. Another problem Agile attempts to solve is the so called “analysis paralysis”, with team members so afraid of making any design decisions that they make no progress at all. While Agile advocates recognize the importance of design decision, they resist upfront design. Instead they employ a great deal of implementation flexibility, and through iterative development with continuous business stakeholder participation and a lot of refactoring, the development team gets to learn more about the customer domain and can better produce software that meets the customers needs. The Agile methods have their own problems and limitations; they advocate simplicity, but everybody has their own view of what that means. Also, continuous refactoring done by developers without solid design principles will produce code that is hard to understand or change. And while the waterfall approach may lead to over-engineering, the fear of overengineering may lead to another fear: the fear of doing a deep, thoroughly thought out design. Chapter 2 The Ubiquitous Language A core principle of domain-driven design is to use a language based on the model. Since the model is the common ground, the place where the software meets the domain, it is appropriate to use it as the building ground for this language. Building a language like that has a clear outcome: the model and the language are strongly interconnected with one another. A change in the language should become a change to the model. Chapter 3 Model-Driven Design A better approach is to closely relate domain modeling and design. The model should be constructed with an eye open to the software and design considerations. Developers should be included in the modeling process.
Entities: There is a category of objects which seem to have an identity, which remains the same throughout the states of the software. For these objects it is not the attributes which matter, but a thread of continuity and identity, which spans the life of a system and can extend beyond it. Such objects are called Entities. Value Objects: There are cases when we need to contain some attributes of a domain element. We are not interested in which object it is, but what attributes it has. An object that is used to describe certain aspects of a domain, and which does not have identity, is named Value Object. It is highly recommended that value objects be immutable. One golden rule is: if Value Objects are shareable, they should be immutable. Value Objects should be kept thin and simple. When a Value Object is needed by another party, it can be simply passed by value, or a copy of it can be created and given. Services: we discover that some aspects of the domain are not easily mapped to objects. But there are some actions in the domain, some verbs, which do not seem to belong to any object. They represent an important behavior of the domain, so they cannot be neglected or simply incorporated into some of the Entities or Value Objects. When such a behavior is recognized in the domain, the best practice is to declare it as a Service. Such an object does not have an internal state, and its purpose is to simply provide functionality for the domain. The assistance provided by a Service can be a significant one, and a Service can group related functionality which serves the Entities and the Value Objects. (For example, to transfer money from one account to another; should that function be in the sending account or the receiving account? It feels just as misplaced in either.) There are three characteristics of a Service: 1. The operation performed by the Service refers to a domain concept which does not naturally belong to an Entity or Value Object. 2. The operation performed refers to other objects in the domain. 3. The operation is stateless. Modules: it is necessary to organize the model into modules. Modules are used as a method of organizing related concepts and tasks in order to reduce complexity. Another reason for using modules is related to code quality. It is widely accepted that software code should have a high level of cohesion and a low level of coupling. Two of the most used are communicational cohesion and functional cohesion. Three patterns: Aggregate is a domain pattern used to define object ownership and boundaries. Factories and Repositories are two design patterns which help us deal with object creation and storage. An Aggregate is a group of associated objects which are considered as one unit with regard to data changes. The root is an Entity, and it is the only object accessible from outside. The root can hold references to any of the aggregate objects, and the other objects can hold references to each other, but an outside object can hold references only to the root object. Cluster the Entities and Value Objects into Aggregates and define boundaries around each. Choose one Entity to be the root of each Aggregate, and control all access to the objects inside the boundary through the root. Allow external objects to hold references to the root only. Transient references to internal members can be passed out for use within a single operation only. Factories are used to encapsulate the knowledge necessary for object creation, and they are especially useful to create Aggregates. When the root of the Aggregate is created, all the objects contained by the Aggregate are created along with it, and all the invariants are enforced. A Factory Method is an object method which contains and hides knowledge necessary to create another object. There are times when a Factory is not needed, and a simple constructor is enough. Use a constructor when: • The construction is not complicated. • The creation of an object does not involve the creation of others, and all the attributes needed are passed via the constructor. • The client is interested in the implementation, perhaps wants to choose the Strategy used. • The class is the type. There is no hierarchy involved, so no need to choose between a list of concrete implementations. Therefore, use a Repository, the purpose of which is to encapsulate all the logic needed to obtain object references. The overall effect is that the domain model is decoupled from the need of storing objects or their references, and accessing the underlying persistence infrastructure. Provide repositories only for Aggregate roots that actually need direct access. Keep the client focused on the model, delegating all object storage and access to the Repositories. There is a relationship between Factory and Repository. They are both patterns of the model-driven design, and they both help us to manage the life cycle of domain objects. While the Factory is concerned with the creation of objects, the Repository takes care of already existing objects. Chapter 4 Refactoring Toward Deeper Insight One of the first things we are taught about modeling is to read the business specifications and look for nouns and verbs. The nouns are converted to classes, while the verbs become methods. This is a simplification, and will lead to a shallow model. We start with a coarse, shallow model. Then we refine it and the design based on deeper knowledge about the domain, on a better understanding of the concerns. We add new concepts and abstractions to it. The design is then refactored. Each refinement adds more clarity to the design. This creates in turn the premises for a Breakthrough. To reach a Breakthrough, we need to make the implicit concepts explicit. The first way to discover implicit concepts is to listen to the language. Try to see if there is a missing concept. Another obvious way of digging out model concepts is to use domain literature. There are other concepts which are very useful when made explicit: Constraint, Process and Specification. Placing the Constraint into a separate method has the advantage of making it explicit. Processes are usually expressed in code with procedures. Simply said, a Specification is used to test an object to see if it satisfies a certain criteria. The domain layer contains business rules which are applied to Entities and Value Objects. Those rules are usually incorporated into the objects they apply to. When rule is not a simple method and spans many entities and value objects, the rule should be encapsulated into an object of its own, which becomes the Specification of the Customer, and should be kept in the domain layer. Chapter 5 Preserving Model Integrity This chapter is about large projects which require the combined efforts of multiple teams. Instead of trying to keep one big model that will fall apart later, we should consciously divide it into several models. Each model should have a clearly delimited border, and the relationships between models should be defined with precision.
A model should be small enough to be assigned to one team. Bounded Context: The main idea is to define the scope of a model, to draw up the boundaries of its context, then do the most possible to keep the model unified. Explicitly set boundaries in terms of team organization, usage within specific parts of the application, and physical manifestations such as code bases and database schemas. Keep the model strictly consistent within these bounds, but don’t be distracted or confused by issues outside. A Bounded Context is not a Module. A Bounded Context provides the logical frame inside of which the model evolves. Modules are used to organize the elements of a model, so Bounded Context encompasses the Module. A Context Map is a document which outlines the different Bounded Contexts and the relationships between them. What it is important is that everyone working on the project shares and understands it. A common practice is to define the contexts, then create modules for each context, and use a naming convention to indicate the context each module belongs to. The purpose of the Shared Kernel is to reduce duplication, but still keep two separate contexts. Core Domain and Generic Subdomain Last Chapter Keep in mind some of the pitfalls of domain modeling: 1) Stay hands-on. Modelers need to code. 2) Focus on concrete scenarios. Abstract thinking has to be anchored in concrete cases. 3) Don't try to apply DDD to everything. Draw a context map and decide on where you will make a push for DDD and where you will not. And then don't worry about it outside those boundaries. 4) Experiment a lot and expect to make lots of mistakes. Modeling is a creative process.
http://referencesource.microsoft.com/serversetup.aspx Configuring Visual Studio for Debugging Set Up Visual Studio 2008: a. Install and set up Visual Studio 2008 including any updates. Set Up the Symbols Path: a. Launch Visual Studio 2008. b. From the Tools menu, choose Options. c. In the Options dialog box, open the Debugging node and select General a. Clear 'Enable Just My Code (Managed only)' b. Check 'Enable source server support'
d. Select Symbols under Debugging. e. In the Symbol File Locations box, add the following location: http://referencesource.microsoft.com/symbols
Note: To add the Symbols path Click folder icon. f. Enter in text box under 'Cache symbols from symbol servers to this directory:' C:\Symbols\RSCC: Note : If C:\Symbols is already in use then you can chose another folder name. The folder name must be input into the text box g. Click OK. Debugging your Application a. Open your application code solution and build the solution. b. Set a break point in the code. c. Start debugging (press F5). d. EULA pops up, click Accept. e. Source code will be downloaded.
Model-View Architecture Three-Tie Architecture Model-View-Controller Architecture The preceding test is a unit test, because it tests just one isolated component: AdminController. It doesn’t rely on any real implementation of IMembersRepository, and so it doesn’t need to access any database. When you deliberately chain together a series of components and test them together, that’s an integration test.  
The BackgroundWorker class is built on top of ThreadPool and adds many features for interthread communication. The single most important issue you must deal with is exceptions in your WaitCallback, the method that does the work in the background thread. If any exceptions are thrown from that method, the system will terminate your application. It doesn't simply terminate that one background thread; it terminates the entire application. This behavior is consistent with other background thread API methods, but the difference is that QueueUserWorkItem doesn't have any built-in capability to handle reporting errors. In addition, QueueUserWorkItem does not give you any built-in methods to communicate between the background threads and the foreground thread. It doesn't provide any built-in means for you to detect completion, track progress, pause tasks, or cancel tasks. When you need those capabilities, you can turn to the BackgroundWorker component, which is built on top of the QueueUserWorkItem functionality. For most common synchronization problems, examine the Interlocked class to see whether you can use it to provide the capabilities you need. With many single operations, you can. Otherwise, your first choice is the lock() statement. Look beyond those only when you need special-purpose locking capability. Two of the most widely used locking techniques are just plain wrong when seen from that viewpoint. lock(this) and lock(TypeOf(MyType)) have the nasty effect of creating your lock object based on a publicly accessible instance. When you decide what to lock, pick a private field that's not visible to any callers. Do not lock a publicly visible object. Locking publicly visible objects requires that all developers always and forever follow the same practice, and it enables client code to easily introduce deadlock issues. No matter how it happens, the pattern is similar. Your class acquires a lock. Then, while still in the synchronized section, it invokes a method that calls code beyond your control. That client code is an open-ended set of code that may eventually trace back into your class, even on another thread. You can't do anything to prevent that open-ended set of code from doing something that might be evil. So instead, you must prevent the situation: Don't call unknown code from inside locked sections of your code. Let's summarize what you've learned about InvokeRequired. Once your controls are created, InvokeRequired is reasonably fast and always safe. However, if the target control has not been created, InvokeRequired can take much longer, and if none of the controls has been created, InvokeRequired takes a long time to give you an answer that's probably not even correct. Even though Control.InvokeRequired can be a bit expensive, it's still quite a bit cheaper than a call to Control.Invoke when it's not necessary. In WPF, some of the edge cases have been optimized and work better than they do in the Windows Forms implementation. Invoke and InvokeRequired do quite a bit of work on your behalf. All this work is required because Windows Forms controls are built on the single-threaded apartment model. That legacy behavior continues under the new WPF libraries. Underneath all the new .NET Framework code, the Win32 API and window messages are still lurking. That message passing and thread marshaling can lead to unexpected behavior. You need to understand what those methods do and work with their behavior.
Chapter 1 : Working with Generics. 1: public class EmployeeComparer : EqualityComparer<Employee> 2: { 3: public override bool Equals(Employee x, Employee y) 4: { 5: return EqualityComparer<Employee>.Default.Equals(x, y); 6: } 7: 8: public override int GetHashCode(Employee obj) 9: { 10: return EqualityComparer<Employee>.Default. 11: GetHashCode(obj); 12: } 13: }
The Default property examines the type argument, T. If the type implements IEquatable<T>, then Default returns an IEqualityComparer<T> that uses the generic interface. If not, Default returns an IEqualityComparer<T> that uses the System.Object virtual methods Equals() and GetHashCode(). In this way, EqualityComparer<T> guarantees the best implementation for you.
public delegate void Action<T>(T obj);
1: public static void EnumerateAll<T>(this IEnumerable<T> 2: theCollection, Action<T> doIt) 3: { 4: foreach (T thing in theCollection) 5: doIt(thing); 6: }
delegate bool Predicate<T>(T obj)
1: public IEnumerable<T> Test<T> (IEnumerable<T> theCollection, 2: Predicate<T> test) 3: { 4: foreach (T source in theCollection) 5: if ( test( source ) ) 6: yield return source; 7: }
public delegate void EventHandler<TEventArgs>(
object sender, TEventArgs args)
where TEventArgs: EventArgs Now you can define a event like this
public event EventHandler<MyEventArgs> OnRaiseMyEvent;Performance of boxing of unboxing 1. A new object must be allocated on the managed heap. 2. The value of the stack-based data must be transferred into that memory location. 3. When unboxed, the value stored on the heap-based object must be transferred back to the stack. 4. The now unused object on the heap will (eventually) be garbage collected.
1: public static T FirstOrDefault<T>(this IEnumerable<T> sequence, 2: Predicate<T> test) 3: { 4: foreach (T value in sequence) 5: if (test(value)) 6: return value; 7: 8: return default(T); 9: }
1: public delegate T FactoryFunc<T>();
2: public static T Factory<T>(FactoryFunc<T> makeANewT) 3: where T : new() 4: { 5: T rVal = makeANewT(); 6: if (rVal == null) 7: return new T(); 8: else 9: return rVal; 10: }
Ensure your generic classes support disposable type parameters
1: public void GetThingsDone() 2: { 3: T driver = new T(); 4: using (driver as IDisposable) 5: { 6: driver.DoWork(); 7: } 8: } If drive is a property member in the generic class, you have to implement IDisposable interface. So better to take it out from generic class.
1: public class EngineDriver<T> where T : IEngine 2: { 3: private T driver; 4: public EngineDriver(T driver) 5: { 6: this.driver = driver; 7: } 8: 9: public void GetThingsDone() 10: { 11: driver.DoWork(); 12: } 13: }
Use Delegates to define method constrains on Type Parameters When it's unwieldy to use an interface to define a constraint, you can define a method signature and a delegate type that suits your needs. Then you add an instance of that delegate to the list of the parameters of the generic method. The developers using your class can use a lambda expression to define that method, writing much less code, in a much clearer fashion. Developers using your class need to create the lambda expression that defines the method functionality they need. There's no extra code to support the syntax of interface-based constraints.
1: public static class Example 2: { 3: public static T Add<T>(T left, T right, 4: Func<T, T, T> AddFunc) 5: { 6: return AddFunc(left, right); 7: } 8: }
In the general case, any method your generic class needs to call can be replaced by a specific delegate.
It's not a good idea to create generic specializations for base classes when you intend to support the class and all its descendents. (That is to say: don’t create a same name generic method in a class as the names in base classes or derivative classes))
If a type needs type-level data members, especially data members involving the type parameter, make it a generic class. Otherwise, use generic methods. Obviously, not every generic algorithm is suited for generic methods instead of a generic class. Some simple guidelines can help you determine which to use. In two cases you must make a generic class: The first occurs when your class stores a value of one of the Type parameters as part of its internal state. (Collections are an obvious example.) The second occurs when your class implements a generic interface. Except for those two cases, you can usually create a nongeneric class and use generic methods. You'll end up with more granularity in your options for updating the algorithms in the future.
One common problem for many developers is how to create a method signature for methods that logically return more than one item. Many developers turn to ref or out parameters in those cases. But it's better to define generic tuples that can return multiple discrete values. A tuple is nothing more than a composite with n elements.
1: public struct Tuple<T1, T2> : IEquatable<Tuple<T1, T2>> 2: { 3: private readonly T1 first; 4: public T1 First 5: { 6: get { return first; } 7: } 8: 9: private readonly T2 second; 10: public T2 Second 11: { 12: get { return second; } 13: } 14: 15: public Tuple(T1 f, T2 s) 16: { 17: first = f; 18: second = s; 19: } 20: // Implementation of IEquatable<Tuple<T1, T2>> elided 21: }
1: public static Tuple<string, decimal> FindTempForNearestCity 2: (string soughtCity) 3: { 4: string city = "algorithmElided"; 5: decimal temp = decimal.MinValue; // really cold. 6: return new Tuple<string, decimal>(city, temp); 7: }
in AssemblyInfo.cs [Assembly:ScriptResource(“Calculator.Resources.Calculator.js”,”Calculator.Resources.MessageResources”,"Messages”)] When you configure an AJAX-enabled ASP.NET Web site, use only the default value of UseCookies for the cookieless attribute. Settings that use cookies encoded in the URL are not supported by the ASP.NET AJAX client script libraries. use load event to load view data, use preRender event to save view data <trace enabled=”true” pageOutput=”false” localOnly = “true” />
Custom server controls that use control state must call the RegisterRequiresControlState method on each request because registration for control state is not carried over from request to request during a postback event. It is recommended that registration occur in the Init event. System.Web.Management.WebAuditEvent for Security-related Web Events. System.Web.Management.WebErrorEvent for Web Events caused by problems with configuration or application code. aboutPostBack(): Cancel the postback that is currently running args.set_cancel(true) Cancel this postback AJAX add error handler code by pageMgr.add_endRequest(errorHandler); Raised after the response for an asynchronous postback is processed and the page is updated, or during the processing of the response if there is an error. If an error occurs, the page is not updated. Use this event to provide customized error notification to users or to log errors. Override Evaluate(HttpContext context, Control control) in custom parameter for commands. Request.ServerVariables[“REMOTE_ADDR”]
Use ScriptManager.RegisterDataItem method to send data from the server to the client during asynchronous postbacks, regardless of whether the control receiving the data is inside an UpdatePanel control. Use REgisterAsyncPOstBackControl for registers a control as a trigger for asynchronous postbacks. abortPostBack(): Cancel the postback that is currently running args_set_cancel(true): Cancel this postback The partial page postback is managed on the client-side by the PageRequestManager object. Whenever a partial page postback is initiated, the PageRequestManager object performs the following client-side actions: http://www.4guysfromrolla.com/demos/printPage.aspx?path=/articles/052808-1.aspx - The
initializeRequest event is raised - this is the first event raised during the partial postback life-cycle and affords us an opportunity to determine the HTML element that triggered the postback and cancel the postback, if needed. - The
beginRequest event is raised - this event is raised just before the request is sent to the server. The UpdateProgress control uses this event to displayed it's output. - The request is sent to the server and the page is re-rendered there.
- The
pageLoading event is raised when the server returns its response. - The
pageLoaded event is raised. This event is raised whenever the content on the page is refreshed, be it via a full page postback or a partial page postback. - The
endRequest event is raised, signalling completion of the partial page postback lifecycle. DataSourceID in <asp:BulletedList .. /> <httpHandlers> <add verb=”*" path=”*.media” validate=”false” type=”Contoso.Web.UI.MultimediaDownloader” /></httpHandlers> If the Validate property is false, ASP.NET will not attempt to load the class until the actual matching request comes, potentially delaying the error but improving the startup time. $Create shortcut method Provides a shortcut to the create method of the Sys.Component class. $get $get can be used as shorthand for the document.getElementById and element.getElementById functions. The $get shortcut function points to the Sys.UI.DomElement.getElementById JavaScript function which is defined as part of the ASP.NET AJAX client side library (which means you will need to include a ScriptManager on the page to be able to use it). $get accepts two parameters, the first is the ID of the DOM element you want to retrieve, the second is the parent element of where the search starts. The second parameter is optional and when it is not supplied defaults to the document element. $find The $find shortcut function allows you to look up an ASP.NET AJAX client side Component by it's ID. Here is a link to the $find shortcut's documentation and below is the API description. Template.InstantiateIn(control c) <asp:AsyncPostBackTrigger> and <asp:PostBackTrigger> childrenAsTriggers = true; LoadViewState :control developers can override this method to specify how a custom server control restores its view state. For more information, see ASP.NET State Management Overview. public bool HasCapability(
string delegateName,
string optionalParameter
)
DataKeyNames property in asp:DetailsView
ASP.NET session state supports several different storage options for session data. Each option is identified by a value in the SessionStateMode enumeration. The following list describes the available session state modes:
-
InProc mode, which stores session state in memory on the Web server. This is the default.
-
StateServer mode, which stores session state in a separate process called the ASP.NET state service. This ensures that session state is preserved if the Web application is restarted and also makes session state available to multiple Web servers in a Web farm.
-
SQLServer mode stores session state in a SQL Server database. This ensures that session state is preserved if the Web application is restarted and also makes session state available to multiple Web servers in a Web farm.
-
Custom mode, which enables you to specify a custom storage provider.
-
Off mode, which disables session state. http://msdn.microsoft.com/en-us/library/hkx121s4.aspx <system.web>
<deviceFilters>
<filter
name="capability"
compare="capabilityName"
argument="argument" />
<filter
name="capability"
type="className"
method="methodName" />
</deviceFilters>
</system.web>
<mobile:Image runat=server ImageURL="bw.gif">
<DeviceSpecific>
<Choice Filter="isColor" ImageURL="colorImg.gif"
AlternateText="This device cannot display the image." />
<Choice Filter="isWML11" ImageURL="myImage.wbmp" />
<Choice ImageURL="monoImage.gif" />
</DeviceSpecific>
</mobile:Image>
If the filter name is omitted, the choice is selected by default.
ScriptManager.RegisterClientScriptBlock(txtInfo, typeof(TextBox), “txtInfo_Script”, generatedScript, false);
Disable Request Validation <%@ Page validateRequest=”false” %>
a new validation control ovverrides the EvaluateIsValid method to validate the value of the related control.
HttpContext.RewritePath method redirects a request for a resource to another resource without changing the URL. S Redirects a request for a resource to a different path than the one that is indicated by the requested URL. RewritePath is used in cookieless session state to strip session IDs from URLs.
Response.Redirect will have 2 request from client browser. Server.Transfer is 1 request and will not change the path in the browser.
Use Style defined in StyleSheet control <mobile:Label ID=”MyLabel” Runat=”server” StyleReference=”MyStyleSheet:StyleA”> </mobile:Label>
<Compilation debug=”false” Batch=”true”> debug=false (optimize the performance) batch=”true” (default, ensure that during the initial request to the application, the code-behind files for the Web pages are compiled. If True, eliminates the delay caused by the compilation required when you access a file for the first time. When this attribute is set to True, ASP.NET precompiles all the uncompiled files in a batch mode, which causes an even longer delay the first time the files are compiled. However, after this initial delay, the compilation delay is eliminated on subsequent access of the file.
ProfileOnMigrateAnonymous(…) 4 types of authentication: Windows, forms, passport anonymous <deny users=”?" /> and <allow users=”*" /> FormsAuthentication.Authenticate FormsAuthentication.RedirectFromLoginPage(…) FormsAuthentication.SignOut() SeesionState in mobile website <sessionState cookieless=”true”/> <mobileControls cookielessDatadictionaryType=”System.web.Mobile.CookielessData” />
User-Agent HTTP header browserCaps relies on XML files that contain a hierarchal structure of browser definitions. The default location is at .net framework folder .\CONFIG\Browser ASP.BrowserCapsFactory.dll and HttpBroserCapabilities class Request.Browser.IsMobileDevice Search Target machine and launch conditions Pregrouped Launch Conditions MSI command-line options. The Copy Web tool doesn not merge changes within a single file; it only does complete file copies. By default, a Web Setup Project checks for an IIS version later than 4. Precompiling Web Applications. Application caching The cache object is available as a property of the Page object. absoluteExpiration and slidingExpiration onRemoveCallback CacheDependency and AggregateCacheDependency Cache.Insert(“FileCache”, “CacheContents”, new System.Web.Caching.CacheDependency(Server.MapPath(“SourceFile.xml”))) Page output caching With page output caching, ASP.NET can keep a copy of a rendered ASP.NET Web page in memory on the server. <%@ OutputCache Duration=”15” VaryByParam=”location;count” %> Use REspoinse.Cache object to do the run-time decision about output caching Response.WriteSubstitution method and Subsitution control (with MethodName property) HttpValidationStatus and Response.Cache.AddValidationCallback to invalidate the page output caching if needed. Add CacheProfile in Web.config and then reference it in page <%@ OutputCache CacheProfile=”One MInuteProfile” VaryByParam=”none” %>
The templated user control can be used to provide data that is to be rendered but allows the Web page designer to specify the format of the data. A custom Web control is a control that inherits from a WebServer control. It can be compiled into a dll and put to GAC. To create a custom version of existing control. YOu need to override the Render method and use HtmlTextWriter to output your display information. Add icon to your control [ToolboxBitmap(typeof(LabeledTextbox), “MyUserControls.LabeledTextBox.bmp”)] [DefaultProperty(“PromptText”)] public class LabeledTextBox : TextBox Use ToolboxDataAttribute to control the the Markup generated for your Custom Control. Also use [assembly: TagPrefix(“MyUserControls”, “muc”0] to change the prefix. Create a Custom Designer for a Custom Control (p693) Composite control inherits from CompositeControl class and overrides the CreateChildControls method. It has no designer screen. Page_Error event handler Server.GetLastError().Message Server.ClearError() Application_Error event handler and Server.Transfer WebConfigurationManager GetSection GetSectionGroup Asynchronous Web Page Async attribute in Page declarative Create event to start and end your asynchronous code (BeginProcessRequest, EndProcessRequest) AddOnPreRenderCompleteAsync(bh, eh) Customize hander should implement IHttpHandler IsResuable property and ProcessRequest method Request.Browser HttpBrowserCapabilities Page.Header <%@ Page Debug=”true” … %> We can define specific page for various HTTP status codes Remote Debugging Monitor (Msvsmon.exe) <%@ Page trace=”true” … /> View Trace data on a virtual page named Trace.axd Sys.Debug for AJAX client debugging ASP.NET health monitoring Local Resource file: <PageName>.aspx.<LanguageId>.resx meta:resourcekey Language preference option in Browser Global Resources <%$ Resources:LocalizedText, Greeting %> Label1.Text = Resources.LocalizedText.Greeting; Store local resources in the App_LocalResources folder To localize static text that is not part of a control, you can either convert it to a control or use the Localize control. It functions much like the Literal control. GetLocalResourceObject method and GetGlobalResourceObject method. Global resources should be stored in the App_GlobalResources folder <div style=’height: expression(document.body.clientHeight / 2); width: expression(document.body.clientWidth / 2); ‘> Culture: This object determines the results of culture-dependent functions, such as the date, number, and currency formatting. You can only define the Culture object with specific cultures that define both language and regional formatting requirements. You can not define the Culture object with neutral cultures that define only a language. UICulture This property determines which global or local resources are loaded for the page. You can define UICulture with either neutral or specific cultures. You define the Culture and UICulture properties by overriding the page’s InitializeCulture method. CultureInfo.GetCultures(CultureTypes enumeration) <globalization uiculture=”es” culture=”es-MX” /> <%@ Page uiculture=”es” culture=”es-MX” %>
The ObjectDataSource control is responsible for the lifetime of the object. It creates it and dispose of it. Therefore, the business layer code should be written in a stateless manner. Alternatively, if the business layer uses static methods, the ObjectDataSource an use these methods without creating an instance of the actual business object. DataObject and DataObjectMethod attributes. SqlDataSource can work with ODBC and OLE DB SQlDataSource.DataSourceMode SiteMapDataSource: StartingNodeUrl, ShowStartingNode, StartFromCurrentNode, StartingNodeOffset <%# Eval(“Vin”) %> <%# Eval(“Price”, “{0:C}”) %> Eval is one-way (read-only) data binding
AppendDataBoundItems in ListControl can be used to keep all items that are currently in the ListControl in addition to appending the items from the data binding. The DetailsView does not directly support sorting, whereas the GridView does.. GirdView does not automatically support inserting new records, whereas the DetailsView does support this feature. Like the DetailsView, the FormView control is used to display a single record from a data source. However, the FormView control can allows developers to create templates that define how the data should be displayed. FormView supports mutiple templates while Repeater control only support ItemTemplate. ASP.NET Web Service : Set the Web service’s generated client proxy’s Credentials property to the newly created CredentialCache object. WCF is a unifying programming model. It is meant to define a singular way for writing services and thereby unify things like Web services(.asmx), .Net Remoting, Message Queue (MSMQ), Enterprise Services (COM+), and Web Services Enhancements (WSE). It doesn’t replace these technologies on a individual basis. Instead, it provides a single programming model that you can use to take advantage of all of these items at once. With WCF, you can create a single service that can be exposed as HTTP, TCP, named pipes, and so on. You also have multiple hosting options. EndPoint = A (address) + B (binding) + C (contract) You can edit the WCF configuration information by using Service Configuration Editor (right click Web.config and choose Edit Wcf Configuration)
use SqlMetal.exe to generate DBML file and code file use XmlReaderSettings and XmlReader.Create to validate XML
DataRow has a RowState property: Detached, Added, Unchanged, Modified, Deleted Holding multiple copies of data with the DataRowVersion: Current, Default, Original, Proposed Resetting the RowState with AcceptChanges and RejectChanges Explicit changing RowState with the SetAdded and SetModified methods DataTable.Copy will copy both schema and data while DataTable.Clone will only copy schema. Importing DataRow Object into a DataTable Dataview is seeentially an index collection. DataSet contains a collection of DataTable and DataRelation bojects. XmlWriteMode.DiffGram aspnet_regiis –pef “ConnectionStrings” “C”\..\EncryptWebSite” aspnet_regiis –pdf “ConnectionStrings” “C”\..\EncryptWebSite” DataReader rdr = cmd.ExecuteReader(); DataTable publishers = new DataTable(); publishers.Load(rdr, LoadOption.Upsert) Using multiple Active Result Sets (MARS) to execute multiple commands on a connection. DBProviderFactory class ProviderList = System.Data.Common.DbProviderFactories.GetFactoryClasses(); Enumerate Data Sources DataTable sources = factory.CreateDataSourceEnumerator().GetDataSources(); Catch DBException The connection classes contain an event called InfoMessage that can be used to retrieve general and error information from the database. IAsyncResult object’s AsyncWaitHandle property was used to wait until the command finished executing. To read BLOB data, the ExecuteReader method should be executed with the CommandBehavior.SequentialAccess parameter. Also it needs to use reader.GetBytes(..) to read data. TEXTPTR function and UPDATETEXT Command
Page.ViewState property provides a dictionary object for retaining values between multiple requests for the ame page. The object is of the type StateBag. Hidden field __ViewState. The view state includes a message authentication code (MAC). Or you can use ViewStateEncryptionMode property of the Page object to protect the viewstate. Set to ControlEnableViewState to false to improve the performance on the large data input form. (data state and control state) Control state allows you to store property value information that is specific to a control. This state cannot be turned off and therefore should not be used in lieu of view state. (Override OnInit, call Page.RegisterRequiresControlState method, override the SaveControlState mthod) Hidden Fields control only store informaiton for a single page. Ti has no built-in compression, encryption, hashing, or chunking. It only works with HTTP POST. Cookie’s Path and Domain propoerty. Response.Cookies[“Info”][“FirstName”].value = “Tony”; //store multiple values in a Cookie Should validate the query string. Also you should always encode cookie or query string values using Server.HtmlEncode before displaying the value in an HTML Web page to any user. (System.Web.HttpRequestValidationException) Data Stored in the Application is not permanent. It is temporarily held in memory on the server. The ASP.NET Application Life Cycle Page209 Implemente HttpApplication events by adding a Global.asax file ASP.NET writes a cookie to the client’s machines to track their session. This cookie is called ASP.NET_SessionId and contains a random 24-byte value. Requests submit this cookie from the browser and ASP.NET maps the cookie’s value to the session on the server. <SessionState mode=”off”/> in web settings EnableSessionState=”False” in page <SessionStte cookieless=”true” …/> in web settings. Session_Start and Session_End events. Session State Mode: InProc, SateServer, SQLServer, Custom, Off Profile properties are persisted in a database on a per-user basis and not stored in memory on a server. You can define a master page to work at the folder level within your site. Referencing Master Page Properties and Controls from Content Pages. P237 Global Theme for all sites in your domain To apply a theme programmatically, set the page’s Theme property in the Page_PreInit method. Web Parts are components of predefined fuctionality that can be embedded in a Web page. Web Parts in ASP.NET require the ASP.NET personalization database (ASPNETDB) The display mode is set using the SupportedDisplayModes collection. Web Parts personalization relies on client-side cookies. It uses these cookies to look up setting sin the ASPNETDB. Shared Personalization ScriptManager and ScriptManagerProxy UpdateMOde and ChildrenAsTrigger property of UpdatePanel AsyncPostBackTrigger of UpdatePanel AsyncPostBackError event of ScriptManager abortPOstBack method of the PageRequestManager class Page.ClientScript.RegisterClientScriptBlock; RegisterClientScript; RegisterONSubmitStatement Only script registered with the ScriptManager are available for use in partial-page update scenarios. If you need your script in these scenarios you must resiger it with the Script-Manager class. Creating own Client Callbacks Server-Side 1. Implement the System.Web.UI,ICallbackEventHandler for your ASP.NET page. 2. Implement the RaiseCallbackEvent method 3. Implement the GetCallbackResult method In Page_Load 1. Register the name of the client-side function by using Page.ClientScript.GetCallbackEventReference 2. Define a function used by the client to call the server and register it by using RegisterClientScriptBlock Loaded script: Call the notifyScriptLoaded method of the Sys.Application object to tell the AJAX library once you have finished loading your script. AJAX Client-Side Life Cycle Events: Application: Init, load, unload, disposing PageRequestManager: initialiizeRequest, beginRequest, pageLoading, pageLoaded, endRequest When working with JavaScript files in the code editor, you can add a reference to the AJAX Library. This will ensure your coding gets IntelliSense for the library. This is similar to the using statement in c# and the imports statement in Visual Basic. You embed this reference in a comment at the top of your .js file. The following shows a example: /// <reference anme=”MicrosoftAjax.js” />
View state is not stored by the server. It is saved into the page’s view state and sent in the page’s response back to the user. Page Life Cycle Events: PreInit->Init->InitComplete->Load->Control(PostBack) events->LoadComplete->PreRender->SaveStateComplete->Render->Unload HTML vs Web Server Control DIV tag’s InnerText and InnerHtml property Any postponed event (an event triggered by a user that does not cause an automatic PostBack) executes before the actual event that caused the PostBack. AutoPostBack property Control c = FindControl(“lblMessage”); Use HttpUtility.HtmlEncode or the Server.HtmlEncode method to encode the untrusted data prior to placing it the Text Property of the controls. Button control can be rendered as a submit button or a command button. Command button is one of a set of buttons that work together as a group, such as a toolbar. When clicked, Command event is called on the server. This event is passed an instance of CommandEVentArgs as a parameter. Use the CheckBoxList control to create group of CheckBox controls. Same to RadioButtonList Label is rendered as a <span> tag. Literal control is not inherited from WebControl and mainly used to add text to the output of the page dynamically (from server) Literal Mode Property: PassThrough, Encode, Transform The Image control does not have a Click event. In situations in which a click event is necessary, you can use ImageButton or ImageMap instead. ImageMap allows you to define regions or “hot spots” that cause a PostBack. If you set the HOtSpotMode on the HotSpot and the ImageMap, the HotSpot takes precedence. Use Calendar control to show the schedule. (DayRender event) Panel control generates a <div> element inside the browser. MultiView and View Controls are meant to work together. ACtiveViewIndex property and SetActiveView method. (Usually we use command buttons for navigation) Xml control is used to display the contents of an XML document with Extensible Stylesheet Language(SXL) transform. Validators property of Page class. ASP.NET calls the Validate method automatically after the page’s Load event handler method executes. You need to check the IsValid property in every event handler to determine whether the code should run; EnableClientScript property and SetFocusOnError Set control’s CausesValidation to false to prevent Client-Side Validation. ValidationGroup Custom Client-Side Validation : function ClientFunctionName(source, arguments) Attach the client-side function to a CustomValidator by setting the ClientFunctionName property of the CustomValidator control to the name of your validation function Custom Server-Side Validation: Override its ServerValidate event(source, args) Page Navigation: Client-side navigation;Cross-page posting;Client-side browser redirect;Server-side transfer Cross-page posting: Set PostBackUrl, Page, use PreviousPage property, use PreviousPage.FindControl method or access strongly typed data directly. Client-Side Browser Redirect: Use Response.Redirect (the redirect is accomplished by sending a Http response code of (302) to the browser along with the URL) (URL in address bar will change) (Can not access the PreviousPage property) Server-Side Transfer: Page.Server.Transfer method. It Tranfer the entire context of a Web page over to another page (URL in address bar will not change) (You can access the PreviousPage property)
HTTP Verbs: OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT, DEBUG LOCK AND UNLOCK (ONLY WITH DAV) DAV: Disributed Authoring and Versioning. It is a set of extensions to HTTP/1.1 HTTP/1.1 200 ok 200 is the status code. 1xx: Informational 2xx: Success 3xx: Redirect Command 4xx: Client Error 5xx: Server Error Get and Post: Get append the form data to the URL as part of the query string. Post put the form data into the message body of the request. Assemblies in the Bin folder are automatically referenced in web application. ASPX page = Page directives + Code + Page Layout Dynamically compilation and pre-compilation (only in 2008) FTP passive and active mode. (passive is more firewall friendly) .SUO file: User option file. It is best to keep the solution files in an independent folder. Root Default Web.config file is located in the same directory as the Machine.config file. WSAT: Web Site Administration Tool
PrintDocument.BeginPrint event, set the position of the streamToPrint.BaseStream property to 0. chkIsManager.DataBindings.Add(“Checked”, ds, “Users.IsManager); DataRowVersion.Original Thread.Enter and Exit to lock object for reading and writing. SuspendLayout and ResumeLayout http://msdn.microsoft.com/en-us/library/system.windows.forms.control.suspendlayout.aspx XmlReader is more timeefficient than XmlDocument and Linq to XML SafePrinting (PrintingPermissionLevel enumerations) Call the endInvoke method in callback method
Transaction Scope Enumerate SQL Data sources. CommandBehavior.SequentialAccess as a parameter for ExecuteReader method to support stream reading. check Nested relation between two tables to make XML serialization results nested PrintControllerWithStatusDialog QueryPageSettings event PrintDocument allows you to override the OnPrintPage method that can add a water mark on each page. The PrintController class will allow you to control the printing process but cannot force secure watermarks. Basically, Assert gives some additional rights to untrusted code, while Demand requires that everyone in the call stack must have the required permissions. CurrentUICulture only identifies the culture to be used by a resource manager. The WorkerReportsProgress property should be set when ReportProgress is wanted to report the progress. Event-based Asynchronous Pattern http://msdn.microsoft.com/en-us/library/wewwczdw.aspx A class that supports the Event-based Asynchronous Pattern will have one or more methods named MethodNameAsync. These methods may mirror synchronous versions, which perform the same operation on the current thread. The class may also have a MethodNameCompleted event and it may have a MethodNameAsyncCancel (or simply CancelAsync) method. The UserPaint flag shows that the control paints itself than having the operating system performs the job. If the flag is not set, the OnPaint method is not called. ClickOnce Dynamic loading assembly: You should handle the AssemblyResolve event of the AppDomain class and call the DownLoadFileGroup method of the ApplicationDeployment class. Mage.exe is used to change the GradeBook.application settings. It also helps to manage a published application. x86 setting allows a package to be installed on 32-bit and 64-bit computer.
From the Amazon: The authors have only added content for two new topics: 24 pages on LINQ and 3 pages on hosting a WPF control by using ElementHost. But they have missed out some important deployment-related topics that appear on the exam: 1) Install a Windows Presentation Foundation (WPF) browser application by using ClickOnce 2) Install a Visual Studio Tools for Office (VSTO) application by using ClickOnce 3) Configure and work with Windows Vista User Account Control (UAC) by using ClickOnce deployments 4) Set appropriate security permissions to deploy the application. This objective may include but is not limited to: elevated permissions 5) Configure Trusted Application deployments 6) Configure security features in an application. This objective may include but is not limited to: Configure code access security, configure the application to work with UAC, configure Windows manipulation permissions, configure appropriate file access permissions for the application, control printing security for the application
Accessibility Flexibility;Choice of input and output method;Consistency;Compatibility with accessibility aids
PropertyGrid.SelectedObject = Button1; PropertyGrid.PropertySort = PropertySort.Categorized; //Alphabetical, Categorized, CategorizedAlphabetical, NoSort
ToolStripProgressbar and ToolStripoStatusLabel ToolTip.SetToolTip(Button1, “text”); Set CauseValidation property; Add handler to Validating event; call ErrorProvider1.SetError(TextBox1, “”); View Errors in a DataSet with the ErrorProvider Component. errorProvider1.DataSource = DataSet1; errorProvider1.DataMember = “Customers”; errorProvider1.ContainerControl = this; DataTable.Rows[5].SetColumnError(“Name”, “The data is incorrect”); this.BindingContext[DataTable1].Position = 5; System.Media.SoundPlayer play System.Media.SystemSound.Beep.Play()
Bind a setting to a property at design time. Application scope settings (read-only in run time) and user scope settings Properties.Settings.Default.TitleSetting = “This is the new Title”; Properties.Settings.Default.Save(); BAckGroundWorker.RunWorkAsync([parameter]) WorkerReportProgress = true; //set handler to ProgressChangedEvent, then call backgroundworker1.ReportProgress(…) Asynchronous Method Create a delegate, then you can call del.Invoke([Parameter]); For asynchoronous call, we can call the methods BeginInvoke and EndInvoke P613 del = (myDelegate)result.AsyncState; ResultString = del.EndInvoke(result); SyncRoot of ArrayList Control.InvokeRequired and ControlInvoke Form1.TransparentKey = Color.Red myUserControl.BackColor = Color.Red; ToolboxBitmap Attribute Custom Controls inherits from Control class. You can create the UI by implementating the OnPaint method. Use ElementHost control to add WPF control to Windows Forms project WPFProject.UserControl1 aWPFcontrol = new WPFProject.UserControl1; ElementHost1.Child = aWPFcontrol; Configureing REquired Permissions for a ClickOnce Application Override the Install, Rollback, Uninstall, and Commit InstallException cases the installation to be rolled back without leaving any lasting effect on the system
XML Document Object Model (DOM) XMLDocument class exposes an XML Document as a hierachical collection of XmlNode objects. XMLdocument.Load(parameter)// The parameter must be a String, Stream, TextWriter, or XmlWriter XMLNode.Value XMLNode.InnerXml XMLNode.ReplaceChild XMLElement.SetAttribute(p1, p2) XmlWriter awriter = Xml.XmlWriter.Create(“myFile.xml”); aDocument.WriteTo(aWriter); //equals to Write OuterXml aDocument.WriteContentTo(aWriter); //equals to write innerXml XmlDeclaration PrintDocument Component PrintPage Event Tracking Page number and set HasMorePages property PrintDocument.EndPrint event PrintPermission class and PrintingPermissionLevel enumerations. //add to class as attribute PrintPreviewControl Drag-Drop MouseEnter(call DoDragDrop) –> DragEnter(Set effect) –>DragDrop (get data) AllowDrop property e.Data.GetDataPresent e.Data.GetData TreeView: ItemDrag –>DragEnter->DragDrop Globalization refers to formatting existing data in formats appropriate for the current culture setting. Localization, on the other hand, refers to retrieving appropriate data based on the culture. System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo(“fr-CA”); Set the UI culture in construction function of main form or in Application’s main function. Localizable property and Language (only design time) property RightToLeft proerty and RightToLeftLayout Property Currentculture and CurrentUICulture Set IsMDIContainer property to True in Parent Form aChildForm.MdiParent = this aForm = parentForm.ActiveMDIChild LayoutMdi (enumerations) List child form items in menu by set MdiWindowListItem property to the menu item
AutoIncrement, AutoIncrementSeed and AutoIncrementStep property ForeignKeyConstrain class and UniqueConstrain class Use CommandBuilder to automatically generate INSERT, UPDATE, and DELETE statements for the adapter SqlDataAdapter adapter1 = new SqlDataAdapter(“Select *….); SqlCommandBuilder commands = new SqlCommandBuilder(adapter1); MissingMappingAction and MIssingSchemaAction Enumeration Batch Updates with DataAdapter: Set UpdateBatchSize. 0 is the default that means largest batch size the server can process. When performing batch updates, the DataAdapter fires a RowUpdating event for each row being updated but fires only one RowUpdated event for the entire batch. RowState enumberations: Unchanged, Added, Modified, Deleted, Detached DataRow.RowError is assigned, the DataTable.HasErrors property is authmatically set to True. Synchronizing a DataSet with an XmlDataDocument XmlDataDocument NwDataDocument = new XmlDataDocument(NorthwindDataset); Then pass an XPath query to the XMLDataDocument.DocumentElement.SelectNodes method. The SelectNodes method returns the data as a collection of Xml.Xmlnode (Xml.XmlNodeList)
DataView DataView customerDataView = Northwind.Customers.DefaultView; CustomerDataView.Sort = “ContactName DESC”; int FoundRow = CustomersDataView.Find(“FADF”); //FoundRow is index OrderDataView = CustomersDataRowView.CreateChildView(“FK_Orders_Customers”); //RataRelation ListChanged event of DataView Using DataViewManager as the databind source to manage several tables. DataViewManager dvm = new DataViewManager(NorthwindDataSet1); OrderDataGridView.DataSource = dvm.DataViewSettings(“Customers”).Table BindingSource customersBindingSource = new BindingSource(northwindDataSet1, “Customers”); Validating input in DataGridView by handling the DataGridView.CellValidating event handle the CellPainting event to customize the DataGridView XmlTextReader, XmlNodeReader both are implementations of the XmlReader class XmlValidatingReader aValReader = new XmlValidatingReader(aReader); DTD document type definition XSD extensible schema definition SDR XML-Data Reduced (XDR) schema ValidationEvent XmlReaderSettings.ValidationType and ValidationEventHandler XmlWriter.Create(parameter, [XmlWriterSettings])//parameter can be a stream, a file, stringBuilder, TextWriter, or XmlWriter
FlowLayoutPanel Method: SetFlowBreak(Control, bool) and GetFlowBreak Document Outline Window TextBox Property Lines is a string array representing the individual lines of the text box. MaskedTextBox ListBox.Sorted = true ListView DomainUpDown UseMnemonic Property ToolStrip ToolStripItem ToolStripContainer ToolStripManager.Merge Connection Events: StateChanged and InfoMessage SqlException SqlDataSourceEnumberator.Instance.GetDataSource() Persist Security Information should be false in the connection string to ensure that the credentials used to open the connection are discarded and not stored where someone might be able to retrieve them. Use protected-configuration provider to encrypt configuration data. ConfigurationSection connstrings = config.ConnectionStrings; connstrings.SectionInformation.ProtectSection(provider); connstrings.sectionInformation.ForceSave = true; config.Save(configurationSaveMode.Full); SqlCommand.ExecuteXMLReader(); //SqlCommand only Asynchoronous SQL Command Call nextResult to get result from multiple SQL Statement execution Byte[] BLOB; BLOB = fileReader.ReadBytes((int)(file.Length)); SqlBulkCopy (with optional Transaction) SqlBulkCopy BulkCopier = new SqlBulkCopy(DestinationConnection, UserInternalTransaction); BuilkCopier.DestinationTableName=”XXX”; BulkCopier.WriteToServer(reader); (Bulk Insert Statement only for SQL) data from .bcp file string BulkInsertStatement = “BULK INSERT CustomerHIstory FROM ‘c:\\NorthwindCustomers.txt’”; Isolation Level of a Transaction Enlist Transaction to a distrubuted transaction NorthWindConnection.EnlistTRansaction(activeTransaction); LINQ queries against any .Net Framework collection that implements IEnumberable, IEnumerable<T> or inherited from IEnumerable<T> DataRow.GetParentRow(string foreignkey) DataRow.GetChildRows(string foreignkey) DataSet.Merge(sourcedataset, IfPreserveChanges, MIssingSchemaAction) DataSet.Copy()
.Net targeting http://msdn.microsoft.com/en-us/library/9w519wzk.aspx BitVector32 constructor takes takes an Int32 parameter. Going back to Microprocessor basics, all modern processors stores negative number in 2's complement notation. 0 is stored as "0...(32 zeroes)" in binary 1 is stored as "00000.....1" as a 32 bit binary -1 is stored as "1111 ...1" as a 32 bit binary Search on 2's complement and read on for further clarity. ArrayList.Synchronized method IDeserializationCallback and OnDeserialization Method Process.GetProcessesByName (String, processName, String computerName) Process.GetProcesses() GetProcessesById(Int32, [string]), there is no GetProcesses(string name) CLR (Unit of isolation) is AppDomain DEVPATH http://msdn.microsoft.com/en-us/library/cskzh7h6%28VS.71%29.aspx [XMLArrayItem(Type = typeof(yourclass))] http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlarrayitemattribute.aspx Evidence evidence = new Evidence(); evidence.AddHost(new Zone(SecurityZone.Intranet)); CompareInfo:Implements a set of methods for culture-sensitive string comparisons. http://msdn.microsoft.com/en-us/library/system.globalization.compareinfo.aspx Assembly.LoadFrom(Path) Assembly.Load(AssemblyName) HashAlgorithm instance.ComputeHash() Exposing .net class to Com needs non-parameter constructor in .Net class? Change security settings of a file ObjectSecurity.SetAccessRuleProtection(isProtected, preserveInheritance) ServiceController.MachineName property (You can use the ServiceController class to connect to and control the behavior of existing services. When you create an instance of the ServiceController class, you set its properties so it interacts with a specific Windows service. You can then use the class to start, stop, and otherwise manipulate the service.) BufferedStream ManagementObjectSearcher: syntax is like PL-SQL
http://social.msdn.microsoft.com/Forums/en-US/adodotnetentityframework/thread/74dac8d1-6fa7-4d23-a740-738f9c707d28 “ This exception says that you are deleting a relationship but not the entity association with that relationship. Sometimes that's OK, but if your relationship is a 1-to-many (rather than 0..1-to-many) that means the entities on the many side cannot exist independent of the entity on the one side. In your case, you are deleting the relationship between a Link and a WebPage, but the Link cannot exist on its own independent of the WebPage. Configuring a cascade delete doesn't make it so that deleting the relationship will delete the entity--what it does is make it so that deleting the entity on one side of a relationship will cause the entity on the other side to be deleted. So that doesn't fix the issue in this case. The fix in this case would be to change the line at the end of FromBusinessObject from this.Links.Remove(entity); to context.DeleteObject(entity); Of course that also means you will need to pass the context to the FromBusinessObject method or something like that... This change will cause the link entity to be deleted which implicitly deletes any relationships it participates in rather than just deleting the relationship between the page and the link. “ 1: partial void OnContextCreated() 2: { 3: this.SavingChanges += new EventHandler(onSavingChanges); 4: } 5: 6: private static void onSavingChanges(object sender, EventArgs e) 7: { 8: foreach (ObjectStateEntry entry in ((ObjectContext)sender).ObjectStateManager.GetObjectStateEntries(EntityState.Deleted)) 9: { 10: if (entry.IsRelationship) 11: { 12: AssociationType asso = (AssociationType)entry.EntitySet.ElementType; 13: 14: if (asso.RelationshipEndMembers[0].RelationshipMultiplicity == RelationshipMultiplicity.One && asso.RelationshipEndMembers[1].RelationshipMultiplicity == RelationshipMultiplicity.Many) 15: { 16: object o = entry.OriginalValues[1]; 17: object ob = ((ObjectContext)sender).GetObjectByKey((EntityKey)o); 18: ((ObjectContext)sender).DeleteObject(ob); 19: } 20: else if (asso.RelationshipEndMembers[1].RelationshipMultiplicity == RelationshipMultiplicity.One && asso.RelationshipEndMembers[0].RelationshipMultiplicity == RelationshipMultiplicity.Many) 21: { 22: object o = entry.OriginalValues[0]; 23: object ob = ((ObjectContext)sender).GetObjectByKey((EntityKey)o); 24: ((ObjectContext)sender).DeleteObject(ob); 25: } 26: } 27: } 28: }
http://support.microsoft.com/kb/257757 Alternatives to server-side Automation The Open XML file formats are a public standard. To obtain a copy of the specification, visit the following Web site: http://www.ecma-international.org/publications/standards/Ecma-376.htm (http://www.ecma-international.org/publications/standards/Ecma-376.htm) Microsoft provides an SDK for manipulating Open XML file formats from the .NET 3.x Framework. For more information about the SDK and about how to use the SDK to create or edit Open XML files, visit the following Microsoft Developer Network (MSDN) Web sites: Open XML SDK Documentation http://msdn.microsoft.com/en-us/library/bb226703.aspx (http://msdn.microsoft.com/en-us/library/bb226703.aspx) How to: Manipulate Office Open XML Formats Documents http://msdn.microsoft.com/en-us/library/aa982683.aspx (http://msdn.microsoft.com/en-us/library/aa982683.aspx) Manipulating Word 2007 Files with the Open XML Object Model (Part 1 of 3) http://msdn.microsoft.com/en-us/library/bb656295.aspx (http://msdn.microsoft.com/en-us/library/bb656295.aspx) Manipulating Word 2007 Files with the Open XML Object Model (Part 2 of 3) http://msdn.microsoft.com/en-us/library/bb739835.aspx (http://msdn.microsoft.com/en-us/library/bb739835.aspx) Manipulating Word 2007 Files with the Open XML Object Model (Part 3 of 3) http://msdn.microsoft.com/en-us/library/bb727374.aspx (http://msdn.microsoft.com/en-us/library/bb727374.aspx) Manipulating Excel 2007 and PowerPoint 2007 Files with the Open XML Object Model (Part 1 of 2) http://msdn.microsoft.com/en-us/library/bb739834.aspx (http://msdn.microsoft.com/en-us/library/bb739834.aspx) Manipulating Excel 2007 and PowerPoint 2007 Files with the Open XML Object Model (Part 2 of 2) http://msdn.microsoft.com/en-us/library/bb727373.aspx (http://msdn.microsoft.com/en-us/library/bb727373.aspx) Building Server-Side Document Generation Solutions Using the Open XML Object Model (Part 1 of 2) http://msdn2.microsoft.com/en-us/library/bb735940.aspx (http://msdn2.microsoft.com/en-us/library/bb735940.aspx) Building Server-Side Document Generation Solutions Using the Open XML Object Model (Part 2 of 2) http://msdn2.microsoft.com/en-us/library/bb735939.aspx (http://msdn2.microsoft.com/en-us/library/bb735939.aspx) For more information about using Open XML from the .NET 3.0 Framework and for an example, click the following article numbers to view the articles in the Microsoft Knowledge Base: 932921 (http://support.microsoft.com/kb/932921/ ) How to use components of the .NET Framework 3.0 to create and then to stream an Office Word 2007 document and an Office Excel 2007 workbook to a client computer 931866 (http://support.microsoft.com/kb/931866/ ) How to use the Office XML file format and the packaging components from the .NET Framework 3.0 to create a simple Excel 2007 workbook or a simple Word 2007 document Users who are running earlier versions of Office (such as Office 2000, Office XP, and Office 2003) can view and edit Open XML files if the users install the free compatibility pack download from the Microsoft Web site. To download and install the compatibility pack, visit the following Microsoft Web site: Microsoft Office Compatibility Pack for Word, Excel, and PowerPoint 2007 file formats http://office.microsoft.com/en-us/products/HA101686761033.aspx (http://office.microsoft.com/en-us/products/HA101686761033.aspx) When you stream Open XML files from ASP or from ASP.NET, you must provide the correct Multipurpose Internet Mail Extension (MIME) type for the content that you stream. For a listing of the MIME types for Office 2007 files, visit the following Web site: http://blogs.msdn.com/vsofficedeveloper/pages/Office-2007-Open-XML-MIME-Types.aspx (http://blogs.msdn.com/vsofficedeveloper/pages/Office-2007-Open-XML-MIME-Types.aspx) Documentation: · Open XML Markup Language Reference (ECMA specification) http://www.ecma-international.org/publications/files/ECMA-ST/Office%20Open%20XML%201st%20edition%20Part%204%20(PDF).zip · ECMA-376 Implementer notes for Office 2007 SP2 (will help ECMA-376 implementers interoperate with Office by explaining, among other things, Office’s support for optional features, range restrictions for attribute values, and how Office’s functionality maps to Open XML constructs. http://www.documentinteropinitiative.org/implnotes/ecma-376/ec354bc5-2931-46ca-b117-cc8ba7e5a33c.aspx · MSDN Library (including introduction of Open XML SDK and How-To articles) http://msdn.microsoft.com/en-us/library/bb448854(office.14).aspx MSDN Open XML File Format Center http://msdn.microsoft.com/en-us/office/bb265236.aspx Forums: · Connect Site (including A=articles, downloadable sample code, customer feedbacks, surveys, etc. Need to firstly register as a member, then choose the “Open Xml SDK” group to join in) https://connect.microsoft.com/site/sitehome.aspx?SiteID=589 · MSDN forum (a forum for worldwide customers to submit any questions , feedbacks and requirements) http://social.msdn.microsoft.com/Forums/en-US/oxmlsdk/threads/ · Open XML Developer forum (a forum for worldwide customers to submit any questions , feedbacks and requirements) http://openxmldeveloper.org/forums/default.aspx Tutorial Book: · e-book: Open Xml Explained (very detail introduction of Open Xml Format SDK concepts and markup explanation) http://openxmldeveloper.org/articles/1970.aspx Blog Posts: · Brian Jone’s Blog (very useful articles about Open Xml Format SDK basic concepts and sample code of real-world solutions) http://blogs.msdn.com/brian_jones/ · Eric White’s Blog (very useful articles about file format, Open Xml SDK related technologies and useful tools) http://blogs.msdn.com/ericwhite/default.aspx · Erika Ehrli’s Blog http://blogs.msdn.com/erikaehrli/default.aspx · Doug Mahuge http://blogs.msdn.com/dmahugh/
http://msdn.microsoft.com/en-us/library/aa720433(VS.71).aspx Programming with the .NET Framework This section describes the programming essentials you need to build .NET applications, from creating assemblies from your code to securing your application. Many of the fundamentals covered in this section are used to create any application using the .NET Framework. This section provides conceptual information about key programming concepts, as well as code samples and detailed explanations. In This Section - Accessing Data with ADO.NET
- Describes the ADO.NET architecture and how to use the ADO.NET classes to manage application data and interact with data sources, including Microsoft SQL Server, OLE DB data sources, and XML.
- Accessing Objects in Other Application Domains Using .NET Remoting
- Describes the various communications methods available in the .NET Framework for remote communications.
- Accessing the Internet
- Shows how to use Internet access classes to implement both Web- and Internet-based applications.
- Creating Active Directory Components
- Discusses using Active Directory Services Interfaces (ADSI).
- Creating Messaging Components
- Discusses how to build complex messaging into your applications.
- Creating System Monitoring Components
- Discusses how to use performance counters and event logs with your application.
- Creating Timer-Based Server Tasks
- Discusses how to create events that are raised on reoccurring intervals.
- Developing Components
- Provides an overview of component programming and explains how those concepts work with the .NET Framework.
- Developing World-Ready Applications
- Explains the extensive support the .NET Framework provides for developing international applications.
- Discovering Type Information at Run Time
- Explains how to get access to type information at run time by using reflection.
- Drawing and Editing Images
- Discusses using GDI+ with the .NET Framework.
- Emitting Dynamic Assemblies
- Describes the set of managed types in the System.Reflection.Emit namespace.
- Employing XML in the .NET Framework
- Provides an overview to a comprehensive and integrated set of classes that work with XML documents and data in the .NET Framework.
- Extending Metadata Using Attributes
- Describes how you can use attributes to customize metadata.
- Generating and Compiling Source Code Dynamically in Multiple Languages
- Explains the .NET Framework SDK mechanism called the Code Document Object Model (CodeDOM), which enables the output of source code in multiple programming languages.
- Grouping Data in Collections
- Discusses the various collection types available in the .NET Framework, including stacks, queues, lists, arrays, and structs.
- Handling and Raising Events
- Provides an overview of the event model in the .NET Framework.
- Handling and Throwing Exceptions
- Describes error handling provided by the .NET Framework and the fundamentals of handling exceptions.
- Hosting the Common Language Runtime
- Explains the concept of a runtime host, which loads the runtime into a process, creates the application domain within the process, and loads and executes user code.
- Including Asynchronous Calls
- Discusses asynchronous programming features in the .NET Framework.
- Interoperating with Unmanaged Code
- Describes interoperability services provided by the common language runtime.
- Managing Applications Using WMI
- Explains how to create applications using Windows Management Instrumentation (WMI), which provides a rich set of system management services built into the Microsoft® Windows® operating systems.
- Processing Transactions
- Discusses the .NET Framework support for transactions.
- Programming for Garbage Collection
- Discusses how the garbage collector manages memory and how you can program to use memory more efficiently.
- Programming with Application Domains and Assemblies
- Describes how to create and work with assemblies and application domains.
- Securing Applications
- Describes .NET Framework code access security, role-based security, security policy, and security tools.
- Serializing Objects
- Discusses XML serialization.
- Threading
- Explains the runtime support for threading and how to program using various synchronization techniques.
- Using Side-by-Side Execution
- Explains what side-by-side execution is and how you can use it to run multiple copies of an application, a component, or the entire runtime.
- Working With Base Types
- Discusses formatting and parsing base data types and using regular expressions to process text.
- Working with I/O
- Explains how you can perform synchronous and asynchronous file and data stream access, and how to use to isolated storage.
- Writing Serviced Components
- Describes how to configure and register serviced components to access COM+ services.
Related Topics - Creating ASP.NET Web Applications
- Discusses how to create and optimize ASP.NET Web applications.
- Creating Windows Forms Applications
- Describes how to create Windows Forms and Windows controls applications.
- Building Console Applications
- Discusses how to create console-based .NET applications.
Sachabarber’s extension method http://sachabarber.net/?p=411 (Five start solution) http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/82c6451d-d37b-4380-aa11-d75c2f759ba7/ XAML:
<Window x:Class="WindowsApplication1.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Testing BackgroundWorker" Height="300" Width="300"
>
<Grid>
<Button HorizontalAlignment="Left" Margin="8,25,0,0" x:Name="_btnStart" VerticalAlignment="Top" Width="87" Height="27" Content="Start" Click="StartWorker"/>
<Button IsEnabled="False" Margin="99,25,102,0" x:Name="_btnCancel" VerticalAlignment="Top" Height="27" Content="Cancel" Click="CancelWorker"/>
<ProgressBar Margin="8,0,8,107" x:Name="_progressBar" VerticalAlignment="Bottom" Height="23" Maximum="10"/>
</Grid>
</Window> C#:
using System.ComponentModel;
using System.Threading;
using System.Windows;
namespace WindowsApplication1
{
/// <summary>
/// Interaction logic for Window1.xaml
/// </summary>
public partial class Window1 : System.Windows.Window
{
private BackgroundWorker _worker;
public Window1()
{
InitializeComponent();
}
private void StartWorker(object sender, RoutedEventArgs e)
{
int N = 10;
_worker = new BackgroundWorker();
_worker.WorkerReportsProgress = true;
_worker.WorkerSupportsCancellation = true;
_worker.DoWork += delegate(object s, DoWorkEventArgs args)
{
BackgroundWorker worker = s as BackgroundWorker;
for (int i = 0; i < N; i++)
{
if (worker.CancellationPending)
{
args.Cancel = true;
return;
}
Thread.Sleep(1000);
worker.ReportProgress(i + 1);
}
};
_worker.ProgressChanged += delegate(object s, ProgressChangedEventArgs args)
{
_progressBar.Value = args.ProgressPercentage;
};
_worker.RunWorkerCompleted += delegate(object s, RunWorkerCompletedEventArgs args)
{
_btnStart.IsEnabled = true;
_btnCancel.IsEnabled = false;
_progressBar.Value = 0;
};
_worker.RunWorkerAsync();
_btnStart.IsEnabled = false;
_btnCancel.IsEnabled = true;
}
private void CancelWorker(object sender, RoutedEventArgs e)
{
_worker.CancelAsync();
}
}
}
http://blog.schuager.com/2009/01/line-count-in-visual-studio.html Select Edit -> Find & Replace -> Find in files... or just press CTRL+SHIFT+F Check Use and select Regular expressions. Type the following as the text to find: ^~(:Wh@//.+)~(:Wh@\{:Wh@)~(:Wh@\}:Wh@)~(:Wh@/#).+ Select where you want to do the search/count: file, project or solution.
From http://www.codethinked.com/ Simone Chiaretta’s CodeClimber - A good friend, and a better blogger. Simone is an ASP.NET MVP and is co-writing the book “Beginning ASP.NET MVC 1.0” by Wrox. Simone blogs about all sorts of different ASP.NET MVC topics, and will certainly bring tons more content once he finishes his book. He is also an active developer on the Subtext project. Stephen Walther - Stephen is a Senior Program Manager at Microsoft where he creates much of the tutorial content on the www.asp.net/mvc website. Somehow he also finds time to put up tons of helpful posts on his personal blog. He is also authoring the book “ASP.NET MVC Framework Unleashed” by Sams. Kazi Manzur Rashid - Kazi is surprisingly the only person on this list who isn’t writing a book! He is also an ASP.NET MVP and his claim to fame is dotnetshoutout.com (which is a great site) and the open source Kigg project. He writes tons of posts on ASP.NET MVC, and has recently been on quite a run with many lengthy and in-depth articles. Maarten Balliauw - Maarten is authoring the book ASP.NET MVC 1.0 Quickly by Packt. I’m not sure how Maarten has time to write the book and his blog, because he has been pumping out quite a few awesome ASP.NET MVC posts recently. Steve Sanderson - Steve is the author of Pro ASP.NET MVC Framework by Apress and like these other guys, still finds time to write some good informative posts on his blog. He is also the author of the xVal validation framework which aims to help developers more easily tie domain validations to the front-end web application. Luis Abreau – This one is a bonus, and was added because of Marwan's comment below. I went and checked it out, and there are many great little ASP.NET MVC tidbits on this guys blog. Too bad there isn't much information about him at all. It looks like he might be a current or former MVP, I don't know. He has a linked in profile, but not too much info there other than the fact that he is in Portugal. So lots of good ASP.NET MVC information, but other than that, I don't know what to tell you about the guy!
http://www.andrewconnell.com/blog/archive/2006/09/15/4587.aspx - In Visual Studio, click Tools -> External Tools...
- Click Add and enter the following into the different fields as displayed in the following screenshot:
- Title: Get Public Key
- Command: C:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\Bin\sn.exe
- Arguments: -Tp "$(TargetPath)"
- Uncheck all options, except Use Output window\
@for %%e in (%PATHEXT%) do @for %%i in (%1%%e) do @if NOT "%%~$PATH:i"=="" echo %%~$PATH:i
http://searchwindevelopment.techtarget.com/tip/0,289483,sid8_gci1255498,00.html public static void GenerateRsa(string privateKeyPath, string publicKeyPath, int size)
{
//stream to save the keys
FileStream fs = null;
StreamWriter sw = null;
//create RSA provider
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(size);
try
{
//save private key
fs = new FileStream(privateKeyPath, FileMode.Create, FileAccess.Write);
sw = new StreamWriter(fs);
sw.Write(rsa.ToXmlString(true));
sw.Flush();
}
finally
{
if (sw != null) sw.Close();
if (fs != null) fs.Close();
}
try
{
//save public key
fs = new FileStream(publicKeyPath, FileMode.Create, FileAccess.Write);
sw = new StreamWriter(fs);
sw.Write(rsa.ToXmlString(false));
sw.Flush();
}
finally
{
if (sw != null) sw.Close();
if (fs != null) fs.Close();
}
rsa.Clear();
}
ProcessStartInfo si = new ProcessStartInfo("cmd.exe");
// Redirect both streams so we can write/read them.
si.RedirectStandardInput = true;
si.RedirectStandardOutput = true;
si.UseShellExecute = false;
// Start the procses.
Process p = Process.Start(si);
// Issue the dir command.
p.StandardInput.WriteLine(@"dir c:");
// Exit the application.
p.StandardInput.WriteLine(@"exit");
// Read all the output generated from it.
string output = p.StandardOutput.ReadToEnd();
http://www.c-sharpcorner.com/UploadFile/DipalChoksi/ShellCommandsInCS12032005042031AM/ShellCommandsInCS.aspx
http://www.dotnetinterop.com/faq/?q=LoadLibrary You can load the DLL manually before the CLR tries to do it for you, using the LoadLibrary Win32 API. By passing it the fully qualified path, you can bypass the regular search path rules. The following code calls the exported function MyFunc in unmanaged.dll, located in the ..\unmanaged directory relative to the executable. C# [DllImport("kernel32.dll", CharSet=CharSet.Auto)]
static extern IntPtr LoadLibrary(string lpFileName);
[DllImport("unmanaged.dll")]
static extern int MyFunc(int i);
static void Main()
{
// Ensure current directory is exe directory
Environment.CurrentDirectory = Path.GetDirectoryName( Assembly.GetExecutingAssembly().Location );
string dllPath = Path.GetFullPath( @"..\unmanaged\unmanaged.dll" );
LoadLibrary( dllPath );
Console.WriteLine( MyFunc( 5 ) );
}
VB.NET Declare Auto Function LoadLibrary Lib "kernel32.dll" (ByVal lpFileName As String) As IntPtr
Declare Function MyFunc Lib "unmanaged.dll" (ByVal i As Integer) As Integer
Shared Sub Main()
' Ensure current directory is exe directory
Environment.CurrentDirectory = Path.GetDirectoryName([Assembly].GetExecutingAssembly().Location)
Dim dllPath As String = Path.GetFullPath("..\unmanaged\unmanaged.dll")
LoadLibrary(dllPath)
Console.WriteLine(MyFunc(5))
End Sub
1. Select the directory. 2. In the top buttons, choose "Show all files" 3. Select the directory again and choose "include in project" 4. you can choose "refresh" button on the top to update the content in the directory, and then add those new added items again.
http://dn.codegear.com/article/32384 Environment.SpecialFolder.ApplicationData Environment.SpecialFolder.System Environment.SpecialFolder.CommonApplicationData Environment.SpecialFolder.CommonProgramFiles Environment.SpecialFolder.Cookies Environment.SpecialFolder.Desktop Environment.SpecialFolder.DesktopDirectory Environment.SpecialFolder.Favorites Environment.SpecialFolder.History Environment.SpecialFolder.InternetCache Environment.SpecialFolder.LocalApplicationData Environment.SpecialFolder.MyComputer Environment.SpecialFolder.MyMusic Environment.SpecialFolder.MyPictures Environment.SpecialFolder.Personal (My documents) Environment.SpecialFolder.ProgramFiles Environment.SpecialFolder.Programs Environment.SpecialFolder.Recent Environment.SpecialFolder.SendTo Environment.SpecialFolder.StartMenu Use Environment.GetFolderPath() function to get the physical path string
http://www.cnblogs.com/reallypride/archive/2008/09/08/1287095.html Enumnamespace EnumTest
{
enum date { sun, mon, tue, wes, thu, fri, sat }
class Program
{
static void Main(string[] args)
{
Console.WriteLine("输入星期的名称:");
string name = Console.ReadLine();
//Type参数表示要转换成的枚举的类型,true指示忽略大小写
object obj = Enum.Parse(typeof(date), name, true);
Console.WriteLine("输出星期的数字:");
Console.WriteLine(obj + ":" + (int)obj);
}
}
}
Delegate namespace DelegateTest
{
class Person
{
public void FirstMethod()
{
Console.WriteLine("这是第一个方法!");
}
public void SecondMethod()
{
Console.WriteLine("这是第二个方法!");
}
}
delegate void dele();
class Program
{
static void Main(string[] args)
{
Console.WriteLine("输入方法的名字:");
string name = Console.ReadLine();
Person p = new Person();
//Type参数是要转换的委托的类型,p是要调用的委托的实例,true指示忽略大小写
dele d = Delegate.CreateDelegate(typeof(dele), p, name + "Method", true) as dele;
d.Invoke();
Console.WriteLine("输入方法的名字:");
name = Console.ReadLine();
d = Delegate.CreateDelegate(typeof(dele), p, name + "method", true) as dele;
d.Invoke();
}
}
}
Anonymous Methodnamespace Anonymity
{
delegate void dele();
class Program
{
static void Main(string[] args)
{
dele d = delegate() { Console.WriteLine("这是一个匿名方法!"); };
d.Invoke();
}
}
}
Indexernamespace IndexerTest
{
class PersonNames
{
List<string> names = new List<string>();
/// <summary>
/// 为对象创建索引器,注意它和属性的get/set的不同
/// </summary>
/// <param name="index">索引值</param>
/// <returns></returns>
public string this[int index]
{
get { return names[index]; }
set { names.Add(value); }
}
}
class Program
{
static void Main(string[] args)
{
PersonNames names = new PersonNames();
names[0] = "微软";
names[1] = "谷歌";
names[2] = "百度";
for (int i = 0; i < 3; i++)
{
Console.WriteLine(names[i]);
}
}
}
}
HashTablenamespace HashTableTest
{
class Program
{
static void Main(string[] args)
{
Hashtable table = new Hashtable();
table["name1"] = "微软";
table.Add("name2", "谷歌");
table["name3"] = "百度";
//注意name的类型名
foreach (DictionaryEntry name in table)
{
Console.WriteLine(name.Key + ":" + name.Value);
}
}
}
}
// preprocessor_if.cs
#define DEBUG
#define VC_V7
using System;
public class MyClass
{
public static void Main()
{
#if (DEBUG && !VC_V7)
Console.WriteLine("DEBUG is defined");
#elif (!DEBUG && VC_V7)
Console.WriteLine("VC_V7 is defined");
#elif (DEBUG && VC_V7)
Console.WriteLine("DEBUG and VC_V7 are defined");
#else
Console.WriteLine("DEBUG and VC_V7 are not defined");
#endif
}
}
http://msdn.microsoft.com/en-us/library/4y6tbswk(VS.71).aspx
http://www.c-sharpcorner.com/UploadFile/nagryum/Appdomain07102007081415AM/Appdomain.aspx Advantages A single CLR operating system process can contain multiple application domains. There are advantages to having application domains within a single process. -
Lower system cost - many application domains can be contained within a single system process. -
Each application domain can have different security access levels assigned to them, all within a single process. -
Code in one AppDomain cannot directly access code in another AppDomain. -
The application in an AppDomain can be stopped without affecting the state of another AppDomain running in the same process. -
An Exception in on AppDomain will not affect other AppDomains or crash the entire process that hosts the AppDomains.
Quick Tour of Some of the New Features Visual Studio 2008 and .NET 3.5 contain a ton of new functionality and improvements. Below are links to blog posts I've done myself as well as links to videos you can watch to learn more about it: VS 2008 Multi-Targeting Support VS 2008 enables you to build applications that target multiple versions of the .NET Framework. This means you can use VS 2008 to open, edit and build existing .NET 2.0 and ASP.NET 2.0 applications (including ASP.NET 2.0 applications using ASP.NET AJAX 1.0), and continue to deploy these application on .NET 2.0 machines. You can learn more about how this works from my blog post here: ASP.NET AJAX and JavaScript Support .NET 3.5 has ASP.NET AJAX built-in (no separate download required). In addition to including all of the features in ASP.NET AJAX 1.0, ASP.NET 3.5 also now includes richer support for UpdatePanels integrating with WebParts, ASP.NET AJAX integration with controls like <asp:menu> and <asp:treeview>, WCF support for JSON, and many other AJAX improvements. VS 2008 and Visual Web Developer 2008 also now have great support for integrating JavaScript and AJAX into your applications. You can learn more about this from my blog posts here: You can watch some videos that discuss ASP.NET AJAX and Visual Studio 2008 support for it here. I also highly recommend the excellent ASP.NET AJAX in Action book to learn more about ASP.NET AJAX (both client-side and server-side). VS 2008 Web Designer and CSS Support VS 2008 and Visual Web Developer 2008 Express includes a significantly improved HTML web designer (the same one that ships with Expression Web). This delivers support for split-view editing, nested master pages, and great CSS integration. Below are some articles I've written that discuss this more: ASP.NET 3.5 also has a new <asp:ListView> control that provides the ability to perform rich data scenarios with total control over the markup. It works nicely with the new CSS support in VS 2008. You can learn more about it from my article here: You can watch some videos that discuss the new Visual Studio 2008 web designer features and the new ListView/DataPager controls here. Language Improvements and LINQ The new VB and C# compilers in VS 2008 deliver significant improvements to the languages. Both add functional programming concepts that enable you to write cleaner, terser, and more expressive code. These features also enable a new programming model we call LINQ (language integrated query) that makes querying and working with data a first-class programming concept with .NET. Below are some of the articles I've written that explore these new language features using C#: Here are a few additional blog posts I've written that show off some of the new VS 2008 code editing support and some cool ways to use these new language features: The Visual Basic team has also created some great free videos that cover LINQ. You can watch them here. Data Access Improvements with LINQ to SQL LINQ to SQL is a built-in OR/M (object relational mapper) in .NET 3.5. It enables you to model relational databases using a .NET object model. You can then query the database using LINQ, as well as update/insert/delete data from it. LINQ to SQL fully supports transactions, views, and stored procedures. It also provides an easy way to integrate business logic and validation rules into your data model. Below are some of the articles I've written that explore how to use it: I think you'll find that LINQ and LINQ to SQL makes it much easier to build much cleaner data models, and write much cleaner data code. I'll be adding more posts to my LINQ to SQL series in the weeks and months ahead (sorry for the delay in finishing them earlier - so much to-do and so little time to-do it all!). Scott Stanfield is also working on creating some great LINQ to SQL videos for the www.asp.net site based on my article series above (all videos are in both VB and C#). You can watch the first 4 videos in this series here. Browsing the .NET Framework Library Source using Visual Studio As I blogged a few weeks ago, we will be releasing a reference version of the .NET Framework library source code as part of this release. Visual Studio 2008 has built-in debugger support to automatically step-into and debug this code on demand (VS 2008 can pull down the source for the appropriate .NET Framework library file automatically for you). We are deploying the source servers to enable this right now, and will be publishing the steps to turn this feature on in the next few weeks. Lots of other improvements The list above is only a small set of the improvements coming. For client development VS 2008 includes WPF designer and project support. ClickOnce and WPF XBAPs now work with FireFox. WinForms and WPF projects can also now use the ASP.NET Application Services (Membership, Roles, Profile) for roaming user data. Office development is much richer - including support for integrating with the Office 2007 ribbon, and with Outlook. Visual Studio Tools for Office support is also now built-into Visual Studio (you no longer need to buy a separate product). New WCF and Workflow projects and designers are now included in VS 2008. Unit testing support is now much faster and included in VS Professional (and no longer just VSTS). Continuous Integration support is now built-in with TFS. AJAX web testing (unit and load) is now supported in the VS Test SKU. And there is much, much more... Installation Suggestions People often ask me for suggestions on how best to upgrade from previous betas of Visual Studio 2008. In general I'd recommend uninstalling the Beta2 bits explicitly. As part of this you should uninstall Visual Studio 2008 Beta2, .NET Framework Beta2, as well as the Visual Studio Web Authoring Component (these are all separate installs and need to be uninstalled separately). I then usually recommend rebooting the machine after uninstalling just to make sure everything is clean before you kick off the new install. You can then install the final release of VS 2008 and .NET 3.5 on the machine. Once installed, I usually recommend explicitly running the Tools->Import and Export Settings menu option, choosing the "Reset Settings" option, and then re-pick your preferred profile. This helps ensure that older settings from the Beta2 release are no longer around (and sometimes seems to help with performance). Note that VS 2008 runs side-by-side with VS 2005 - so it is totally fine to have both on the same machine (you will not have any problems with them on the same box). Silverlight Tools and VS Web Deployment Project Add-Ins Two popular add-ins to Visual Studio are not yet available to download for the final VS 2008 release. These are the Silverlight 1.1 Tools Alpha for Visual Studio and the Web Deployment Project add-in for Visual Studio. Our hope is to post updates to both of them to work with the final VS 2008 release in the next two weeks. If you are doing Silverlight 1.1 development using VS 2008 Beta2 you'll want to stick with with VS 2008 Beta2 until this updated Silverlight Tools Add-In is available. Hope this helps, Scott
http://blog.emanuelebartolesi.com/post/2007/12/Log4net-Simple-way-to-use-in-your-Aspnet-application.aspx Introduction Log the actions of your applications is very important especially when you develop new features or develop very difficult logical business. But it is also important when users use your applications to understand the critical issues or problems. To implement quickly the log operations Apache developed an opensource library for .Net developers. Download You can download the latest version of Log4net from this location. Add reference to your solution In Visual Studio 2005 select Project -> Add Reference. In the tab Browse, find and select the dll Log4net.dll in your local folder. Modify web.config Into web.config file add this code into the section Configuration->Configsections: <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/> Yet, add the section: <log4net> <appender name="RollingFile" type="log4net.Appender.RollingFileAppender"> <file value="c:\temp\web.log" /> <appendToFile value="true" /> <maximumFileSize value="1024KB" /> <maxSizeRollBackups value="10" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%date %level %logger - %message%newline" /> </layout> </appender> <root> <level value="DEBUG" /> <appender-ref ref="RollingFile" /> </root> </log4net> In this configuration will create a log file into the folder "c:\temp\" until its size is 1024Kb. After this size the name of file will be web.log.1 until 10. At this link you can find another configurations. Global.asax In the event "Application_Start" of the file Global.asax add this line: log4net.Config.XmlConfigurator.Configure(); Begin to log In every page you want to log something, add the static variable like below: private static readonly ILog log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); This class has 5 levels of severity to log the operations: log.Debug("log something at this level") log.Info("log something at this level") log.Warn("log something at this level"); log.Error("log something at this level"); log.Fatal("log something at this level"); Simple and fast to use. You find the official documentation at this link.
Show date in english: ToString("MM/dd", new System.Globalization.CultureInfo("en-us"))
// // Any source code blocks look like this //
DateTime dt = DateTime.Now; String strDate=""; strDate = dt.ToString("MM/dd/yyyy"); // 07/21/2007 strDate = dt.ToString("dddd, dd MMMM yyyy"); //Saturday, 21 July 2007 strDate = dt.ToString("dddd, dd MMMM yyyy HH:mm"); // Saturday, 21 July 2007 14:58 strDate = dt.ToString("dddd, dd MMMM yyyy hh:mm tt"); // Saturday, 21 July 2007 03:00 PM strDate = dt.ToString("dddd, dd MMMM yyyy H:mm"); // Saturday, 21 July 2007 5:01 strDate = dt.ToString("dddd, dd MMMM yyyy h:mm tt"); // Saturday, 21 July 2007 3:03 PM strDate = dt.ToString("dddd, dd MMMM yyyy HH:mm:ss"); // Saturday, 21 July 2007 15:04:10 strDate = dt.ToString("MM/dd/yyyy HH:mm"); // 07/21/2007 15:05 strDate = dt.ToString("MM/dd/yyyy hh:mm tt"); // 07/21/2007 03:06 PM strDate = dt.ToString("MM/dd/yyyy H:mm"); // 07/21/2007 15:07 strDate = dt.ToString("MM/dd/yyyy h:mm tt"); // 07/21/2007 3:07 PM strDate = dt.ToString("MM/dd/yyyy HH:mm:ss"); // 07/21/2007 15:09:29 strDate = dt.ToString("MMMM dd"); // July 21 strDate = dt.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffK"); // 2007-07-21T15:11:19.1250000+05:30 strDate = dt.ToString("ddd, dd MMM yyyy HH':'mm':'ss 'GMT'"); // Sat, 21 Jul 2007 15:12:16 GMT strDate = dt.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss"); // 2007-07-21T15:12:57 strDate = dt.ToString("HH:mm"); // 15:14 strDate = dt.ToString("hh:mm tt"); // 03:14 PM strDate = dt.ToString("H:mm"); // 5:15 strDate = dt.ToString("h:mm tt"); // 3:16 PM strDate = dt.ToString("HH:mm:ss"); // 15:16:29 strDate = dt.ToString("yyyy'-'MM'-'dd HH':'mm':'ss'Z'"); // 2007-07-21 15:17:20Z strDate = dt.ToString("dddd, dd MMMM yyyy HH:mm:ss"); // Saturday, 21 July 2007 15:17:58 strDate = dt.ToString("yyyy MMMM"); // 2007 July
When you click datasource in .net, it will drive you crazy when error message "object reference not set to an instance of an object" pops out. It is caused by VS.Net can not load data source configuration file correctly. Solution is that you have to go into exclude the datasource configuration file from your project. Normally it is put under the properties directory in the project.
Dim startInfo As System.Diagnostics.ProcessStartInfo Dim pStart As New System.Diagnostics.Process startInfo = New System.Diagnostics.ProcessStartInfo("C:\file.exe") pStart.StartInfo = startInfo pStart.Start() pStart.WaitForExit() 'Your code will halt until the exe file has executed.
http://www.manifold.net/doc/7x/sql_server_express_... SQL Server Express Edition The Manifold DVD includes a complete distribution of Microsoft® SQL Server™ 2005 Express Edition. SQL Server Express provides the power of SQL Server to Manifold System users at no additional charge. Introduction SQL Server 2005 Express Edition is derived from the same engine upon which Microsoft SQL Server 2005 is built. It is a newer and, in many key ways, better alternative to the SQL Server 2000 Desktop Engine (known as MSDE) distributed in earlier Manifold releases. When delivered in SQL Server Express form, Microsoft has limited SQL Server in several ways: § A database cannot exceed 4 gigabytes in size. § SQL Server Express may be installed on a multiple CPU machine, but it will execute (run) only on a single processor or a single processor core if multi-core processors are used. § SQL Server Express may be installed on a server with any amount of memory, but will use only up to 1 GB of available RAM memory. Other than these limitations SQL Server Express provides virtually the full power and breadth of SQL Server capabilities. Although MSDE was limited to no more than five users, SQL Server Express no longer has such an artificial throttle on performance. Within the limits of processor, RAM and maximum database size, SQL Server Express always runs at full speed. SQL Server 2005 Features Comparison http://www.microsoft.com/sql/prodinfo/features/com... Note: If SQL Server 2005 Express is running on Windows XP Home, it is limited to five simultaneous connections. If it is running on Windows 2000 or Windows XP Professional, it is limited to 10 simultaneous connections. However, these are limitations of the operating system and not of SQL Server 2005 Express. Upgrading MSDE 2000 to SQL Server 2005 Express http://www.microsoft.com/technet/prodtechnol/sql/2... MySQL Community Server http://dev.mysql.com/downloads/mysql/5.0.html dual license model: http://www.mysql.com/company/legal/licensing/faq.h... MySQL Enterprise Basic $595
- SQLite (only C/C++ interfaces are provided)
- Firebird (Previously Borland "interbase"
- WilsonXmlDbClient (ADO.NET provider simulating database)
- Microsoft potable database
From: http://www.andymcm.com/dotnetfaq.htm#4.
An AppDomain can be thought of as a lightweight process. Multiple AppDomains can exist inside a Win32 process. The primary purpose of the AppDomain is to isolate applications from each other, and so it is particularly useful in hosting scenarios such as ASP.NET. An AppDomain can be destroyed by the host without affecting other AppDomains in the process.
Win32 processes provide isolation by having distinct memory address spaces. This is effective, but expensive. The .NET runtime enforces AppDomain isolation by keeping control over the use of memory - all memory in the AppDomain is managed by the .NET runtime, so the runtime can ensure that AppDomains do not access each other's memory.
One non-obvious use of AppDomains is for unloading types. Currently the only way to unload a .NET type is to destroy the AppDomain it is loaded into. This is particularly useful if you create and destroy types on-the-fly via reflection.
Microsoft have an http://www.gotdotnet.com/team/clr/AppdomainFAQ.aspx.
|
Copyright © 2010 Kevin Mocha. All rights reserved.
DasBlog 'Portal' theme by Johnny Hughes.
Pick a theme:
|
|