dropdownstyle: dropdownlist autocompletemode: append autocompletesource: listtiems
http://www.vbinfozine.com/t_wfdlg.shtml But what if I want to do some validation WITHIN the button's Click event handler and if the validation fails, I DON'T WANT to close the dialog? First solution: Set OKCmd.DialogResult = DialogResult.None (string "None" in the designer) and close the form manually: Second solution: Leave the OKCmd.DialogResult = DialogResult.OK, but prevent the form to automatically close when the user enters invalid logon information. Here is how:
http://stackoverflow.com/questions/135020/advantages-to-using-private-static-methods After you mark the methods as static, the compiler will emit non-virtual call sites to these members. Emitting non-virtual call sites will prevent a check at runtime for each call that ensures that the current object pointer is non-null. This can result in a measurable performance gain for performance-sensitive code. In some cases, the failure to access the current object instance represents a correctness issue. Static methods are useful, because just by looking at its signature, you know that the calling it doesn't use or modify the current instance's state.
http://www.albahari.com/nutshell/predicatebuilder.aspx http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx Visitor class
/// <summary>
/// A visitor that filters visited items
/// </summary>
/// <typeparam name="T">The type of item to be visited</typeparam>
public class FilterVisitor<T> : IVisitor<T>
{
#region Private Members
/// <summary>
/// The function to use for filtering items
/// </summary>
private readonly Func<T, bool> _filterFunction;
/// <summary>
/// The filtered items
/// </summary>
private readonly List<T> _result;
#endregion
#region Constructor
/// <summary>
/// Constructor
/// </summary>
/// <param name="filterFunction">The function to use for filtering items</param>
public FilterVisitor(Func<T, bool> filterFunction)
{
_filterFunction = filterFunction;
_result = new List<T>();
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="expression">The lambda expression to use for filtering items</param>
public FilterVisitor(Expression<Func<T, bool>> expression)
{
_filterFunction = expression.Compile();
_result = new List<T>();
}
#endregion
#region Public Properties
/// <summary>
/// The filtered items
/// </summary>
public List<T> Result
{
get
{
return _result;
}
}
#endregion
#region IVisitor<T> Members
/// <summary>
/// Visits the specified item, and adds the item to the result if the filter function is true
/// </summary>
/// <param name="item">The item to be evaluated</param>
public void Visit(T item)
{
if (_filterFunction(item))
{
_result.Add(item);
}
}
#endregion
}
}
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://randypatterson.com/index.php/2007/09/26/how-to-design-a-fluent-interface/ http://en.wikipedia.org/wiki/Fluent_interface#C.23 #region Fluent Example
public interface IConfigurationFluent
{
IConfigurationFluent SetColor(string color);
IConfigurationFluent SetHeight(int height);
IConfigurationFluent SetLength(int length);
IConfigurationFluent SetDepth(int depth);
}
public class ConfigurationFluent : IConfigurationFluent
{
string color;
int height;
int length;
int depth;
public IConfigurationFluent SetColor(string color)
{
this.color = color;
return this;
}
public IConfigurationFluent SetHeight(int height)
{
this.height = height;
return this;
}
public IConfigurationFluent SetLength(int length)
{
this.length = length;
return this;
}
public IConfigurationFluent SetDepth(int depth)
{
this.depth = depth;
return this;
}
}
#endregion
public class ExampleProgram
{
public static void Main(string[] args)
{
//Standard Example
IConfiguration config = new Configuration
{
Color = "blue",
Height = 1,
Length = 2,
Depth = 3
};
//Fluent Example
IConfigurationFluent fluentConfig =
new ConfigurationFluent().SetColor("blue")
.SetHeight(1)
.SetLength(2)
.SetDepth(3);
}
}
Vulnerability Scanners Discovery Tools Port Scanners Sniffers Password Crackers Intrusion Detection System (snort, ISS RealSecure) Firewalls Denial-of-Services Attacks Algorithm RSA (Factorization Problem) Eclipse Curve (Discrete Logarithm) Diffie-Hellman (DHP)
http://stackoverflow.com/questions/58739/interview-questions-wpf-developer What should every WPF developer know? Entry Level - Strong .NET 2.0 Background & willing to learn!
- Explain dependency properties?
- What's a style?
- What's a template?
- Binding
- Differences between base classes: Visual, UIElement, FrameworkElement, Control
- Visual vs Logical tree?
- Property Change Notification (INotifyPropertyChange and ObservableCollection)
- ResourceDictionary - Added by a7an
- UserControls - Added by a7an
- difference between bubble and tunnel routing strategies - added by Carlo
Mid-level - Routed Events & Commands
- Converters - Added by Artur Carvalho
- Explain WPF's 2-pass layout engine?
- How to implement a panel?
- Interoperability (WPF/WinForms)
- Blend/Cider - Added by a7an
- animations and storyboarding
- ClickOnce Deployment
- Skinning/Themeing
- Custom Controls
- How can worker threads update the UI?
Senior - Example of attached behavior?
- What is PRISM,CAL & CAG?
- How can worker threads update the UI?
- WPF 3D - Added by a7an
- Differences between Silverlight 2 and WPF
- MVVM/MVP - Added by a7an
- WPF Performance tuning
- Pixel Shaders
- Purpose of Freezables
http://www.sqlite.org/whentouse.html http://www.theopensourcery.com/sqlite2.htm No stored Procedure No Nested Transactions Situations Where Another RDBMS May Work Better -
Client/Server Applications If you have many client programs accessing a common database over a network, you should consider using a client/server database engine instead of SQLite. SQLite will work over a network filesystem, but because of the latency associated with most network filesystems, performance will not be great. Also, the file locking logic of many network filesystems implementation contains bugs (on both Unix and Windows). If file locking does not work like it should, it might be possible for two or more client programs to modify the same part of the same database at the same time, resulting in database corruption. Because this problem results from bugs in the underlying filesystem implementation, there is nothing SQLite can do to prevent it. A good rule of thumb is that you should avoid using SQLite in situations where the same database will be accessed simultaneously from many computers over a network filesystem. -
High-volume Websites SQLite will normally work fine as the database backend to a website. But if you website is so busy that you are thinking of splitting the database component off onto a separate machine, then you should definitely consider using an enterprise-class client/server database engine instead of SQLite. -
Very large datasets With the default page size of 1024 bytes, an SQLite database is limited in size to 2 tebibytes (241 bytes). And even if it could handle larger databases, SQLite stores the entire database in a single disk file and many filesystems limit the maximum size of files to something less than this. So if you are contemplating databases of this magnitude, you would do well to consider using a client/server database engine that spreads its content across multiple disk files, and perhaps across multiple volumes. -
High Concurrency SQLite uses reader/writer locks on the entire database file. That means if any process is reading from any part of the database, all other processes are prevented from writing any other part of the database. Similarly, if any one process is writing to the database, all other processes are prevented from reading any other part of the database. For many situations, this is not a problem. Each application does its database work quickly and moves on, and no lock lasts for more than a few dozen milliseconds. But there are some applications that require more concurrency, and those applications may need to seek a different solution.
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.
http://msdn.microsoft.com/en-us/library/ms229603.aspx Each control that accepts free-form user input has a Validating event that will occur whenever the control requires data validation. In the Validating event-handling method, you can validate user input in several ways. The Validating event is supplied an object of type CancelEventArgs. If you determine that the control's data is not valid, you can cancel the Validating event by setting this object's Cancel property to true. If you do not set the Cancel property, Windows Forms will assume that validation succeeded for that control, and raise the Validated event. When you use data binding, the data in your control is synchronized with the data source during execution of the Validating event. If you cancel the Validating event, the data will not be synchronized with the data source Implicit and Explicit Validation So when does a control's data get validated? This is up to you, the developer. You can use either implicit or explicit validation, depending on the needs of your application. Implicit Validation The implicit validation approach validates data as the user enters it. You can validate the data as the data is entered in a control by reading the keys as they are pressed, or more commonly whenever the user takes the input focus away from one control and moves to the next. This approach is useful when you want to give the user immediate feedback about the data as they are working. If you want to use implicit validation for a control, you must set that control's AutoValidate property to true. If you cancel the Validating event, the behavior of the control will be determined by what value that you assigned to AutoValidate. If you assigned EnablePreventFocusChange, canceling the event will cause the Validated event not to occur. Input focus will remain on the current control until the user changes the data to a valid input. If you assigned EnableAllowFocusChange, the Validated event will not occur when you cancel the event, but focus will still change to the next control. Assigning Disable to the AutoValidate property prevents implicit validation altogether. To validate your controls, you will have to use explicit validation. Explicit Validation The explicit validation approach validates data at one time. You can validate the data in response to a user action, such as clicking a Save button or a Next link. When the user action occurs, you can trigger explicit validation in one of the following ways: -
Call Validate to validate the last control to have lost focus. -
Call ValidateChildren to validate all child controls in a form or container control. -
Call a custom method to validate the data in the controls manually.
Development Opportunities: 1. ASP.Net master pages and CSS 2. Standard ASP.NET server controls, Web Parts, event handlers, custom field types, and custom policies. 3. Site Column 4. Content type 5. Office Open XML file format 6. Workflow 7. Features Features are a new developer-focused innovation that has been added to WSS 3.0. Features provide a mechanism for defining site elements and adding them to a target site or site collection through a process known as feature activation. The element types that can be defined by a feature include menu commands, link commands, page templates, page instances, list definitions, list instances, event handlers, and workflows. (lulu: Activate and De-Activate events) WSS object model The WSS object model exposes an SPSite class that serves as an entry point into the WSS object model at the site collection level. Each site within a site collection is represented as an SPWeb object. Each list within a site is represented as an SPList object. Here’s a simple example using the WSS object model to access the top-level site within a target site collection and discover all its lists. using Microsoft.SharePoint;
namespace Hello_WSS_OM {
class Program {
static void Main() {
string sitePath = "http://litwareinc.com";
// enter object model through site collection.
SPSite siteCollection = new SPSite(sitePath);
// obtain reference to top-level site.
SPWeb site = siteCollection.RootWeb;
// enumerate through lists of site
foreach (SPList list in site.Lists) {
Console.WriteLine(list.Title);
}
// clean up by calling Dispose.
site.Dispose();
siteCollection.Dispose();
}
}
}
ASP.NET 2.0 introduced a new pluggable component type known as a virtual path provider. The idea behind a virtual path provider is that it abstracts the details of where page files are stored away from the ASP.NET runtime. By creating a custom virtual path provider, a developer can write a custom component that retrieves ASP.NET file types, such as .aspx and .master files, from a remote location, such as a Microsoft SQL Server database. Once a virtual path provider retrieves the contents of an .aspx page, it can pass it along to the ASP.NET runtime for parsing.
The WSS team created a virtual path provider named SPVirtualPathProvider that is integrated into every Web application. The SPVirtualPathProvider class is integrated into the ASP.NET request handling infrastructure by the SPRequestModule. More specifically, the SPRequestModule component contains code to register the SPVirtualPathProvider class with the ASP.NET Framework as it does its work to initialize a Web application. Figure 2-6 displays a diagram that depicts the role of the SPVirtualPathProvider.
Application Page (Ghosted and Non-customizable) Site Page (Customizable, so Non-Ghosted) As a rule, application pages should derive from a base class in the Microsoft.SharePoint assembly named LayoutsPageBase.
Web Part pages in a WSS 3.0 site are built on top of the new Web Part infrastructure introduced with ASP.NET 2.0. To create a Web Part page in an ASP.NET 2.0 application, you must create an .aspx page that contains exactly one instance of a control named WebPartManager and one or more WebPartZone controls. The WebPartManager is responsible for managing the lifetime of Web Part instances as well as serializing Web Part–related data so that they can be stored and retrieved from the tables in the ASP.NET services database.
The Web Part infrastructure of WSS 3.0 does not use the standard WebPartManager control from ASP.NET. Instead, WSS relies on a specialized control named SPWebPartManager that derives from the ASP.NET 2.0 WebPartManager control. The SPWebPartManager control overrides the standard behavior of the WebPartManager control to persist Web Part data inside the WSS content database instead of inside the ASP.NET services database.
Site pages and application pages use separate master pages.
Delegate Controls and ContentLightup
A Web Part is a class that inherits from the WebPart class defined in the System.Web.UI.WebControls.WebParts namespace inside the System.Web assembly. The Web Part is a special type of Web control that is deployable inside of a Web Part Zone control after the initial page has been created and deployed.
Web Parts interact with the Web Part Manager control, which itself adds and maintains the instances of Web Parts that are added to Web Part zones either at page design time or at run time.
Web Parts render inside of chrome.
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.
http://stackoverflow.com/questions/2056/what-are-mvp-and-mvc-and-what-is-the-difference
Model-View-Presenter In MVP, the Presenter contains the the UI business logic for the View. All invocations from the View delegate directly to Presenter. The Presenter is also decoupled directly from the View and talks to it through an interface. This is to allow mocking of the View in a unit test. One common attribute of MVP is that there has to be a lot of two-way dispatching. For example, when someone clicks the "Save" button, the event handler delegates to the Presenter's "OnSave" method. Once the save is completed, the Presenter will then call back the View through it's interface so that the View can display that the save has completed. MVP tends to be a very natural pattern for achieving separated presentation in Web Forms. The reason is because the View is always created first by the ASP.NET runtime. You can find out more about both variants. Two primary variations Passive View: The View is as as dumb as possible and contains almost zero logic. The Presenter is a middle man that talks to the View and the Model. The View and Model are completely shielded from one another. The Model may raise events, but the Presenter subscribes to them for updating the View. In Passive View there is no direct data binding, instead the View exposes setter properties which the Presenter uses to set the data. All state is managed in the Presenter and not the View. - Pro: maximum testability surface; clean separation of the View and Model
- Con: more work (for example all the setter properties) as you are doing all the data binding yourself.
Supervising Controller: The Presenter handles user gestures. The View binds to the Model directly through data binding. In this case it's the Presenter's job to pass off the Model to the View so that it can bind to it. The Presenter will also contain logic for gestures like pressing a button, navigation, etc. - Pro: by leveraging databinding the amount of code is reduced.
- Con: there's less testable surface (because of data binding), and there's less encapsulation in the View since it talks directly to the Model.
Model-View-Controller In the MVC, the Controller is responsible for determining which View is displayed in response to any action including when the application loads. This differs from MVP where actions route through the View to the Presenter. In MVC, every action in the View correlates with a call to a Controller along with an action. In the web each action involves a call to a URL on the other side of which there is a Controller who responds. Once that Controller has completed it's processing, it will return the correct View. The sequence continues in that manner throughout the life of the application: Action in the View
-> Call to Controller
-> Controller Logic
-> Controller returns the View.
One other big difference about MVC is that the View does not directly bind to the Model. The view simply renders, and is completely stateless. In implementations of MVC the View usually will not have any logic in the code behind. This is contrary to MVP where it is absolutely necessary as if the View does not delegate to the Presenter, it will never get called. (lulu: That means the view has to have the delegate code in MVP)
There is a MSDN article about the Presentation Model and a section in the Composite Application Guidance for WPF (former Prism) about Separated Presentation Patterns
Presentation Model
One other pattern to look at is the Presentation Model pattern. In this pattern there is no Presenter. Instead the View binds directly to a Presentation Model. The Presentation Model is a Model crafted specifically for the View. This means this Model can expose properties that one would never put on a domain model as it would be a violation of separation-of-concerns. In this case, the Presentation Model binds to the domain model, and may subscribe to event coming from that Model. The View then subscribes to events coming from the Presentation Model and updates itself accordingly. The Presentation Model can expose commands which the view uses for invoking actions. The advantage of this approach is that you can essentially remove the code-behind altogether as the PM complete encapsulates all of the behaviour for the view. This pattern is a very strong candidate for use in WPF applications and is also called Model-View-ViewModel.
More links about this:
http://www.aspiringcraftsman.com/2007/08/interactive-application-architecture/
(lulu: traditional MVC)

The View’s responsibility can be seen as primarily dealing with output while the Controller’s responsibility can be seen as primarily dealing with input. It is the shared responsibility of both the View and the Controller to interact with the Model. The Controller interacts with the Model as the result of responding to user input, while the View interacts with the Model as the result of updates to itself. Both may access and modify data within the Model as needed.
As data is entered by the user, the Controller intercepts the user’s input and responds appropriately. Some user actions will result in interaction with the Model, such as changing data or invoking methods, while other user actions may result in visual changes to the View, such as the collapsing of menus, the highlighting of scrollbars, etc.
MVC Misconceptions
One common misconception about the relationship between the MVC components is that the purpose of the Controller is to separate the View from the Model. While the MVC pattern does decouple the application’s domain layer from presentation concerns, this is achieved through the Observer Pattern, not through the Controller. The Controller was conceived as a mediator between the end user and the application, not between the View and the Model.
http://haacked.com/archive/2008/06/16/everything-you-wanted-to-know-about-mvc-and-mvp-but.aspx
(lulu: IN current MVC, the view will not get data from Model directly)
The two patterns are similar in that they both are concerned with separating concerns and they both contain Models and Views. Many consider the MVP pattern to simply be a variant of the MVC pattern. The key difference is suggested by the problem that the MVP pattern sought to solve with the MVP pattern. Who handles the user input?
With MVC, it’s always the controller’s responsibility to handle mouse and keyboard events. With MVP, GUI components themselves initially handle the user’s input, but delegate to the interpretation of that input to the presenter. This has often been called “Twisting the Triad”, which refers to rotating the three elements of the MVC triangle and replacing the “C” with “P” in order to get MVP.
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.
http://www.ccvita.com/418.html 范式的原理 - 第一范式(1NF)无重复的列
所谓第一范式(1NF)是指数据库表的每一列都是不可分割的基本数据项,同一列中不能有多个值,即实体中的某个属性不能有多个值或者不能有重复的属性。如果出现重复的属性,就可能需要定义一个新的实体,新的实体由重复的属性构成,新实体与原实体之间为一对多关系。在第一范式(1NF)中表的每一行只包含一个实例的信息。简而言之,第一范式就是无重复的列。 说明:在任何一个关系数据库中,第一范式(1NF)是对关系模式的基本要求,不满足第一范式(1NF)的数据库就不是关系数据库。 - 第二范式(2NF)属性完全依赖于主键[消除部分子函数依赖]
第二范式(2NF)是在第一范式(1NF)的基础上建立起来的,即满足第二范式(2NF)必须先满足第一范式(1NF)。第二范式(2NF)要求数据库表中的每个实例或行必须可以被惟一地区分。为实现区分通常需要为表加上一个列,以存储各个实例的惟一标识。 例如员工信息表中加上了员工编号(emp_id)列,因为每个员工的员工编号是惟一的,因此每个员工可以被惟一区分。这个惟一属性列被称为主关键字或主键、主码。 第二范式(2NF)要求实体的属性完全依赖于主关键字。所谓完全依赖是指不能存在仅依赖主关键字一部分的属性,如果存在,那么这个属性和主关键字的这一部分应该分离出来形成一个新的实体,新实体与原实体之间是一对多的关系。为实现区分通常需要为表加上一个列,以存储各个实例的惟一标识。简而言之,第二范式就是属性完全依赖于主键。 - 第三范式(3NF)属性不依赖于其它非主属性[消除传递依赖]
满足第三范式(3NF)必须先满足第二范式(2NF)。简而言之,第三范式(3NF)要求一个数据库表中不包含已在其它表中已包含的非主关键字信息。例如,存在一个部门信息表,其中每个部门有部门编号(dept_id)、部门名称、部门简介等信息。 那么在的员工信息表中列出部门编号后就不能再将部门名称、部门简介等与部门有关的信息再加入员工信息表中。如果不存在部门信息表,则根据第三范式(3NF)也应该构建它,否则就会有大量的数据冗余。简而言之,第三范式就是属性不依赖于其它非主属性。 范式的说明
The whole point of bringing in an IoC container is that you can use it to eliminate hard-coded dependencies between components. Using an IoC Container
An IoC container is a standard software component that supports and simplifies IoC. It lets you register a set of components (i.e., abstract types and your currently chosen concrete implementations), and then handles the business of instantiating them. You can configure and register components either with an XML file or with C# code (or both).
At runtime, you can call a method similar to container.Resolve(Type type), where type could be a particular interface or abstract type or a particular concrete type, and the container will return an object satisfying that type definition, according to whatever concrete type is configured. It sounds trivial, but a good IoC container adds three extra clever features:
Dependency chain resolution: If you request a component that itself has dependencies (e.g., constructor parameters), the container will satisfy those dependencies recursively, so you can have component A, which depends on B, which depends on C, and so on. In other words, you can forget about the wiring on your component circuit board—just think about the components, because wiring happens magically.
Object lifetime management: If you request component A more than once, should you get the same actual instance of A each time, or a fresh new instance each time? The container will usually let you configure the “lifestyle” of a component, allowing you to select from predefined options including singleton (the same instance each time), transient (a new instance each time), instance-per-thread, instance-from-a-pool, and so on.
Explicit constructor parameter values configuration: For example, if the constructor for MembersRepository demands a string called connectionString, (as ours did earlier), you can configure a value for it in your XML config file. It’s a crude but simple configuration system that removes any need for your code to pass around connection strings, SMTP server addresses, and so on. So, in the preceding example, you’d configure MembersRepository as the active concrete implementation for IMembersRepository. Then, when some code calls container.Resolve (typeof(AdminController)), the container will figure out that to satisfy AdminController’s constructor parameters it first needs an object implementing IMembersRepository. It will get one according to whatever concrete implementation you’ve configured (in this case, MembersRepository), supplying the connectionString you’ve configured. It will then use that to instantiate and return an AdminController.
Model-view-presenter (MVP) is a recent variation on MVC that’s designed to fit more easily with stateful GUI platforms such as Windows Forms or ASP.NET WebForms. You don’t need to know about MVP when you’re using ASP.NET MVC, but it’s worth explaining what it is so you can avoid confusion.
In this twist, the presenter has the same responsibilities as MVC’s controller, plus it also takes a more hands-on relationship to the stateful view, directly editing the values displayed in its UI widgets according to user input (instead of letting the view render itself from a template). There are two main flavors:
• Passive view, in which the view contains no logic, and merely has its UI widgets manipulated by the presenter.
• Supervising controller, in which the view may be responsible for certain presentation logic, such as data binding, having been given a reference to some data source in the model.
The difference between the two flavors is quite subjective and simply relates to how intelligent the view is allowed to be. Either way, the presenter is decoupled from the GUI technology, so its logic can be followed easily and is suitable for automated testing In this architecture, requests are routed to a controller class, which processes user input and works with the domain model to handle the request. While the domain model holds domain logic (i.e., business objects and rules), controllers hold application logic, such as navigation through a multistep process or technical details like authentication. When it’s time to produce a visible UI for the user, the controller prepares the data to be displayed (the presentation model, or ViewData in ASP.NET MVC, which for example might be a list of Product objects matching the requested category), selects a view, and leaves it to complete the job. Since controller classes aren’t coupled to the UI technology (HTML), they are just pure, testable application logic.
• WebForms takes the view that UIs should be stateful, and to that end adds a sophisticated abstraction layer on top of HTTP and HTML, using ViewState and postbacks to create the effect of statefulness. This makes it suitable for drag-and-drop Windows Forms–style development, in which you pull UI widgets onto a canvas and fill in code for their event handlers.
• MVC embraces HTTP’s true stateless nature, working with it rather than fighting against it. It requires you to understand how web applications actually work; but given that understanding, it provides a simple, powerful, and modern approach to writing web applications with tidy code that’s easy to test and maintain over time, free of bizarre complications and painful limitations.
There are certainly cases where WebForms is at least as good as, and probably better than, MVC. The obvious example is small, intranet-type applications that are largely about binding grids directly to database tables or stepping users through a wizard. Since you don’t need to worry about the bandwidth issues that come with ViewState, don’t need to be concerned with search engine optimization, and aren’t bothered about testability or long-term maintenance, WebForms’ drag-and-drop development strengths outweigh its weaknesses.
On the other hand, if you’re writing applications for the public Internet, or larger intranet applications (e.g., more than a few person-month’s work), you’ll be aiming for fast download speeds and cross-browser compatibility, built with higher-quality, well-architected code suitable for automated testing, in which case MVC will deliver significant advantages for you.
http://www.learncpp.com/cpp-tutorial/125-the-virtual-table/ Compiling time Set up the virtual table (static array) in each class Adds a hidden pointer to the base class * _vptr, which is inherited by derived classes. Running time When a class instance is created, the _vptr points to the virtual table for that class.
http://msdn.microsoft.com/en-us/library/ms731913.aspx
Windows Communication Foundation (WCF) transports support two modes for transferring messages: - Buffered transfers hold the entire message in a memory buffer until the transfer is complete. A buffered message must be completely delivered before a receiver can read it.
- Streamed transfers expose the message as a stream. The receiver starts processing the message before it is completely delivered.
- Streamed transfers can improve the scalability of a service by eliminating the requirement for large memory buffers. Whether changing the transfer mode improves scalability depends on the size of the messages being transferred. Large message sizes favor using streamed transfers.
By default, the HTTP, TCP/IP, and named pipe transports use buffered transfers.
http://agilemanifesto.org/principles.html Principles behind the Agile Manifesto We follow these principles: - Our highest priority is to satisfy the customer through early and continuous delivery of valuable software.
- Welcome changing requirements, even late in development. Agile processes harness change for the customer's competitive advantage.
- Deliver working software frequently, from a couple of weeks to a couple of months, with a preference to the shorter timescale.
- Business people and developers must work together daily throughout the project.
- Build projects around motivated individuals. Give them the environment and support they need, and trust them to get the job done.
- The most efficient and effective method of conveying information to and within a development team is face-to-face conversation.
- Working software is the primary measure of progress.
- Agile processes promote sustainable development. The sponsors, developers, and users should be able to maintain a constant pace indefinitely.
- Continuous attention to technical excellence and good design enhances agility.
- Simplicity--the art of maximizing the amount of work not done--is essential.
- The best architectures, requirements, and designs emerge from self-organizing teams.
- At regular intervals, the team reflects on how to become more effective, then tunes and adjusts its behavior accordingly.
http://www.mountaingoatsoftware.com/topics/scrum What is Scrum? Scrum is an agile approach to software development. Rather than a full process or methodology, it is a framework. So instead of providing complete, detailed descriptions of how everything is to be done on the project, much is left up to the team. This is done because the team will know best how to solve its problem. This is why, for example, a sprint planning meeting is described in terms of the desired outcome (a commitment to set of features to be developed in the next sprint) instead of a set of Entry criteria, Task definitions, Validation criteria, and Exit criteria (ETVX) as would be provided in most methodologies. Scrum relies on a self-organizing, cross-functional team. The scrum team is self-organizing in that there is no overall team leader who decides which person will do which task or how a problem will be solved. Those are issues that are decided by the team as a whole. The team is cross-functional so that everyone necessary to take a feature from idea to implementation is involved. These teams are supported by two specific individuals: a ScrumMaster and a product owner. The ScrumMaster can be thought of as a coach for the team, helping team members use the Scrum framework to perform at their highest level. The product owner represents the business, customers or users and guides the team toward building the right product. Scrum projects make progress in a series of sprints, which are timeboxed iterations no more than a month long. At the start of a sprint, team members commit to delivering some number of features that were listed on the project’s product backlog. At the end of the sprint, these features are done--they are coded, tested, and integrated into the evolving product or system. At the end of the sprint a sprint review is conducted during which the team demonstrates the new functionality to the product owner and other interested stakeholders who provide feedback that could influence the next sprint. What are the main activities in Scrum? The sprint itself is the main activity of a Scrum project. Scrum is an iterative and incremental process and so the project is split into a series of consecutive sprints. Each is timeboxed, usually to between one week and a calendar month. A recent survey found that the most common sprint length is two weeks. During this time the team does everything to take a small set of features from idea to coded and tested functionality. The first activity of each sprint is a sprint planning meeting. During this meeting the product owner and team talk about the highest-priority items on the product backlog. Team members figure out how many items they can commit to and then create a sprint backlog, which is a list of the tasks to perform during the sprint. On each day of the sprint, a daily scrum meeting is attended by all team members, including the ScrumMaster and the product owner. This meeting is timeboxed to no more than fifteen minutes. During that time, team members share what they worked on the prior day, will work on today, and identify any impediments to progress. Daily scrums serve to synchronize the work of team members as they discuss the work of the sprint. At the end of a sprint, the teams conducts a sprint review. During the sprint review, the team demonstrates the functionality added during the sprint. The goal of this meeting is to get feedback from the product owner or any users or other stakeholders who have been invited to the review. This feedback may result in changes to the freshly delivered functionality. But it may just as likely result in revising or adding items to the product backlog. Another activity performed at the end of each sprint is the sprint retrospective. The whole team participates in this meeting, including the ScrumMaster and product owner. The meeting is an opportunity to reflect on the sprint that is ending and identify opportunities to improve in the new sprint. What are the main artifacts of a Scrum project? The primary artifact of a Scrum project is, of course, the product itself. The team is expected to bring the product or system to a potentially shippable state at the end of each sprint. The product backlog is a complete list of the functionality that remains to be added to the product. The product backlog is prioritized by the product owner so that the team always works on the most valuable features first. The most popular and successful way to create a product backlog is to populate it with user stories, which are short descriptions of functionality described from the perspective of a user or customer. On the first day of a sprint and during the sprint planning meeting, team members create the sprint backlog. The sprint backlog can be thought of as the team’s to-do list for the sprint. Whereas a product backlog is a list of features to be built (often written in the form of user stories), the sprint backlog is the list of tasks the team needs to perform in order to deliver the functionality they committed to deliver during the sprint. Two other primary artifacts are the sprint burndown chart and release burndown chart. Burndown charts show the amount of work remaining either in a sprint or a release. They are a very effective tool for determining at a glance whether a sprint or release is on schedule to have all planned work finished by the desired date. What are the main roles on a Scrum team? Even if you are new to Scrum, you may have heard of a role called ScrumMaster. The ScrumMaster is the team’s coach and helps team members achieve their highest level of performance. A ScrumMaster differs from a project manager in many key ways, including that the ScrumMaster does not provide day-to-day direction to the team and does not assign tasks to individuals. A good ScrumMaster shelters the team from outside distractions, allowing team members to focus maniacally during the sprint on the goal they have selected. While the ScrumMaster focuses on helping the team be the best that it can be, the product owner works to direct the team at the right goal. The product owner does this by creating a compelling vision of the product and then conveying that vision to the team through the product backlog. The product owner is responsible for ensuring that the product backlog remains prioritized as more is learned about the system being built, its users, the team, and so on. The third and final role on a Scrum project is the team itself. Although individuals on a Scrum team may come to that team with various job titles, while on the team those titles are insignificant. Each person contributes in whatever ways they best can to complete the work of each sprint. This does not mean that a tester will be expected to rearchitect the system; individuals will spend most (and sometimes all) of their time working in whatever discipline they worked before adopting Scrum. But on a Scrum team, individuals are expected to work beyond their preferred disciplines whenever doing so would be for the good of the team. One convenient way to think of the interlocking nature of these three roles is as a race car. The team is the car itself, ready to speed along in whatever direction it is pointed. The product owner is the driver, making sure that the car is always going in the right direction. The ScrumMaster is the chief mechanic, keeping the car well-tuned and performing at its best. http://xprogramming.com/xpmag/whatisxp Extreme Programming is a discipline of software development based on values of simplicity, communication, feedback, and courage. It works by bringing the whole team together in the presence of simple practices, with enough feedback to enable the team to see where they are and to tune the practices to their unique situation. In Extreme Programming, every contributor to the project is an integral part of the “Whole Team“. The team forms around a business representative called “the Customer”, who sits with the team and works with them daily. Extreme Programming teams use a simple form of planning and tracking to decide what should be done next and to predict when the project will be done. Focused on business value, the team produces the software in a series of small fully-integrated releases that pass all the tests the Customer has defined. Extreme Programmers work together in pairs and as a group, with simple design and obsessively tested code, improving the design continually to keep it always just right for the current needs. The Extreme Programming team keeps the system integrated and running all the time. The programmers write all production code in pairs, and all work together all the time. They code in a consistent style so that everyone can understand and improve all the code as needed. The Extreme Programming team shares a common and simple picture of what the system looks like. Everyone works at a pace that can be sustained indefinitely.
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: }
如果输入数组本来的顺序比较好,基本上是有序的,插入排序就很快,因为每个元素只需要移动几步。O(n^2) 快速排序数列是需要不断的执行划分操作,划分了n个元素之后,大概有一半元素的值大于划分值,一半元素的值小于划分值,在相同的运行时间中,插入排序的移动操作只能将一个元素移动到适当的位置。 
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

Scripts and Batches DECLARE @Ident int; SET @TotalCost = 10 SET @TotalCost = @UnitCost * 1.1 SELECT @Test = MAX(UnitPrice) FROM Sales.SalesOrderDetail; @@IDENTITY Returns the last identity value inserted as a result of the last INSERT or SELECT INTO statement @@ROWCOUNT Returns the number of rows affected by the last statement. A batch is a grouping of T-SQL statements into one logical unit. All of the statements within a batch are combined into one execution plan, so all statements are parsed together and must pass a validation of the syntax or none of the statements will execute. Note, however, that this does not prevent runtime errors from happening. In the event of a runtime error, any statement that has been executed prior to the runtime error will still be in effect. To summarize, if a statement fails at parse-time, then nothing runs. If a statement fails at runtime, then all statements until the statement that generated the error have already run. To separate a script into multiple batches, we make use of the GO statement. Because each batch is processed independently, an error in one batch does not prevent another batch from running. Thinking that GO is a T-SQL command is a common mistake. GO is a command that is only recognized by the editing tools (Management Studio, sqlcmd). If you use a third-party tool, then it may or may not support the GO command, but most that claim SQL Server support will. There are several commands that absolutely must be part of their own batch. These include: ❑ CREATE DEFAULT ❑ CREATE PROCEDURE ❑ CREATE RULE ❑ CREATE TRIGGER ❑ CREATE VIEW USE AdventureWorks2008; DECLARE @MyVarchar varchar(50); --This DECLARE only lasts for this batch! SELECT @MyVarchar = ‘Honey, I’’m home...’; PRINT ‘Done with first Batch...’; GO PRINT @MyVarchar; --This generates an error since @MyVarchar --isn’t declared in this batch PRINT ‘Done with second Batch’; GO PRINT ‘Done with third batch’; -- Notice that this still gets executed -- even after the error GO Perhaps the most likely scenario for using batches is when precedence is required — that is, you need one task to be completely done before the next task starts. sqlcmd is a utility that allows you to run scripts from a command prompt in a Windows command box. Dynamic SQL: Generating Your Code On the Fly with the EXEC Command T-SQL offers most of the classic choices for control of flow situations, including: ❑ IF ... ELSE ❑ GOTO ❑ WHILE ❑ WAITFOR ❑ TRY/CATCH CASE <input expression> WHEN <when expression> THEN <result expression> [...n] [ELSE <result expression>] END WAITFOR DELAY <’time‘> | TIME <’time‘> BEGIN TRY { <sql statement(s)> } END TRY BEGIN CATCH { <sql statement(s)> } END CATCH [ ; ] Store Procedure The primary benefits of sprocs include: ❑ Making processes that require procedural action callable ❑ Security ❑ Performance Much like views, we can create a sproc that returns a recordset without having to give the user authority to the underlying table. After the sproc has been created, it sits in wait for the first time that it is executed. At that time, the sproc is optimized and a query plan is compiled and cached on the system. Subsequent times that we run our sproc will, unless we specify otherwise using the WITH RECOMPILE option, generally use that cached query plan rather than creating a new one. EXEC spMySproc ‘1/1/2004’ WITH RECOMPILE DROP PROC|PROCEDURE <sproc name>[;] USE AdventureWorks2008; GO CREATE PROC spEmployeeByName @LastName nvarchar(50) AS SELECT p.LastName, p.FirstName, e.JobTitle, e.HireDate FROM Person.Person p JOIN HumanResources.Employee e ON p. BusinessEntityID = e.BusinessEntityID WHERE p.LastName LIKE @LastName + ‘%’; EXEC spEmployeeByName ‘Dobney’; CREATE PROC spEmployeeByName @LastName nvarchar(50) = NULL AS IF @LastName IS NOT NULL SELECT p.LastName, p.FirstName, e.JobTitle, e.HireDate FROM Person.Person p JOIN HumanResources.Employee e ON p.BusinessEntityID = e.BusinessEntityID WHERE p.LastName LIKE @LastName + ‘%’; ELSE SELECT p.LastName, p.FirstName, e.JobTitle, e.HireDate FROM Person.Person p JOIN HumanResources.Employee e ON p.BusinessEntityID = e.BusinessEntityID; CREATE PROCEDURE [dbo].[uspLogError] @ErrorLogID [int] = 0 OUTPUT -- contains the ErrorLogID of the row inserted AS -- by uspLogError in the ErrorLog table BEGIN SET NOCOUNT ON; -- Output parameter value of 0 indicates that error -- information was not logged SET @ErrorLogID = 0; BEGIN TRY …… Actually, your program will receive a return value whether you supply one or not. By default, SQL Server automatically returns a value of zero when your procedure is complete. Note that the return value must be an integer. USE AdventureWorks2008; GO ALTER PROC spTestReturns AS DECLARE @MyMessage varchar(50); DECLARE @MyOtherMessage varchar(50); SELECT @MyMessage = ‘Hi, it’’s that line before the RETURN’; PRINT @MyMessage RETURN 100; SELECT @MyOtherMessage = ‘Sorry, but we won’’t get this far’; PRINT @MyOtherMessage; RETURN; DECLARE @Return int; EXEC @Return = spTestReturns; SELECT @Return; @@ERROR USE AdventureWorks2008 GO CREATE PROC spInsertValidatedBusinessEntityContact @BusinessEntityID int, @PersonID int, @ContactTypeID int AS BEGIN DECLARE @Error int; INSERT INTO Person.BusinessEntityContact (BusinessEntityID ,PersonID ,ContactTypeID) VALUES (@BusinessEntityID, @PersonID, @ContactTypeID); SET @Error = @@ERROR; IF @Error = 0 PRINT ‘New Record Inserted’; ELSE BEGIN IF @Error = 547 -- Foreign Key violation. Tell them about it. PRINT ‘At least one provided parameter was not found. Correct and retry’; ELSE -- something unknown PRINT ‘Unknown error occurred. Please contact your system admin’; END END Manually Raising Errors RAISERROR (<message ID | message string | variable>, <severity>, <state> [, <argument> [,<...n>]] ) [WITH option[,...n]] Extended Stored Procedures (XPs) SQL Server does allow for the idea of externally written code that runs as a .DLL in process with SQL Server. XPs are created using C or C++. User-Defined Functions (UDFs) With a sproc, you can pass parameters in and also get values in parameters passed back out. You can return a value, but that value is really intended to indicate success or failure rather than return data. You can also return result sets, but you can’t really use those result sets in a query without first inserting them into some kind of table (usually a temporary table) to work with them further Even using a table valued output parameter, you still need to make at least one additional step before using the results in a query.
With a UDF, however, you can pass parameters in, but not out. Instead, the concept of output parameters has been replaced with a much more robust return value. As with system functions, you can return a scalar value — what’s particularly nice, however, is that this value is not limited to just the integer data type as it would be for a sproc. Instead, you can return most SQL Server data types (more on this in the next section).
As they like to say in late-night television commercials: “But wait! There’s more!” The “more” is that you are actually not just limited to returning scalar values—you can also return tables. This is wildly powerful, and we’ll look into this fully later in the chapter. CREATE FUNCTION dbo.DayOnly(@Date datetime) RETURNS varchar(12) AS BEGIN RETURN CONVERT(varchar(12), @Date, 101); END SELECT * FROM Orders WHERE dbo.DayOnly(OrderDate) = dbo.DayOnly(GETDATE()); CREATE FUNCTION dbo.fnContactList() RETURNS TABLE AS RETURN (SELECT BusinessEntityID, LastName + ‘, ‘ + FirstName AS Name FROM Person.Person); GO // parameterized view CREATE FUNCTION dbo.fnContactSearch(@LastName nvarchar(50)) RETURNS TABLE AS RETURN (SELECT p.BusinessEntityID, LastName + ‘, ‘ + FirstName AS Name, ea.EmailAddress FROM Person.Person as p LEFT OUTER JOIN Person.EmailAddress ea ON ea.BusinessEntityID = p.BusinessEntityID WHERE LastName Like @LastName + ‘%’); GO Any coverage of UDFs would be incomplete without discussing determinism. If SQL Server is going to build an index over something, it has to be able to deterministically define (define with certainty) what the item being indexed is. Transactions and Locks Transactions are all about atomicity. Atomicity is the concept that something should act as a unit. From our database standpoint, it’s about the smallest grouping of one or more statements that should be considered to be all or nothing. ❑ BEGIN a transaction: Set the starting point. ❑ COMMIT a transaction: Make the transaction a permanent, irreversible part of the database. ❑ ROLLBACK a transaction: Say essentially that we want to forget that it ever happened. ❑ SAVE a transaction: Establish a specific marker to allow us to do only a partial rollback. In the normal operation of your database, most activities that you perform are logged to the transaction log, rather than written directly to the database. A checkpoint is a periodic operation that forces all dirty pages for the database currently in use to be written to disk. Dirty pages are log or data pages that have been modified after they were read into the cache, but the modifications have not yet been written to disk. Without a checkpoint the log would fill up and/or use all the available disk space. The SQL Server lock manager is that shopkeeper. When you come into the SQL Server store, the lock manager asks what your intent is — what it is you’re going to be doing. If you say “just looking,” and no one else already there is doing anything other than just looking, then the lock manager will let you in. If you want to buy (update or delete) something, then the lock manager will check to see if anyone’s already there. If so, you must wait, and everyone who comes in behind you will also wait. When you are let in to buy, no one else will be let in until you are done. Locks can address four major problems: ❑ Dirty reads Dirty reads occur when a transaction reads a record that is part of another transaction that isn’t complete yet. If the first transaction completes normally, then it’s unlikely there’s a problem. But what if the transaction were rolled back? You would have information from a transaction that never happened from the database’s perspective! ❑ Non-repeatable reads A non-repeatable read is caused when you read the record twice in a transaction and a separate transaction alters the data in the interim. ❑ Phantoms records that appear mysteriously, as if unaffected by an UPDATE or DELETE statement that you’ve issued. someone performed an INSERT statement at the very same time your UPDATE was running. Since it was an entirely new row, it didn’t have a lock on it and it proceeded just fine ❑ Lost updates Lost updates happen when one update is successfully written to the database, but is accidentally overwritten by another transaction. Lost updates can happen when two transactions read an entire record, then one writes updated information back to the record and the other writes updated information back to the record. Lockable Resources There are six lockable resources for SQL Server, and they form a hierarchy. The higher level the lock, the less granularity it has (that is, you’re choosing a higher and higher number of objects to be locked a cascading type of action just because the object that contains them has been locked). These include, in ascending order of granularity: ❑ Database: The entire database is locked. This happens usually during database schema changes. ❑ Table: The entire table is locked. This includes all the data-related objects associated with that table, including the actual data rows (every one of them) and all the keys in all the indexes associated with the table in question. ❑ Extent: The entire extent is locked. Remember than an extent is made up of eight pages, so an extent lock means that the lock has control of the extent, the eight data or index pages in that extent, and all the rows of data in those eight pages. ❑ Page: All the data or index keys on that page are locked. ❑ Key: There is a lock on a particular key or series of keys in an index. Other keys in the same index page may be unaffected. ❑ Row or Row Identifier (RID): Although the lock is technically placed on the row identifier (an internal SQL Server construct), it essentially locks the entire row. Lock Modes Beyond considering just what resource level you’re locking, you also should consider what lock mode your query is going to acquire. Just as there are a variety of resources to lock, there are also a variety of lock modes. Shared Locks A shared lock is used when you need only to read the data. one thing that shared locks do is prevent users from performing dirty reads. Exclusive Locks Exclusive locks are not compatible with any other lock. This prevents two people from updating, deleting, or whatever at the same time. Update Locks Update locks are something of a hybrid between shared locks and exclusive locks. Think about it — in order to do an update, you need to validate your WHERE clause (assuming there is one) to figure out just what rows you’re going to be updating. That means that you only need a shared lock, until you actually go to make the physical update. At the time of the physical update, you’ll need an exclusive lock. an update lock prevents any other update locks from being established. deadlock: two update query finish the read and waiting to escalate to an exclusive lock. they wait for each other. Intent Locks Without intent locks, the higher-level objects wouldn’t even know that you had the lock at the lower level. Schema Locks Bulk Update Locks Isolation Level The first thing to understand about the relationship between transactions and locks is that they are inextricably linked with each other. By default, any lock that is data modification related will, once created, be held for the duration of the transaction. If you have a long transaction, this means that your locks may be preventing other processes from accessing the objects you have a lock on for a rather long time. It probably goes without saying that this can be rather problematic. However, that’s only the default. In fact, there are actually five different isolation levels that you can set: ❑ READ COMMITTED (the default) the locks associated with the SELECT statement are freed as soon as the SELECT statement is complete — SQL Server doesn’t wait for the end of the transaction. Action queries (UPDATE, DELETE, and INSERT) are a little different. If your transaction performs a query that modifies data, then those locks will be held for the duration of the transaction (in case you need to roll back). By keeping this level of default with READ COMMITTED, you can be sure that you have enough data integrity to prevent dirty reads. However, non-repeatable reads and phantoms can still occur. ❑ READ UNCOMMITTED
READ UNCOMMITTED is the most dangerous of all isolation level choices, but also has the highest performance in terms of speed. Setting the isolation level to READ UNCOMMITTED tells SQL Server not to set any locks and not to honor any locks. With this isolation level, it is possible to experience any of the various concurrency issues we discussed earlier in the chapter (most notably a dirty read). there are actually good reasons to have this isolation level, and they almost always have to do with reporting. By using READ UNCOMMITTED, you can often get around this problem — at least for reports where the numbers don’t have to be exact. You can get the same effect as READ UNCOMMITTED by adding the NOLOCK optimizer hint in your query. ❑ REPEATABLE READ
The REPEATABLE READ escalates your isolation level somewhat and provides an extra level of concurrency protection by preventing not only dirty reads (the default already does that), but also preventing non-repeatable reads. That prevention of non-repeatable reads is a big upside, but holding even shared locks until the end of the transaction can block users’ access to objects, and therefore hurt productivity. Personally, I prefer to use other data integrity options (such as a CHECK constraint together with error handling) rather than this choice, but it remains an available option. The equivalent optimizer hint for the REPEATABLE READ isolation level is REPEATABLEREAD (these are the same, only no space). ❑ SERIALIZABLE
SERIALIZABLE is something of the fortress of isolation levels. It prevents all forms of concurrency issues except for a lost update. Even phantoms are prevented. When you set your isolation to SERIALIZABLE, you’re saying that any UPDATE, DELETE, or INSERT to the table or tables used by your transaction must not meet the WHERE clause of any statement in that transaction. Essentially, if the user was going to do something that your ❑ SNAPSHOT
指定事务中任何语句读取的数据都将是在事务开始时便存在的数据的事务上一致的版本。事务只能识别在其开始之前提交的数据修改。在当前事务中执行的语句将看不到在当前事务开始以后由其他事务所做的数据修改。其效果就好像事务中的语句获得了已提交数据的快照,因为该数据在事务开始时就存在。 http://blog.csdn.net/sandyzhs/archive/2008/10/24/3136465.aspx
http://adamnoffie.blogspot.com/2007/03/aspnet-forms-authentication-strange.html the login.aspx page would be missing all of the style information from our CSS style sheet Solution - made a second Web.config and placed it in my App_Themes directory where my style sheet lives. <system.web> <authorization> <allow users="*"> </allow> </authorization> </system.web> or use <location path="App_Themes" allowOverride="false"> <system.web> <authorization> <allow users="*"/> </authorization> </system.web> </location>
http://www.4guysfromrolla.com/articles/052406-1.aspx http://www.ezzylearning.com/tutorial.aspx?tid=5187857 <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
BackColor="White" BorderColor="#336699" BorderStyle="Solid" BorderWidth="1px"
CellPadding="0" CellSpacing="0" DataKeyNames="CategoryID" Font-Size="10"
Font-Names="Arial" GridLines="Vertical" Width="40%">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="chkStatus" runat="server"
AutoPostBack="true" OnCheckedChanged="chkStatus_OnCheckedChanged"
Checked='<%# Convert.ToBoolean(Eval("Approved")) %>'
Text='<%# Eval("Approved").ToString().Equals("True") ? " Approved " : " Not Approved " %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="CategoryID" HeaderText="CategoryID" />
<asp:BoundField DataField="CategoryName" HeaderText="CategoryName" />
</Columns>
<HeaderStyle BackColor="#336699" ForeColor="White" Height="20" />
</asp:GridView><asp:GridView ID="FileList" runat="server"
AutoGenerateColumns="False" DataKeyNames="FullName">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox runat="server" ID="RowLevelCheckBox" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Name" HeaderText="Name" />
<asp:BoundField DataField="CreationTime" HeaderText="Created On">
<ItemStyle HorizontalAlign="Right" />
</asp:BoundField>
<asp:BoundField DataField="Length" DataFormatString="{0:N0}"
HeaderText="File Size"
HtmlEncode="False">
<ItemStyle HorizontalAlign="Right" />
</asp:BoundField>
</Columns>
</asp:GridView>
Protected Sub DeleteButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles DeleteButton.Click
Summary.Text = "The following file would have been deleted:<ul>"
Dim currentRowsFilePath As String
'Enumerate the GridViewRows
For index As Integer = 0 To FileList.Rows.Count - 1
'Programmatically access the CheckBox from the TemplateField
Dim cb As CheckBox = CType(FileList.Rows(index).FindControl("RowLevelCheckBox"), CheckBox)
'If it's checked, delete it...
If cb.Checked Then
currentRowsFilePath = FileList.DataKeys(index).Value
Summary.Text &= String.Concat("<li>", currentRowsFilePath, "</li>")
End If
Next
Summary.Text &= "</ul>"
End Sub
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
http://en.wikipedia.org/wiki/Component-oriented_programming The main idea is separation of concerns; Software engineers regard components as part of the starting platform for service orientation. Components play this role, for example, in Web Services, and more recently, in Service-Oriented Architecture (SOA) - whereby a component is converted[by whom?] into a service and subsequently inherits further characteristics beyond that of an ordinary component. An individual component is a software package or a module that encapsulates a set of related functions (or data). All system processes are placed into separate components so that all of the data and functions inside each component are semantically related (just as with the contents of classes). Because of this principle, it is often said that components are modular and cohesive. With regard to system-wide co-ordination, components communicate with each other via interfaces. When a component offers services to the rest of the system, it adopts a provided interface which specifies the services that can be utilized by other components and how. This interface can be seen as a signature of the component - the client does not need to know about the inner workings of the component (implementation) in order to make use of it. This principle results in components referred to as encapsulated. Another important attribute of components is that they are substitutable, Software components often take the form of objects or collections of objects (from object-oriented programming), in some binary or textual form, adhering to some interface description language (IDL) so that the component may exist autonomously from other components in a computer. Reusability is an important characteristic of a high-quality software component. A software component should be designed and implemented so that it can be reused in many different programs. It takes significant effort and awareness to write a software component that is effectively reusable. The component needs to be: - fully documented
- thoroughly tested
- robust - with comprehensive input-validity checking
- able to pass back appropriate error messages or return codes
- designed with an awareness that it will be put to unforeseen uses
Differences from object-oriented programming Proponents of object-oriented programming (OOP) maintain that software should be written according to a mental model of the actual or imagined objects it represents. OOP and the related disciplines of object-oriented design and object-oriented analysis focus on modeling real-world[citation needed] interactions and attempting to create "verbs" and "nouns" which can be used in intuitive[citation needed] ways, ideally by end users as well as by programmers coding for those end users. Component-based software engineering, by contrast, makes no such assumptions, and instead states that developers should construct software by gluing together prefabricated components - much like in the fields of electronics or mechanics. Some peers[who?] will even talk of modularizing systems as software components as a new programming paradigm. Component-based development (CBD) is an extension of object-oriented programming. CBD does away with the language and vendor-specific limitations of OOP, and makes software reuse more practical and accelerates the development process. Event-based programming is the next logical step in CBD, and makes components more reusable due to their decoupled nature. But event-based systems are easier to develop, which means they are cheaper and more reliable than traditional OOP or CBD systems.
Web 2.0 addresses the new web technologies that are used to bring more interactivity to web applications. Additionally, Web 2.0 also includes a behavioral shift on the web, where users are encouraged to customize their own content on web applications rather than view static/ generic content supplied by an organization. In addition to the technology and behavior changes, Web 2.0 can also mean the shift from shrink-wrapped software to software as a service. Another aspect of Web 2.0 are mash-up and plug-in pages. (Personal google page) Injection attacks are based on a single problem that persists in many technologies: namely, no strict separation exists between program instructions and user data (also referred to as user input). This problem allows for attackers to sneak program instructions into places where the developer expected only benign data. By sneaking in program instructions, the attacker can instruct the program to perform actions of the attacker’s choosing. Input Injection SQL Injection SELECT id FROM user_table WHERE username = '' OR 1=1 -- ' AND password = PASSWORD('x') Injection attacks are not necessary blind attacks. Many web applications are developed with open-source tools. To make injection attacks more successful, download free or evaluation copies of products and set up your own test system. Once you have found an error in your test system, it is highly probable that the same issue will exist on all web applications using that tool. Cure: 1. constrain data types, escape user input, prepared statements (the best) XPath Injection //users[username/text()='admin' and password/text()='' or '1'='1' ]/id/text() Command Injection (Escape) Directory Transversal Attacks XXE (XML eXternal Entity) Attacks (prohibit the external entity in XML parser) LDAP Injection whitelisting characters—that is, allow alphanumeric characters (a–z, A–Z, and 0–9) and deny all other characters. Buffer Overflows The injection aspect of buffer overflows is that the attacker injects machine instructions (called shell code) into some user input. The attacker somewhat needs to know where the shell code will end up in the memory of the computer running the web application. Then the attacker overwrites the return address to point to the memory location of the shell code.
Security HTTP offers integrated mechanisms for authenticating users. Collectively referred to as HTTP authentication, these mechanisms provide a way for users to be authenticated without the necessity of any server-side programming logic. This can be especially helpful for restricting access to static resources (such as images or HTML files). Of course, server-side scripts can also implement HTTP authentication, although Web developers often authenticate users in the application logic itself. There are two basic types of HTTP authentication: -
Basic authentication -
Digest authentication
An elegant solution to these types of problems is SSL, Secure Sockets Layer. In 1994, Netscape released the specification of Secure Sockets Layer. By 1995, version 3.0 of SSL was released, and it has since taken the Web by storm. SSL has dramatically changed the way people use the Web, and it provides a very good solution to many of the Web's shortcomings, most importantly: -
Data integrity— SSL can help ensure that data (HTTP messages) cannot be changed while in transit. -
Data confidentiality— SSL provides strong cryptographic techniques used to encrypt HTTP messages. -
Identification— SSL can offer reasonable assurance as to the identity of a Web server. It can also be used to validate the identity of a client, but this is less common. A digital certificate is a document that declares that a particular public key is owned by a particular Web site (see Figure 18.3). The CA's role is very similar to a notary whose responsibility is to ensure the correct identity of people signing a legal document. SSL is basically a protocol that employs both symmetric and asymmetric cryptography to protect messages that use TCP as the transport-level protocol. Because of the high performance expense of asymmetric cryptography, it is only used to exchange the randomly generated symmetric key that is then used for the symmetric encryption of the HTTP messages.
https on port 443 Whenever a Web browser connects to a Web site over a secure connection, it requires that the SSL certificate the Web server presents meets three main conditions: -
The domain name on the certificate must match the domain name the Web browser believes itself to be requesting a resource from. -
The certificate must be valid (not expired). -
The certificate must be signed by a trusted certificate authority (CA). Transport Layer Security (TLS) is a formally standardized version of SSL. The biggest difference, in fact, is that TLS is defined and maintained by an international standards body, the Internet Engineering Task Force (IETF). SSL is developed and maintained by Netscape. One of the advantages of the IETF's involvement in TLS is that they also control the HTTP protocol. This situation can possibly be credited for RFC 2817, which describes a method for using the Upgrade general header to upgrade to HTTP over TLS. The significance of this is that it allows for a change in protocol without having to utilize a separate port. Thus, a Web server that supports this technique can implement TLS over port 80. An example of a Web client's request is the following: GET / HTTP/1.1
Host: 127.0.0.1
Upgrade: TLS/1.0
Connection: Upgrade
A Web server that accepts this upgrade will issue an HTTP response similar to the following: HTTP/1.1 101 Switching Protocols
Upgrade: TLS/1.0, HTTP/1.1
Connection: Upgrade
At this point, a typical SSL handshake will take place over the current connection. It is sometimes confusing to consider that the SSL handshake can take place over port 80 at this point while the Web server can still accept normal HTTP requests over the same port. Note that the upgrade only affects the current TCP connection. Just as a Web server does not (barring extremely odd memory collisions) send the wrong HTTP response to the wrong Web client, it can also keep protocol upgrades straight.
Maintaining State If a unique response per client is desired, something in the HTTP request itself must be unique. Once a method of state management has been established, you need only to authenticate the user once. Because state management provides a way to identify a Web client, user identification simply requires that you remember which user is associated with which client upon authentication.
When I speak of maintaining state, I am only speaking of client identification, which is accomplished by associating multiple HTTP requests. Maintaining session, on the other hand, requires two related tasks: Although cookies are most often described in conversation as if they are entities (for example, "a Web server sends you a cookie"), they are much easier to understand at a functional level if you consider them an extension of the HTTP protocol, which is actually more correct. Cookies can be defined as the addition of two HTTP headers:
A common question seen on mailing lists and discussion forums for Web developers is how to test whether the client is accepting cookies, and many people do not understand the answer. As is evident in Figure 11.3, it is impossible to determine whether the client accepted the cookie until the second request is sent (step 3 in the figure). If the cookie is included in the second request, the client accepted it. If not, the client rejected it. Some developers choose to force the issue of determining whether the client accepts cookies by redirecting the client to a second URL upon entrance. Cookies have become a source of privacy concern in recent years. As with most technologies in the computer industry, this reputation has been earned by the misuse of the technology more than the technology itself. Whether using files or a database to store the session information, there are three basic elements you will want to store for each session's record: -
Unique identifier -
Timestamp of last access -
Client data
Improve the performance Caching can refer to many concepts. The general meaning of cache is to store a copy of something to prevent the necessity of retrieving it again. When speaking of Web development, there are three main types of caching: -
Caching on the server— Storing a complete or partially generated resource on the server to keep from having to regenerate it. -
Caching on the client— Storing a resource on the client to keep from having to receive the entire resource again. -
Proxy caching— Storing a resource on a proxy to allow direct replies to an HTTP request rather than having to receive the entire resource from the origin server again. Although there are many side advantages to caching, there are three core benefits: -
Improve response time from a user perspective— This is what most Web developers focus on, the user experience. -
Lessen network load— Many Web developers overlook this metric because bandwidth is often viewed as an expendable resource, where more can be purchased as needed. -
Lessen server load— This metric is more difficult to overlook, as it directly impacts the user experience in terms of performance and reliability (stressed servers fail more often).
It is important to remember that an HTTP response completes the HTTP transaction. Many people new to Web development have a difficult time distinguishing between server-side code (code that executes on the server) and client-side code (code that executes on the client). Scripting languages such as PHP, ColdFusion, and JSP are executed on the server, and their output is included in the HTTP response. In fact, their output is the content of the HTTP response, and most modern Web scripting languages also allow for some manipulation of the HTTP as well, such as altering or adding headers, changing status codes, and so on. Once the Web client receives the HTTP response, the transaction is complete. The Web client will then render the page, execute client-side scripts such as JavaScript, load images (by issuing separate GET requests), and so on. With HTTP/1.1, persistent connections are the default behavior. This means that the Web server will not close the connection after sending the HTTP response unless the client intends to close the connection after receiving it. In this case, the client will include the following header in the HTTP request: Connection: close
Alternatively, the server can close the connection upon sending the HTTP response, although it should be polite and include the same header as shown previously so that the Web client expects this action.
An HTTP response is broken into the following three logical pieces:
-
Status line
-
HTTP headers
-
Content
An example status line is as follows: HTTP/1.1 200 OK
The status line contains three elements:
There are three types of HTTP headers allowed in a response:
-
General headers
-
Response headers
-
Entity headers
Status codes are grouped into the following ranges:
-
Informational (100-199)
-
Successful (200-299)
-
Redirection (300-399)
-
Client error (400-499)
-
Server error (500-599)
- 100 Continue
- 101 Switching Protocols
- 200 OK
- 400 Bad Request
- 401 Unauthorized
- 403 Forbidden
- 404 Not Found
- 500 Internal Server Error
- 502 Bad Gateway
- 503 Service Unavailable
Content-Disposition, combined with a proper Content-Type header, provides the developer absolute control over the interpretation of the resource's media type.
Server: new a socket –> bind to listen port –> Accept a connection –> send/receive –>close Client: new a socket –> connect –>send/receive –> close http://myname:mypass@httphandbook.org:80/mydir/myfile.html?myvar=myvalue#myfrag HTTP is often referred to as a stateless protocol. Although this is accurate, it does little to explain the nature of the Web. All this means, however, is that each transaction is atomic, and there is nothing required by HTTP that associates one request with another. A transaction refers to a single HTTP request and the corresponding HTTP response. When I speak of a connection in HTTP, I refer to a TCP connection. A single connection can support multiple HTTP transactions. In many cases, multiple HTTP transactions are required to properly render a URL in a Web browser due to images and other associated content. Get and Post GET and POST basically allow information to be sent back to the webserver from a browser (or other HTTP client for that matter). Imagine that you have a form on a HTML page and clicking the "submit" button sends the data in the form back to the server, as "name=value" pairs. Choosing GET as the "method" will append all of the data to the URL and it will show up in the URL bar of your browser. The amount of information you can send back using a GET is restricted as URLs can only be 1024 characters. A POST on the other hand will (typically) send the information through a socket back to the webserver and it won't show up in the URL bar. You can send much more information to the server this way - and it's not restricted to textual data either. It is possible to send files and even binary data such as serialized Java objects! A PUT allows you to "put" (upload) a resource (file) on to a webserver so that it be found under a specified URI. DELETE allows you to delete a resource (file). These are both additions to HTTP/1.1 and are not usually used. HEAD returns just the HTTP headers for a resource. TRACE and OPTIONS are also HTTP/1.1 additions and also rarely used. Although client-side data validation can add to user convenience by avoiding unnecessary HTTP transactions, you should never depend on this technique to ensure the data is valid. GET /search?hl=en&q=HTTP&btnG=Google+Search HTTP/1.1
Host: www.google.com
User-Agent: Mozilla/5.0 Galeon/1.2.0 (X11; Linux i686; U;) Gecko/20020326
Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,
text/plain;q=0.8, video/x-mng,image/png,image/jpeg,image/gif;q=0.2,
text/css,*/*;q=0.1
Accept-Language: en
Accept-Encoding: gzip, deflate, compress;q=0.9
Accept-Charset: ISO-8859-1, utf-8;q=0.66, *;q=0.66
Keep-Alive: 300
Connection: keep-alive
Broken down, the request line is
An HTTP request, which is the message sent from a Web client to a Web server, is comprised of three basic elements:
-
Request line
-
HTTP headers
-
Content
The first line of an HTTP request is always the request line. The request line specifies the request method, the location of the resource, and the version of HTTP being used. These three elements are delimited by spaces. For example: GET / HTTP/1.1
This example specifies the GET request method, the resource located at / (document root), and HTTP/1.1 as the version of protocol used.
The second section of an HTTP request is the headers. HTTP headers include supporting information that can help to explain the Web client's request more clearly. There are three types of HTTP headers that can appear in a request:
-
General headers
-
Request headers
-
Entity headers
There is no requirement pertaining to the order of the headers. Also, because entity headers specify information about the content, they are rarely present in HTTP requests.
In general, it is fairly easy to discern which category a header belongs to. Request headers specifically relate to something unique to an HTTP request, such as the User-Agent header which identifies the client software being used. General headers are common headers that can (at least theoretically) be used in either an HTTP request or an HTTP response. Entity headers relay information about the content itself (the entity). As this request has no content, it also lacks entity headers.
There are eight request methods in HTTP/1.1: GET, POST, PUT, DELETE, HEAD, TRACE, OPTIONS, and CONNECT. HTTP/1.0 specifies three methods (GET, HEAD, and POST), although four others are implemented by some servers and clients claiming to be HTTP/1.0. The support for these four other methods (PUT, DELETE, LINK, and UNLINK) is inconsistent and mostly undefined, although they are each briefly referenced in Appendix D of RFC 1945, the HTTP/1.0 specification.
A GET request is basically a request to receive the content located at a specific URL. Obtaining a URL using the GET method allows users to bookmark the URL, create a link to the URL, email the URL to a friend, and the like. There is a limited amount of data that can be sent from the Web client using get, and this limit is very inconsistently implemented.
The POST method is commonly supported by browsers as a method of submitting form data. As with the query string of a URL, the data in a POST consists of name/value pairs separated by the & character. Special characters are URL encoded, and the Content-Type header references this fact.
For many forms, the POST method is preferable.
The PUT method is not nearly as common as GET or POST. However, it is useful in certain situations because it allows the Web client to send content that will be stored on the Web server. It should be noted that the PUT method is very rarely implemented in Web clients. A common misconception is that the PUT method is required for uploading files. However, this capability is actually an enhancement to the POST method as identified in RFC 1867, "Form-based File Upload in HTML".
HEAD is a very useful request method for people who are interested in finding out more information about the way a certain transaction behaves. The HEAD method is supposed to behave exactly like GET, except that the content is not present. Thus, HEAD is like a normal GET request with all of the HTML stripped away.
TRACE is another diagnostic request method. This method allows the client to gain more perspective into any intermediary proxies that lie between the client and the server. As each proxy forwards the TRACE request on route to the destination Web server, it will add itself to the Via header, with the first proxy being responsible for adding the Via header. When the response is given, the content is actually the final request including the Via header.
Sometimes it is helpful to simply identify the capabilities of the Web server you want to interact with prior to actually making a request. For this purpose, HTTP provides the OPTIONS request method.
The CONNECT request method is reserved explicitly for use by intermediary servers to create a tunnel to the destination server. The intermediary, not the HTTP client, issues the CONNECT request to the destination server. The most common use of the CONNECT method is by a Web client that must use a proxy to request a secure resource using SSL (Secure Sockets Layer) or TLS (Transport Layer Security). The client will tunnel the request through the proxy so that the proxy will simply route the HTTP messages to and from the Web server without trying to examine or interpret them.
Accept Header
Authorization Header Once the browser has successfully authenticated with a Web server in this way, it will appear to a user as if all further requests do not require reauthentication. However, due to the stateless nature of the Web, every request must include the Authorization header, otherwise the server will respond with a 401 Unauthorized response. The convenient behavior of most modern Web browsers involves the browser storing the access credentials and sending the Authorization header with all HTTP requests for a URL within a domain previously discovered to be protected. Because this utilizes the browser's memory, this convenience lasts as long as the browser (at least one instance of the browser) remains active, and the user will be unaware that this authentication takes place in subsequent requests. This can be a very important factor when debugging HTTP authentication, because if you receive a 401 Unauthorized response without being prompted for a username and password, this suggests that the browser is using incorrect credentials in the Authorization header. Restarting the browser will resolve this situation.
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.
http://learn.iis.net/page.aspx/140/understanding-the-built-in-user-and-group-accounts-in-iis-70/ In previous versions of IIS, we had a local account created at install time called IUSR_MachineName. The IUSR_MachineName account was the default identity used by IIS whenever anonymous authentication was enabled. This was used by both the FTP and HTTP services. There was also had a group called IIS_WPG, used as a container for all the application pool identities. We made sure all the appropriate resources on the system had the correct permissions set for the IIS_WPG group during IIS setup so that an administrator only needed to add their identity to that group when they created a new application pool account. This model worked well, but had its drawbacks: the IUSR_MachineName account and IIS_WPG group were both local to the system it was created on. Every account and group within Windows is given a unique number called a SID (security identifier) that distinguishes it from other accounts. When an ACL is created only the SID is used. As part of our design in previous versions of IIS, we had included the IUSR_MachineName in the metabase.xml file so that if you tried to copy the metabase.xml from one machine to another, it would not work--the account on the other machine would have a different name. In addition, you could not just 'xcopy /o' ACLs from one machine to another since the SIDs were different machine to machine. A work around was to use domain accounts--but that required adding an active directory to the infrastructure. The IIS_WPG group had similar issues with permissions. If you set ACLs on one machine's file system for IIS_WPG and tried to 'xcopy /o' those over to another machine, it would fail. The IIS team heard this feedback and improved this experience by using a built-in account and group in IIS 7.0. A built-in account and group are guaranteed by the operating system to always have a unique SID. IIS 7.0 has taken this further and ensured the actual names used by the new account and group will never be localized. For example, regardless of the language of Windows you install, the IIS account name will always be IUSR and the group name will be IIS_IUSRS. In summary, IIS 7.0 offers: - The IUSR built-in account replaces the IUSR_MachineName account
- The IIS_IUSRS built-in group replaces the IIS_WPG group
Since the IUSR account is a built in account, it no longer needs a password. Logically, think of it as being the same as NETWORKSERVICE or LOCALSERVICE accounts. Both the new IUSR account and IIS_IUSRS group are discussed in greater depth in the sections below.
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.  
Understand how event increase the runtime coupling among objects. Event-based communication loosens the static coupling between types, but it comes at the cost of tighter runtime coupling between the event generator and the event subscribers. The multicast nature of events means that all subscribers must agree on a protocol for responding to the event source. The event model, in which the event source holds a reference to all subscribers, means that all subscribers must either (1) remove event handlers when the subscriber wants to be disposed of or (2) simply cease to exist. Also, the event source must unhook all event handlers when the source should cease to exist. You must factor those issues into your design decision to use events. public class DoesWorkThatMightFail
{
public bool TryDoWork()
{
if (!TestConditions())
return false;
Work(); // may throw on failures, but unlikely
return true;
}
public void DoWork()
{
Work(); // will throw on failures.
}
private bool TestConditions()
{
// body elided
// Test conditions here
return true;
}
private void Work()
{
// elided
// Do the work here
}
}
You should expand your set of design choices and use both composition and inheritance. When you create types that reuse implementation from other types, you should use composition. If your types model an Is A relationship in every way, inheritance is the better choice. Composition requires more work to expose the implementation from the inner objects, but the payoff is more control over the coupling between your type and the type whose implementation you wish to reuse. Using inheritance means that your derived type is a special case of the base class in every way.
Extension methods provide a mechanism for C# developers to define behavior in interfaces. You can define an interface with minimal capabilities and then create a set of extension methods defined on that interface to extend its capabilities. In particular, you can add behavior instead of just defining an API.
In short, it's best to declare local variables using var unless developers (including you, in the future) need to see the declared type to understand the code. The title of this item says "prefer," not "always." I recommend explicitly declaring all numeric types (int, float, double, and others) rather than use a var declaration. In addition, use the type parameter in generics (for example T, tresult) rather than var. For everything else, just use var. Merely typing more keystrokes—to explicitly declare the type—doesn't promote type safety or improve readability. You may also introduce inefficiencies that the compiler will avoid if you pick the wrong declared type.
Anonymous types aren't as exotic as they seem, and they don't harm readability when they are used correctly. If you have interim results that you need to keep track of and if they're modeled well with an immutable type, then you should use anonymous types. When you need to define behaviors on those types, that's when you need to create concrete types to represent those concepts. In the meantime, the compiler can generate all the boilerplate code you need. You clearly communicate to other developers that the type is used only within the context of that method and those generic methods it calls.
HttpContext.Request.PhysicalApplicationPath + strYourImageFolderName\Image;
1: RESTORE FILELISTONLY 2: FROM DISK = 'C:\Bridge.bak' 3: GO 4: 5: RESTORE DATABASE Bridge 6: FROM DISK = 'C:\Bridge.bak' 7: WITH 8: MOVE 'Bridge' TO 'C:\Users\Public\Documents\Bridge.mdf', 9: MOVE 'Bridge_log' TO 'C:\Users\Public\Documents\Bridge_log.mdf' 10: GO
“Login Failed for user Reason: The password of the account must be changed!” “I ran the following command to turn off MUST_CHANGE: ALTER LOGIN UserLogin WITH PASSWORD = 'NewPassword' UNLOCK Then you can uncheck 'Enforce password policy' and 'Enforce password expiration' or just run the following two sql commands: ALTER LOGIN UserLogin WITH CHECK_EXPIRATION = OFF ALTER LOGIN UserLogin WITH CHECK_POLICY = OFF Once both of these properties were unchecked the application ran fine with no errors. Interesting. I'm not sure if there was a global setting that caused this when SQL Server 2005 was installed?”
The yield return statement plays an interesting trick: It returns a value and retains information about its current location and the current state of its internal iteration. You've got a method that operates on an entire sequence: Both the input and the output are iterators. Internally, the iteration continues to return the next item in the output sequence while it keeps track of its current location in the input sequence. That's a continuation method. Continuation methods keep track of their state and resume execution at their current location when code enters them again. Decouple Iteractions form Actions, Predicates, and Functions The key is that you've separated two distinct operations: 1) iterating a sequence and ( 2) operating on the individual elements in the sequence. You've applied anonymous delegates or lambda expressions to create building blocks that you can use in various ways with various techniques. Any of these routines can be used as larger building blocks in your applications. You can implement many modifications to a sequence as a function (including the special case of predicates), and you can use an action delegate (or similar definition) to manipulate the items in a collection while enumerating a subset of the elements. namespace System
{
public delegate bool Predicate<T>( T obj);
public delegate void Action<T>( T obj);
public delegate TResult Func<T, TResult>(T arg);
}
It's best to generate sequence items only when each item is requested by the consumer of the sequence. You'll avoid doing extra work when the consumer needs only a portion of the algorithm to perform its work. It may be a small savings, or the savings may be much greater if the cost of creating elements is large. In any case, the code that creates the sequence will be clearer when you generate the sequence items only as needed.
// using lambda notation IEnumerable<int> sequence = CreateSequence(10000, 0, 7). TakeWhile((num) => num < 1000);
Creating interfaces and coding against them results in looser coupling than does relying on base classes. You've likely created an interface and forced client coders to implement that interface. This practice creates a relationship that's similar to the relationship you establish by using a base class. There are only two important differences: First, using an interface does not enforce any class hierarchy on your users. But, second, you can't easily provide a default implementation for any of the behavior necessary for client code.
The reason for using delegates instead of an interface is that the delegate is not a fundamental attribute of the type. It's not the number of methods. Several interfaces in the .NET Framework contain only one method. IComparable<T> and IEquatable<T> are perfectly good interface definitions. Implementing those interfaces says something about your type: that it supports comparisons or equality. Implementing this hypothetical IPredicate<T> doesn't say anything interesting about a particular type. You really need only one method definition for one single API.
IEnumerable<string> result = Join(first, second, (one, two) =>
string.Format("{0} {1}", one, two)); // blue part is the Func
The default choice is still to create interface contracts that mandate how your component will communicate with client code. Abstract base classes give you the extra ability to provide a default implementation of some of the work that otherwise would be done by client code. Defining delegates for the methods you expect gives you the most flexibility, but it also means you have less support from tools. You buy more work but gain greater flexibility.
To provide a complete set of functionality for your users, create the minimum set of overloads. Then stop. Adding methods will only increase your library's complexity without enhancing its usefulness.
Overloaded operators can provide intuitive syntax in those languages that support them. However, not every .NET language supports operator overloading. You should start your design by defining your type's public interface using CLS-compliant members. Once you have done that, consider implementing overloaded operators for those languages that support types. The most common operators you will overload are operator == and operator !=. You must overload those when your type implements IEquatable<T>. Many C# developers use the operators and expect them to behave consistently with the IEquatable<T>.Equals() method. You'll also override the comparison operators: <, >, <=, and >=. You should implement those when your type implements IComparable<T>.
If your type models a numeric type, consider overloading mathematical operators. Start with the methods you intend to support, and then add overloaded operators to match for developers using languages that support overloaded operators (such as C#). In all cases, though, ensure that your type is useful even if you do not implement any overloaded operators. Developers using languages that don't support overloaded operators cannot access that portion of your type's public interface. Prefer methods to overloaded operators.
This idiom is used in .NET because there are performance implications involved in throwing exceptions, and developers may wish to avoid those costs by testing conditions before allowing methods to fail.
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://geekswithblogs.net/claraoscura/archive/2008/10/17/125901.aspx “The solution I have found is to put each radio button in a different group and link their checked/unchecked values via the converter. Like this:” <RadioButton
Grid.Row="1"
Grid.Column="0"
GroupName="rbGroupSuccess"
Margin="8,0,0,0"
VerticalAlignment="Center"
Content="Success"
x:Name="rbSuccess"
IsChecked="{Binding Path=IsSuccess, Mode=TwoWay, Converter={StaticResource nullableBooleanConverter}, ConverterParameter=true}" />
<RadioButton
Grid.Row="1"
Grid.Column="1"
GroupName="rbGroupFailure"
Margin="8,0,0,0"
VerticalAlignment="Center"
Content="Failure"
x:Name="rbFailure"
IsChecked="{Binding Path=IsSuccess, Mode=TwoWay, Converter={StaticResource nullableBooleanConverter}, ConverterParameter=false}" />
[ValueConversion(typeof(bool?), typeof(bool))]
public class SuccessConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
bool param = bool.Parse(parameter.ToString());
if (value == null)
{
return false;
}
else
{
return !((bool)value ^ param);
}
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
bool param = bool.Parse(parameter.ToString());
return !((bool)value ^ param);
}
}
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://social.technet.microsoft.com/Forums/en-US/windowsserver2008r2general/thread/c50706c1-9406-4735-b468-07a75147fb98 If you want to access the sharing on Windows Server 2008 computer from Windows XP and Windows 2000, you have to perform the following stesps: 1. Change the settings in Network and Sharing Center Please navigate to Control Panel >>> Network and Sharing Center, and ensure: 1. Fire Sharing: On; 2. Public folder sharing: Turn on sharing so anyone with network access can open files (or Turn on sharing so anyone with network access can open, change, and create files); 3. Password protected sharing: Turn off password protected sharing 2. Change the security settings in gpedit.msc Please navigate to gpedit.msc >>> Computer Configuration >>> Security Settings >>> Security Options Please change Network access: Sharing and security model for local account from “Classic-local users authenticate as themselves” to “Guest only-local users authenticate as Guest” (This will make your other websites stop working if they are using Classic-local users authenticate.)
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();
}
}
}
Coroutines with IEnumnberable and yield return http://incrediblejourneysintotheknown.blogspot.com/2008/04/coroutines-with-ienumerable-and-yield.html Forcing Update of UI before my function exists http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/6fce9b7b-4a13-4c8d-8c3e-562667851baa/ “ An even easier method has just occurred to me: just call this method after setting UI properties:
void AllowUIToUpdate() {
DispatcherFrame frame = new DispatcherFrame();
Dispatcher.CurrentDispatcher.BeginInvoke(DispatcherPriority.Render, new DispatcherOperationCallback(delegate(object parameter)
{
frame.Continue = false;
return null;
}), null);
Dispatcher.PushFrame(frame);
}
If my understanding of DispatcherPriority is correct, this will allow all render level messages to be processed, and will then return.
This feels a little like a WPF equivalent of Application.DoEvents, and I know their are dangers with that. Anybody with a deeper understanding of WPF threading got any thoughts on this?
“
(From http://mikehadlow.blogspot.com/2009/05/what-i-look-for-in-code-review.html) I recently put this bullet point list together for the team I’m currently working with. Naming Conventions General Principles - The core imperative is to organise complexity.
- Clarity and readability is central. “Intention Revealing”
- Do not prematurely optimise for performance.
- Do not repeat yourself. Never copy-and-paste code.
- Decouple.
- Always try to leave the code you work on in a better state than before you started (the ‘boy scout’ principle)
Keep the source clean - Always delete unused code. Including variables and using statements
- Don’t comment out code, delete it. We have source control to manage change.
Naming things - The name should accurately describe what the thing does.
- Do not use shortenings, only use well understood abbreviations.
- If the name looks awkward, the code is probably awkward.
Namespaces - Namespaces should match the project name + path inside the project. This is what VS will give you by default.
- Classes that together provide similar functions should be grouped in a single namespace.
- Avoid namespace dependency cycles.
Variables - Use constants where possible. Avoid magic strings.
- Use readonly where possible
- Avoid many temporary variables.
- Never use a single variable for two different puposes.
- Keep scope as narrow as possible. (declaration close to use)
Methods - The name should accurately describe what the method does.
- It should only do one thing.
- It should be small (more than 10 lines of code is questionable).
- The number of parameters should be small.
- Public methods should validate all parameters.
- Assert expectations and throw an appropriate error if invalid.
- Avoid deep nesting of loops and conditionals. (Cyclomatic complexity).
Classes - The name should accurately describe what the class does.
- Classes typically represent data or services, be clear which your class is.
- Design your object oriented schema deliberately.
- A class should be small.
- A class should have one responsibility only.
- A class should have a clear contract.
- A class should be decoupled from its dependencies.
- Favour composition over inheritance.
- Avoid static classes and methods.
- Make the class immutable if possible.
Interfaces - Rely on interfaces rather than concrete classes wherever possible.
- An interface is a contract for interaction.
- An interface should have a single purpose (ISP)
Tests - All code should have unit tests if possible.
- Test code should have the same quality as production code.
- Write code test-first wherever possible.
Error Handling - Only wrap code with a try..catch statement if you are expecting it to throw a specific exception.
- Unexpected errors should only be handled at process boundaries.
- Never ‘bury’ exceptions.
http://wpfwonderland.wordpress.com/2007/08/11/mixing-external-mergeddictionaries-with-local-resources-in-appxaml/ Adding local application resources Even though it is easy to add external resources it’s likely that you’ll want to have a style or other resource that you don’t intend to shared across applications. You could isolated these resources within a single page (Page.Resources) or element (DockPanel.Resources) But what if you want to add them to <Application.Resources> tag? You can do it as long as you know the correct location. They have to go between the </ResourceDictionary.MergedDictionaries> and </ResourceDictionary> tags. <Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="WorkshopHelpers/MainResources.xaml"/>
</ResourceDictionary.MergedDictionaries>
<!-- Place here...-->
<Style TargetType="Rectangle" >
<Setter Property="Width" Value="100"/>
<Setter Property="Height" Value="80"/>
</Style>
</ResourceDictionary>
</Application.Resources>
</Application>
-Walt Ritscher
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!
Add “overflow:hidden;” when background picture does not repeat.
http://www.tozon.info/blog/post/2009/02/16/Binding-to-Enums.aspx I’ve seen numerous questions regarding data binding to Enums, together with many solutions on how to do it, but the question I’m asking myself is – do I really want to bind anything to an Enum? I like to think about Enums purely as a coding aid – to help programmer code with some descriptive names instead of messing with pure numeric values. Similar to what constants are for, except Enums provide a set of values for describing a single parameter. Instead of: product.Quality = 3;
the programmer would write: product.Quality = Quality.Good;
… providing that Quality Enum is declared something like: public enum Quality
{
JustBad, Poor, OK, Good, Excellent
}
Of course, you could set your enum values to some concrete numbers, like: public enum Quality
{
JustBad = 1, Poor = 2, OK = 3, Good = 4, Excellent = 5
}
… but in most cases you shouldn’t need to. Like I said, I see Enums only as a before-compilation, human <-> code communication, and therefore I believe no part of Enum should ever see the light of day (i.e. be exposed to the UI). And with that, there goes the need for binding to Enums…
Why would I want to bind to Enums anyway? Enum enumerators have no description (other than their names). If you need to provide spaces or even support localized descriptions, you’ll need to extend them significantly, so why not create a new class anyway? Here’s what I use instead of an Enum: public sealed class Quality
{
public const int JustBad = 1;
public const int Poor = 2;
public const int OK = 3;
public const int Good = 4;
public const int Excellent = 5;
public Dictionary<int, string> Collection { get; private set; }
public Quality()
{
Collection = new Dictionary<int, string>()
{
{JustBad, "Just bad :("},
{Poor, "Poor"},
{OK, "OK"},
{Good, "Good"},
{Excellent, "Excellent!"},
};
}
}
The programmer would still write: product.Quality = Quality.Good;
so it makes it easy to refactor existing code. Additionally, you can put in any description for the values, support localization, and it’s easy bindable in Xaml - declare the class instance as a local resource: <local:Quality x:Key="quality" /> and bind away: <ListBox DisplayMemberPath="Value"
ItemsSource="{Binding Collection, Source={StaticResource quality}}" />
http://www.singular.co.nz/blog/archive/2007/12/20/shortguid-a-shorter-and-url-friendly-guid-in-c-sharp.aspx
转帖,来自 http://news.wenxuecity.com/messages/200902/news-gb2312-796337.html 美国公司杂记 笔者进入美国生物制药公司研发部门工作一晃也有五六个年头了,在其中既被人管理也 管理着别人。近日总有一种冲动想将自己的所见,所闻,所想记录下来,既是一种阶段 总结,也想静下心来挖掘一下自己的内心世界,看看自己拥有了什么,还有哪些不足。 因此写下这篇博文,与大家共享。俗话说"文以载道",如果本文能引起一些共鸣或起到 一些有益的作用,"善莫大焉";如果您认为是无稽之谈,则可一笑置之。"佛法无边, 只渡有缘之人"。 我们 每个人都用自己的眼睛看这个世界,同一个世界在每个个体的眼睛中是不同的, 因此个体对世界的认识与客观事实存在着差距,所谓真理只是对真实世界的无限接近, 但永远不是真实的存在本身。因此,"真理永远在认识之后,存在之前"。我们对世界的 认识大多时候停留在"认知"阶段,距离"真理"尚相差甚远,更别提"存在"本身了。另外 ,笔者是土生土长的中国人,在中国接受的高等教育,是以一个中国人的视觉来看待美 国公司,虽耳濡目染美国文化,但看待美国文化下的美国公司只是一家之言。因此名为 "杂记"。 首先一个问题是美国公司是什么?对这个问题可能政治或经济学家有更精确的定义。但 笔者认为就是中国的大集体或信用合作社,它是具有不同专业或文化背景的个体聚集在 一起求生存求发展的一种组织形式,即所谓的"Corporate System"。它在遵守国家法律 的前提下,有自己的规章制度及文化。既然它是一个大集体,那么当个体的利益与集体 利益有冲突的时候,个体利益将不得不服从集体利益。因此公司就相当于一个滚动的轴 轮,员工好比轴轮中的钢珠,圆溜溜的钢珠会帮助轴轮顺利地滚动向前,但是钢珠是不 能有棱角的,否则会卡住其它的钢珠,影响车轮的前行;时间长了,在公司这个车轮中 每个员工的棱角都会被磨去,变得圆溜溜的。因此美国公司是抹杀员工个性的场所。美 国的民主制度,什么自由精神,独立人格是排除在公司之外的。这并不是说你不能有个 性,只是说你的个性不能影响你的工作。如果你是理想主义者而追求这样的东西,大公 司的工作会让你非常失望。但是大公司的好处就是"众人划桨开大船",集体的力量有时 大于个体力量的简单相加,如果各部门协作得当,大家各用其长,每人都会从他人的长 处中得益。缺点也是不言而喻,就是个体的影响力有限,另外就是"林子大了什么鸟都 有","南郭先生"会比比皆是,因此优秀员工的贡献会被这些"先生"们抵消,更可怕的 是有时互相扯皮,内斗不可避免。在美国的大公司工作就像吃社会主义大锅饭一样,像 一个大馒头,每个人都在吃,但许多人从来不会考虑新馒头在哪里。这时候资本主义社 会的竞争性这一特点的优越性就显示出来了,资本市场会要求上市公司为出效益而精益 求精,公司内部上级也会要求下级出成绩,因此扯皮或内斗在健康的公司里会限制在一 定范围内。另外,高科技公司的研发部门是科学为主导,结果为绩效的单位,单纯靠搞 阶级斗争是持久不了的。上文讲到,公司里尤其是大公司里是没有独立人格及自由精神 的,任何人都有好几层的领导,因此这里的工作并不是适合所有的人,有时并不能帮助 自己发挥出自己的最大潜能。 下面我来谈谈公司的管理体制。一般来说,美国生物制药公司实行的是金字塔式的管理 ,很像军队中的管理,下级服从上级,遵循责权利相结合的原则。因为老板具有给其直 接领导下的员工评分的权力(直接影响到年终奖及加薪的多少),因此一般会得到下属的 尊重,利于管理。就一个职能部门而言,部门主管(VP或DIRECTOR)处于金字塔的塔尖, 他/她对部门的效益负责,同时往往也是该部门员工的上帝,在年终升职加薪奖金的评 定中拥有生杀予夺的权力。因此,美国大公司是颇为专制的一言堂,如上文所讲,在这 时是没有民主的。这种只有集中没有民主的集权可以起到令行禁止的作用,减少了部门 内的摩擦。另外,部门主管的权力越大,他/她的责任也越大。往往我们可以看到某某 Executive年薪达多少多少,但往往我们没有想到的是他/她们承受的压力有多大,能够 做到那个位置付出了多少,是多少好运气的迭加。(He or she must have done something right, probably many many times - 明白了这一点,我们或许会少一点怨 气,多一点平和之气)。上面提到了军队的管理及职能部门的概念,笔者认为制药公司 的研发单位相似于战争中的野战部队:各个疾病研发部门好比野战兵团,负责攻城拔寨 (开辟药物研发的战场);许多支持部门好比工程部队或后勤,负责协调支持;也有许 多专门技术部门,好似炮兵或导弹部队,应用得当可立奇功。(假想敌是各种重大疾病 ,但往往因为敌人太强大,多数战役会以失败收场)。公司内部等级森严,军衔林立, 论资排辈。另外值得指出的是,药物研发的终级或者说是唯一目标是新药上市,但是从 项目的酝酿到新药上市要十年以上的时间,花费十数亿美金,而在此期间是没有人真正 知道最终结果的(大概95%或以上的项目会失败)。因此很难对某一个部门限定硬性指标 ,而管理层就会设定一些阶段性或软指标来作为年终评定绩效的手段,而这些手段都是 人定的,领导的年终奖金会取决于这些阶段性成果的数量,因此"拔苗助长"或"大跃进" 往往比较普遍。这有点像现在经济危机中的华尔街或者放贷经纪人,反正已经凭此升官 发财了,哪里会管得了以后的事情。 了解了公司的管理体制,下面来谈一下如何在公司里争取自己的最大利益。 笔者认为首先应该"修身"与"自强",努力提高自己的业务素养,使自己不但能够胜任自 己当前的工作,同时也时刻准备着胜任更有挑战性的任务。另外,常言道" 艺不压身" ,我们应该充分利用工作中的资源,不断学习新的技术及管理经验。特别是当今生物医 学知识及技术日新月异,在这个领域工作当真如"逆水行舟",不进则退,客观上也要求 我们去不断学习。古人云"朝闻道,夕死可矣",我们应该欢迎这种积极进取乐观向上的 生活态度。因此,我们在公司里应该争取各种培训机会(尽量事先给自己的管理层沟通 ,争取得到支持)。笔者非常推崇的一句格言 - 天行健,君子以自强不息;地势坤,君 子以厚德载物 - 应该在美国也有现实意义。奥林匹克精神所推崇的"更高,更快,更强 "的"超越自我"的精神是全人类共同的美德。这里我想到了两个例子。一个是金庸先生 ,他的 "飞雪连天射白鹿,笑书神侠倚碧鸳"武侠系列小说可以讲是前无古人,给予了 我们芸芸众生无数的美好时光;他的无数社评及政论性文章一针见血,令人拍案叫绝。 就是这样一个令人高山仰止的文学大家,在耆耄之年仍坚持进入牛津大学历史系攻读博 士学位,求知精神可歌可泣;另一个例子是演艺圈的李连杰,成龙,周润发等人,当年 他们在香港事业如日中天之时,为追求更大的舞台,毅然转到美国好莱坞发展,这种超 越自我的精神令人赞赏。大家不要以为好莱坞等着他们去赚钱,他们在香港的名气与经 历作用并不大,后来的成功是一步一步打拼而来的。特别是李连杰先生,成功后虚怀若 谷,致力于慈善事业,是当代艺人的典范。美国最伟大的总统之一THOMAS JEFFERSON也 强烈认为教育是一个终生学习的过程。现代心理学认为人感到幸福往往是因为认识到了 自己对他人或社会有用(当然这可能是更高层次的一种幸福),我们应争取让自己的生命 之花开出更为耀眼的光华。除开这些原因之外,在当代美国社会里,公司为了自己的生 存进行裁员是家常便饭,因此很难让员工对公司保持有一定程度的忠诚。客观上也让我 们每个人在工作中保持"危机感",而保证自己工作职位安全第一要素是自己的"履历表" ,因此我们工作中应致力于不断完善它。因此"自强"是公司里生存的第一要素。但是, 惰性往往是人的天性,有时人在一个舒适的环境里待久了,反而丧失了斗志;拥有过多 有时会成为累赘,不是一件好事,这是生活的辨证法。 公司内争取自己的最大利益,还应该注意与领导的有效沟通。俗话说,会叫的孩子有奶 吃;你只有向上帝要东西,上帝才会给你,否则上帝怎会知道你的心事。升职加薪的机 会往往需要自己去争取,否则领导还以为你满意于目前的职位,而将机会给予了表现不 如你的同僚。但是一定要有策略及一定程度的耐心,比如说时刻注意要当老板的助手而 不要成为竞争对手(黄金定律),让领导的领导欣赏你等等,也要注意物极必反的道理。 上文讲到,大公司里军衔林立,除非你为公司做出了重大贡献或你的老板坐了直升机大 幅升迁,员工大幅升职加薪的机会是较少的。千万不要为了蝇头小利而与老板过不去, 给老板斗争胜利的例子不是没有,但是很少。原因不言而喻,公司一般会认为老板的作 用会比下属大,因此失去他/她比失去属下损失更大,或者说老板具有更大的"不可替代 性"。因此,除非你确信你在公司的地位比你的老板更重要,一般轻易不要给老板闹别 扭。有时争取利益的同时意味着妥协与忍耐,在各种具体情况下应对策略见人见智。很 多情况下应该具有权衡利弊的智慧。适用于法律的颁布,法庭的裁决,新药的批准,医 生的处方等等情况的黄金准则 - 两利相权取其重,两害相权取其轻 - 也应该适用于公 司里最大利益的争取。"此地不留爷,自有留爷处"应是最后的选择,因为到一个新的公 司原来的积累可能会烟消云散,面临的问题可能会更多。有时可以进行一下换位思考或 反向思考,比如说如果我是老板或属下该如何处理这件事,会怎么想;我做了或不做这 件事会不会后悔等。虽说权衡利弊是理性的思考,但有时要"跟着感觉走",FOLLOW YOUR HEART 才是最后的答案。 有效的MARKETING也很重要。大家都知道以前的皇帝或官员出巡,八抬大轿一抬,前面 鸣锣开道,后面鼓乐齐名。抬轿的出力,鸣锣的出人,各有各的用处,抬轿的有时就觉 得自己亏,但是要吹乐鸣锣人家得让你去,自己必须去争取。另外,老板看中的是员工 能否给他们解决问题,因此应该在恰当的时候SHOW OFF。比如每年的10月份评定级效, 成绩应该集中在夏秋季出来,上半年的成绩会很容易被遗忘。 下面探讨一下如何在公司里保持健康快乐的心态。 一句话,不以物喜,不以己悲。要有一种"世事我曾努力,成败不必在我"的达观心理。 上文讲过,大公司里个人对公司的影响有限,因此员工个人虽然要如上所述要获取自己 的最大利益,但一旦不能如愿,千万不要把自己当回事,否则万千烦恼丝会接踵而来。 本人的一位在业界非常成功的朋友曾经对我说:在公司里面做事,也就是问自己两个问 题,一是身体是否健康,二是职位是否稳定,如果回答都是"YES"的话,就要祝福自己 了。另一位更绝,他说在公司里"既不要把自己当男人,也不要把自己当女人,领导说 是什么人就是什么人"。工作必须完成得漂亮,但工作时不要老是想着升职加薪。就像 武侠小说中的练剑,心中无剑,方能将剑练到至高境界。大概姚明或TIGER WOODS在每 一下投篮或击球的时候,是不会想到那一下子会赚多少钱的吧。人是要有一点精神的, 记得有一个西方的哲人(记不得名字及出处了,实是不该)说过,人生有几个不同的境界 ,大致是 - 吃饱穿暖,吃好穿好,男欢女爱,受人尊敬,个人成就感。其中无须别人 承认的自我的成就感是最高的境界。美国的大公司里是不讲历史的,不论你以前做了多 大贡献,一切都是过去时,都在过去给你的工资奖金里面,不存在谁欠谁的问题,公司 给你工钱,你可以有一个像样的生活,不论你的职务有多高,你总是在夹心层,受夹板 气。还有,大公司里一朝天子一朝臣,机关算尽太聪明,反误了卿卿性命的故事一再上 演。年底的评级是相对的,总是横向拿你与同僚来比较,是各种因素平衡制约的结果, 如不满意,抗争一下是必要的,但要审时度势,量力而为。 公司里你不是一个人在战斗,因此与同事特别是老板的关系问题往往是引起我们郁闷的 主要原因之一。如上所述,除非万不得已,千万不能得罪老板。如果遇到太过强横的老 板,建议学习金庸先生的"九阳神功"- 他强由他强,他横由他横,我自一口气,明月照 大江。感觉金先生可能著作倚天是遇到过类似的事情而有感而发。也有对同事应不亢不 卑,但有时不应太过软弱,记住有时人们不是因为你对他们好而对你好,而是因为你不 好了而对他们不利才变得对你好。 下面我想谈谈公司里中国人比较关心的语言及歧视问题。 对于英语不是自己的母语的中国人而言,语言及随之而来的文化隔阂是进入较高管理层 的主要障碍之一。对于青春期(18岁)已过而来美国的人而言,每个人或多或少都会带有 一些口音,这一点信不信由你。我想要说的是,不要为了语言不好而妄自菲薄,高科技 公司雇佣你不是因为你的语言技能,而是因为你的专业技能为他们带来不同,只要你在 语言上的缺陷不影响工作就可以了。就像华为总裁任正非所说,人不能光盯着自己的缺 点,一个人一辈子如果只努力改造缺点,而不发挥优点的话,也会错过很多机会。但是 ,每个人都会同意我们应该花一辈子的精力去学习语言或改善自己的语言能力。有一个 木桶理论我想很多人听说过,决定木桶容量多少的关键不是最长的木条,而是最短的木 条,有时中国人的语言能力恰恰是影响自己发展的那根短木条。这也是许多人遇到的" 玻璃天花板问题"。在美国高科技公司里,我不能说没有歧视问题,但是总体感觉到不 是太严重,几十年的法律及规章制度上的积累已经把这个问题压缩到了很低的限度。 OBAMA成为了美国总统就是对这个问题的最好的答案。你拿不到那个位子,或者感到不 平等,往往并不是受到了歧视,而是你自己的能力还不足以胜任那份工作。比如说部门 主管,有时并不是科学或技术上能力强就足够的,你还需要说些鼓动人心的话,有一些 人格魅力等。作为第一代移民,我们具有语言上的先天不足,不得不花更多的时间,付 出更多的精力,才能够与美国同僚们站在一起(可以讲是其它方面不如你的同僚们),这 平等么,想想似乎不平等;但这是平等中的不平等,不平等中的平等,是社会多样化的 体现。但是我们也有自己的优势,比如对中国的了解,多年积累的勤奋精神,文化理解 上的多元化等等。 最后我想以这样一句话来与大家共勉:改变所能改变的,接受不能改变的,有智慧去区 分这两者的区别。衷心希望大家在各自平凡的位置上,作出不平凡的成就。 2009年2月15日完成于波士顿
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
a farm is a set of one or more server computers working together to provide WSS functionality to clients. An IIS Web site that has been specially configured to run WSS sites is known as a Web application. The installation of WSS creates and configures a Web application named the WSS 3.0 Central Administration application. a WSS site is a storage container for content. Site content is primarily stored in the form of lists, document libraries, and child sites. Second, a site is a securable entity whose content is accessible to a configurable set of users. A site can either define its own set of users, or it can inherit the users of its parent site. A site also contains a configurable set of groups and permissions that define the level of accessibility that various users have on the site’s lists and document libraries.Third, a site is an application with an extensible, fully customizable user interface. A site administrator can create pages and customize their layout and appearance. A site administrator can also modify a site’s navigation structure using the browser. Finally, a site is the foundation for using the Microsoft Web Part Page and Web Part technology. Every WSS site must be provisioned within the scope of an existing Web application. However, a site cannot exist as an independent entity within a Web application. Instead, every WSS site must also be created inside the scope of a site collection. A site collection is a container of WSS sites. Each site collection requires a top-level site. In addition to the required top-level site, a site collection can contain a hierarchy of child sites.  WSS 3.0 has added a valuable new innovation known as the site column. A site column is a reusable column definition that can be used across multiple lists. A site column defines the name for a column, its underlying field type, and other characteristics such as the default value, formatting, and validation. Once you have defined a site column, you can then use it as you define the schema for custom lists and document libraries. An obvious advantage is that you can update the site column in a single place and have that update affect all the lists where the site column has been used. WSS 3.0 adds a second powerful innovation focused on content storage. It is known as a content type. A content type is a flexible and reusable WSS type definition that defines the columns and behavior for an item in a list or a document in a document library. For example, you can create a content type for a customer presentation document with a unique set of columns, an event handler, and its own document template. You can create a second content type for a customer proposal document with a different set of columns, a workflow, and a different document template. Then you can create a new document library and configure it to support both of these content types. The introduction of content types is very significant to WSS 3.0 because it provides an ability that did not exist in WSS 2.0 to deal with heterogeneous types of content in lists and document libraries. Another great new development opportunity is to work with the new Office Open XML file formats. This new technology introduced with Microsoft Office 2007 provides you with the ability to generate and/or manipulate Microsoft Office Word documents and Microsoft Office Excel documents from server-side code within custom components such as event handlers and workflows. What’s nice is that the Office Open XML file formats eliminate the need to install and run a version of a Microsoft Office desktop application such as Office Word or Office Excel on the server. Everything can be done by programming against server-side libraries, which provide high degrees of scalability and robustness. Though there are many different avenues for custom development in WSS, you should start off by learning about features. Features are a new developer-focused innovation that has been added to WSS 3.0. Features provide a mechanism for defining site elements and adding them to a target site or site collection through a process known as feature activation. The element types that can be defined by a feature include menu commands, link commands, page templates, page instances, list definitions, list instances, event handlers, and workflows. At a physical level, a feature consists of a directory created within a special WSS system directory located within the file system of each front-end Web server. The directory for a feature contains one or more XML-based files that contain Collaborative Application Markup Language (CAML). By convention, each feature directory contains a manifest file named feature.xml that defines the high-level attributes of the feature, such as its ID and its user-friendly Title. While a custom feature allows a developer to define one or more elements that can be activated inside the context of a site or site collection, WSS also provides a developer with the ability to define the entire blueprint for a site by creating a custom site definition. The development of custom site definitions allows a developer to take control over every aspect of a new site such as its branding, its initial set of lists, and which features it uses. Chapter 9, “Solutions and Deployment,” is dedicated to working with site definitions. Another important aspect of WSS development is programming against the WSS object model. The core types provided by the WSS programming model are exposed through a standard WSS assembly named Microsoft.SharePoint.dll (under C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\ISAPI).
When you modify a page and save a customized version of it in the content database using SharePoint Designer, you eliminate the possibility of page ghosting. Instead, the provided SPVirtualPathProvider must retrieve the customized version of the page from the content database, as shown in Figure 2-6. For this reason, customized pages are sometimes referred to as unghosted pages. Pages that support user customization are known as site pages. This security concern is mitigated in WSS by having a default policy that prohibits in-line scripting in site pages. The default policy also runs site pages in a no-compile mode, which means they are not compiled into DLLs. WSS architecture provides another type of page known as an application page. One of the key characteristics of an application page is that it does not support customization. Therefore, application pages can circumvent some of the main performance concerns and security issues associated with site pages. Site pages support page customization. Examples of site pages include the home page (default.aspx) for a site as well as the pages associated with lists and document libraries, such as AllItems.aspx, NewForm.aspx, and EditForm.aspx. The fact that site pages support customization provides flexibility but can also impact performance and scalability. Site pages do not support in-line code under the default security policy enforced by WSS. Application pages do not support customization, which gives them two distinct advantages over site pages. First, each application page is always compiled into a single DLL so that it performs and scales better than a site page. Second, application pages are allowed to have in-line code. Now that you have a basic understand of what constitutes an application page, it will be worthwhile to see what is involved in creating your own application pages for a custom solution. Ghosted and uncustomized are terms used to describe site pages served up using file system templates. Unghosted and customized both refer to pages that exist entirely in the database, which no longer depend on a file system template. Debug WSS Components <configuration>
<SharePoint>
<SafeMode CallStack="true" />
</SharePoint>
<system.web>
<customErrors mode="Off" />
<compilation debug="true" />
</system.web>
</configuration>Two Tokens: ~site ~sitecollection
~masterurl/default.master ~masterurl/custom.master Site Page
A Module element can be thought of as a file set. When you create a Module, you add one or more inner File elements. The key point is that each File element is used to provision an instance of a file from a file template. Remember that the file template exists on the file system of the front-end Web server, whereas the file instance being provisioned is being created inside the context of a particular site.
Inside the TEMPLATE directory resides a nested directory named CONTROLTEMPLATES. This directory contains many different user controls that are deployed as part of the standard WSS installation. The CONTROLTEMPLATES directory is also a place where you should deploy custom user control files.
Site pages and application pages use separate master pages.
A Web Part is a class that inherits from the WebPart class defined in the System.Web.UI.WebControls.WebParts namespace inside the System.Web assembly. The Web Part is a special type of Web control that is deployable inside of a Web Part Zone control after the initial page has been created and deployed.
The Web Part Manager class that SharePoint uses is SPWebPartManager, which is a bridge between the page’s Web Part Zone objects and the content database. When you add a Web Part to the page, you are actually adding a serialized instance of the Web Part to the content database.
Web Parts render inside of chrome. Chrome refers to the common user interface elements, such as a formatted title bar and borders around the Web Part’s body that the framework adds to controls. The chrome adds a bit of style to your Web Part in a way that is consistent with the user interface of the application.
A Web Part Verb is an action that is rendered in the Web Part menu by the Web Part framework as part of the chrome that is rendered around the control. The action can call a client-side function or a server-side handler.
Content types are a powerful new enhancement introduced in WSS 3.0. The central idea is that a content type defines the underlying schema for either an item in a list or a document in a document library. However, it’s important to understand that content types are defined independently outside the scope of any list or document library. After you have created a content type, you can use it across several different lists or several different document libraries.
For example, imagine you create a content type named Company that defines a set of columns for tracking information about a company. After creating this content type you could then create two different lists named Vendors and Customers and configure both of these lists to use the Company content type. This gives you something akin to polymorphism, because you have two different list types that contain homogeneous items that are defined by the same schema. With an application design such as this, you can write a Web Part by using the SPSiteDataQuery that queries across lists and sites to find and display all the items that have content based on the Company content type.
Content types also provide you with the ability to maintain heterogeneous content inside a single list or document library. For example, you can configure a single list to support multiple content types. Imagine a business scenario in which you need to track customers, and those customers may be either companies or individuals. The problem you face is that customers that are companies and customers who are individuals require different columns to track their information. The solution is to create two different content types for each type of customer and then to create a Customers list and configure it to support both content types.
Item-based content types are used exclusively in lists, and document-based content types are used exclusively in document libraries. You should observe that no content type can be used in a list and also in a document library.
In terms of general WSS architecture, it’s important to observe that a document library is really just a specialized type of list. Similar to any standard list.
A site definition is the top-level component in WSS that aggregates smaller, more modular definitions to create a complete site template that can be used to provision sites.
A site definition itself does not represent a creatable site template. Instead, a site definition contains one or more configurations, and these configurations are what appear to users as creatable site templates. Therefore, the STS site definition contains three different configurations: Team Site, Blank Site, and Document Workspace.
Note that almost everything that can be defined in a site definition can also be defined in a feature. Features should be used for implementation, and site definitions should be used to aggregate features into user-creatable site templates. Both the Features element and the site definition Project element share common XML schema defined inside wss.xsd.
Note that the resource format within CAML is $Resources:ResourceFile,ResourceName;, where ResourceFile is the name of the file and ResourceName is the name of the string within the file. The WSS runtime replaces this as it parses the CAML. Note that you can access the localized site definition (which is cached for the Internet Information Services [IIS] application lifetime) through the site-relative URL _vti_bin/owssvr.dll?Cmd=GetProjSchema.
position responsibilites. 1. What can I contribute to your company in the position? 2. What do you expect me to accomplish in the first 3 months, 6 months, year? resource to accomplish the responsibilities 3. what equipments do you have to make your products? 4. what equipments do you have to test your products? 5. what softwares are you using to help for your products? Level of authority 6. what is the level of the authority for this position? :)没加工 Performance evaluation 7. How do you evaluate your employee? Culture of company 8. What is the culture of your company? --------------------
9.what is your lead style? 10. what is challenging in your work? 11.what aspects of your products are you satisfied with, unsatisfied with? how do you improve them? 12. what do you plan to lower your cost? improve your yield? 13. do you have any concerns about how I fit this position?
App-Domain could not be created. Error: 0x80131902Mike Stone tonight came across an interesting issue, not with rainbow, but an issue nonetheless. When he downloaded and went to run Rainbow 2.0 He came accross the following message "Failed to execute request because the App-Domain could not be created. Error: 0x80131902" Basically, this happens on first time 2.0 runs sometimes, not sure why, but the following seems to fix the problem. My suspicions and research lead me to believe it has to do with web servies referenced. To fix it, try the following.... - With a command window, get to the latest version of .net under
- C:\Windows\Microsoft.Net\Framework\
- Now run the following command: "net stop w3svc" to stop web services.
- Then use "aspnet_regiis.exe -ua" to uninstall all instances of ASP.NET from IIS.
- Follow with "aspnet_regiis.exe -i" to install ASP.NET into IIS.
- Now restart web services with "net start w3svc".
Published venerdì 10 marzo 2006 4.52 by Jonathan
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();
}
http://msdn.microsoft.com/en-us/ms741997(VS.85).aspx // Begins the storyboard.
private void beginButton_Clicked(object sender, RoutedEventArgs args)
{
// Specifying "true" as the second Begin parameter
// makes this storyboard controllable.
myStoryboard.Begin(this, true);
}
// Pauses the storyboard.
private void pauseButton_Clicked(object sender, RoutedEventArgs args)
{
myStoryboard.Pause(this);
}
// Resumes the storyboard.
private void resumeButton_Clicked(object sender, RoutedEventArgs args)
{
myStoryboard.Resume(this);
}
// Advances the storyboard to its fill period.
private void skipToFillButton_Clicked(object sender, RoutedEventArgs args)
{
myStoryboard.SkipToFill(this);
}
// Updates the storyboard's speed.
private void setSpeedRatioButton_Clicked(object sender, RoutedEventArgs args)
{
// Makes the storyboard progress three times as fast as normal.
myStoryboard.SetSpeedRatio(this, 3);
}
// Stops the storyboard.
private void stopButton_Clicked(object sender, RoutedEventArgs args)
{
myStoryboard.Stop(this);
}
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
To access the console session, do this: start | run - mstsc -v:0.0.0.0 /f -console (replace the 0.0.0.0 with your ipaddress)
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://channel9.msdn.com/posts/jmazner/How-To-Tell-Vistas-UAC-What-Privelege-Level-Your-App-Requires/ http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=1439749&SiteID=1 (Might work) #include "stdafx.h" // includes <tchar.h>
#include <windows.h>
#include <shobjidl.h> // ShellLink
#include <shlobj.h> // IShellLinkDataList (build on Vista use shobjidl.h)
#include <objbase.h> // CoInitialize, CoInitializeEx, CoUninitialize
int _tmain(int argc, _TCHAR* argv[])
{
HRESULT result;
WCHAR wbuf[MAX_PATH];
IShellLink* link;
IPersistFile* file;
char szFile[MAX_PATH];
char szProgramMenuFolder[MAX_PATH];
// SHOULD use CoInitializeEx, but compiler can't find it.
result = CoInitialize(NULL); // For Ex: 2nd param: COINIT_APARTMENTTHREADED
// Create IShellLink object
result = CoCreateInstance(CLSID_ShellLink,
NULL,
CLSCTX_INPROC_SERVER,
IID_IShellLink,
(void**)&link);
if (result != S_OK) {
CoUninitialize();
return -1;
}
// Retreive the IPersistFile
result = link->QueryInterface(IID_IPersistFile, (void**)&file);
if (result != S_OK) {
link->Release();
CoUninitialize();
return -2;
}
// SHOULD get from registry.
strcpy(szProgramMenuFolder, "C:\\ProgramData\\Microsoft\\Windows\\Start Menu\\Programs\\");
// DEBUG
strcpy(szFile, szProgramMenuFolder);
// SHOULD use your folder and shortcut name.
strcat(szFile, "Program Shortcut Folder\\Shortcut.lnk");
// Convert the filename
MultiByteToWideChar(CP_ACP, 0, szFile, -1, wbuf, sizeof(wbuf)-1);
// Load the link data from the file
result = file->Load(wbuf, STGM_READ);
if (result != S_OK) {
file->Release();
link->Release();
CoUninitialize();
return -3;
}
// Look for IShellLinkDataList interface
IShellLinkDataList* pdl;
result = link->QueryInterface(IID_IShellLinkDataList, (void**)&pdl);
if (result != S_OK) {
file->Release();
link->Release();
CoUninitialize();
return -4; // Where did IShellLinkDataList go?
}
DWORD dwFlags = 0;
result = pdl->GetFlags(&dwFlags);
if (result != S_OK) {
pdl->Release();
file->Release();
link->Release();
CoUninitialize();
return -5;
}
// Only set SLDF_RUNAS_USER if it's not set, otherwise
// SetFlags returns an error.
if ((SLDF_RUNAS_USER & dwFlags) != SLDF_RUNAS_USER) {
result = pdl->SetFlags(SLDF_RUNAS_USER | dwFlags);
if (result != S_OK) {
pdl->Release();
file->Release();
link->Release();
CoUninitialize();
return -6;
}
}
else {
pdl->Release();
file->Release();
link->Release();
CoUninitialize();
return 0;
}
result = file->Save(NULL, true);
if (result != S_OK) {
pdl->Release();
file->Release();
link->Release();
CoUninitialize();
return -8;
}
result = file->SaveCompleted(NULL);
if (result != S_OK) {
pdl->Release();
file->Release();
link->Release();
CoUninitialize();
return -9;
}
pdl->Release();
file->Release();
link->Release();
CoUninitialize();
return ERROR_SUCCESS;
}
http://code.msdn.microsoft.com/mef The Managed Extensibility Framework (MEF) provides developers with a tool to easily add extensibility to their applications and with minimal impact on existing code. The application developer can define extension points according to the functionality required of an extension, while the extension developer uses those points to interact with the application. MEF enables this extensibility to take place without creating a hard dependency in either direction. Applications can be extended at run time without recompilation, and extensions can be used by multiple applications sharing the same extension requirements. MEF also allows an application to delay the loading of an extension while still examining its metadata, enabling efficient traversal of large catalogs of extensions.
http://www.cnblogs.com/nuaalfm/archive/2008/08/23/1274868.html 1: static void Main(string[] args) 2: { 3: int[] array = { 9,8,2,6,5,4,3,7,1}; 4: BubleSort(array); 5: for (int i = 0; i < array.Length; i++) 6: { 7: Console.WriteLine(array[i]); 8: } 9: } 10: static void BubleSort(int[] array) 11: { 12: for (int i = 0; i < array.Length; i++) 13: { 14: for (int j = 0; j < array.Length-i-1; j++) 15: { 16: if (array[j] > array[j + 1]) 17: { 18: int temp = array[j]; 19: array[j] = array[j + 1]; 20: array[j + 1] = temp; 21: } 22: } 23: } 24: } 25: 26: // Interface Implement 1 27: 28: public interface IArray 29: { 30: bool Compare(IArray IA); 31: } 32: public class Employee:IArray 33: { 34: public Employee(int age) 35: { 36: this.Age = age; 37: } 38: public int Age { get; set; } 39: public bool Compare(IArray IA) 40: { 41: return this.Age>((Employee)IA).Age; 42: } 43: } 44: class Program 45: { 46: static void Main(string[] args) 47: { 48: Employee[] array = { new Employee(23),new Employee(20),new Employee(19),new Employee(30)}; 49: BubleSort(array); 50: for (int i = 0; i < array.Length; i++) 51: { 52: Console.WriteLine(array[i].Age); 53: } 54: } 55: static void BubleSort(IArray[] array) 56: { 57: for (int i = 0; i < array.Length; i++) 58: { 59: for (int j = 0; j < array.Length-i-1; j++) 60: { 61: if (array[j].Compare(array[j + 1])) 62: { 63: IArray temp = array[j]; 64: array[j] = array[j + 1]; 65: array[j + 1] = temp; 66: } 67: } 68: } 69: } 70: } 71: 72: //Interface implement2 73: 74: class Program 75: { 76: static void Main(string[] args) 77: { 78: //Employee[] array = { new Employee(23),new Employee(20),new Employee(19),new Employee(30)}; 79: IComparable[] array = { 9, 8, 2, 6, 5, 4, 3, 7, 1 }; 80: BubleSort(array); 81: for (int i = 0; i < array.Length; i++) 82: { 83: Console.WriteLine(array[i]); 84: } 85: } 86: static void BubleSort(IComparable[] array) 87: { 88: for (int i = 0; i < array.Length; i++) 89: { 90: for (int j = 0; j < array.Length-i-1; j++) 91: { 92: if (array[j].CompareTo(array[j + 1])>0) 93: { 94: IComparable temp = array[j]; 95: array[j] = array[j + 1]; 96: array[j + 1] = temp; 97: } 98: } 99: } 100: } 101: } 102: 103: 104: //Interface Implement 3 --- Inversion of control 105: class IntCompare:IComparer<int> 106: { 107: public int Compare(int x, int y) 108: { 109: return x.CompareTo(y); 110: } 111: 112: } 113: class Program 114: { 115: static void Main(string[] args) 116: { 117: //Employee[] array = { new Employee(23),new Employee(20),new Employee(19),new Employee(30)}; 118: int[] array = { 9, 8, 2, 6, 5, 4, 3, 7, 1 }; 119: BubleSort<int>(array,new IntCompare()); 120: for (int i = 0; i < array.Length; i++) 121: { 122: Console.WriteLine(array[i]); 123: } 124: } 125: 126: static void BubleSort<T>(T[] array,IComparer<T> compare) 127: { 128: for (int i = 0; i < array.Length; i++) 129: { 130: for (int j = 0; j < array.Length-i-1; j++) 131: { 132: if (compare.Compare(array[j], array[j + 1]) > 0) 133: { 134: T temp = array[j]; 135: array[j] = array[j + 1]; 136: array[j + 1] = temp; 137: } 138: } 139: } 140: } 141: } 142: 143: //Delegate implementation 144: class Program 145: { 146: static void Main(string[] args) 147: { 148: //Employee[] array = { new Employee(23),new Employee(20),new Employee(19),new Employee(30)}; 149: int[] array = { 9, 8, 2, 6, 5, 4, 3, 7, 1 }; 150: BubleSort<int>(array, CompareMethod); 151: for (int i = 0; i < array.Length; i++) 152: { 153: Console.WriteLine(array[i]); 154: } 155: } 156: static bool CompareMethod(int t1, int t2) 157: { 158: return t1 > t2; 159: } 160: delegate bool Compare<T>(T t1, T t2); 161: static void BubleSort<T>(T[] array, Compare<T> compare) 162: { 163: for (int i = 0; i < array.Length; i++) 164: { 165: for (int j = 0; j < array.Length-i-1; j++) 166: { 167: if (compare(array[j], array[j + 1])) 168: { 169: T temp = array[j]; 170: array[j] = array[j + 1]; 171: array[j + 1] = temp; 172: } 173: } 174: } 175: } 176: } 177: 178: //Lamda function implementation 179: class Program 180: { 181: static void Main(string[] args) 182: { 183: //Employee[] array = { new Employee(23),new Employee(20),new Employee(19),new Employee(30)}; 184: int[] array = { 9, 8, 2, 6, 5, 4, 3, 7, 1 }; 185: BubleSort<int>(array, (a,b)=>a>b); 186: for (int i = 0; i < array.Length; i++) 187: { 188: Console.WriteLine(array[i]); 189: } 190: } 191: static void BubleSort<T>(T[] array, Func<T,T,bool> compare) 192: { 193: for (int i = 0; i < array.Length; i++) 194: { 195: for (int j = 0; j < array.Length-i-1; j++) 196: { 197: if (compare(array[j], array[j + 1])) 198: { 199: T temp = array[j]; 200: array[j] = array[j + 1]; 201: array[j + 1] = temp; 202: } 203: } 204: } 205: } 206: }
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.
http://www.15seconds.com/issue/020417.htm ASP.NET request processing is based on a pipeline model in which ASP.NET passes http requests to all the modules in the pipeline. Each module receives the http request and has full control over it. The module can play with the request in any way it sees fit. Once the request passes through all of the HTTP modules, it is eventually served by an HTTP handler. The HTTP handler performs some processing on it, and the result again passes through the HTTP modules in the pipeline.  Notice that during the processing of an http request, only one HTTP handler will be called, whereas more than one HTTP modules can be called.
To solve this, we have to manually add the mouse event handler onto the controls and set the handled parameter to true. this.tbId.AddHandler(TextBox.MouseDownEvent, new RoutedEventHandler(tb_mouseDown), true);
_strandGroup = this.listViewGroups.SelectedItem as StrandGroup;
<GridViewColumn Header="Strand Type"> <GridViewColumn.CellTemplate> <DataTemplate> <ComboBox SelectedValue="{Binding Path=StrandId}" SelectedValuePath="Id" DisplayMemberPath="Name" Width="120" GotFocus="ComboBox_GotFocus" SelectionChanged="ComboBoxStrandType_SelectionChanged" ItemsSource="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type local:LongitudinalStrandGroupsAssist}}, Path=MPrestressedStrands}"/> <DataTemplate> </GridViewColumn.CellTemplate> </GridViewColumn>
From http://dotnet.org.za/rudi/archive/2008/03/25/10-things-i-didn-t-know-about-wpf-data-binding.aspx 1) Binding path "(TextBox.Text)" vs "Text"? If you bind to a path called Text, WPF uses reflection to resolve the name. If you use the class-qualified name, binding avoids the reflection performance hit. Class-qualified names also allows binding to attached properties! 2) WPF doesn't raise exceptions to notify you about data binding problems All binding errors are output as trace information and NOT exceptions! Beatriz Costa (Who else) has a excellent article about this 3) Why use OneWayToSource binding mode? Well, the target object must always be a DP! The most common use of OneWayToSource mode is to by-pass this restriction! The source doesn't need to be a DP and effectively using OneWayToSource reverses the binding direction. A perfect example is Run, it's text property is not backed by a DP! 4) Default binding mode? Not all DP's have the same default binding mode!!! If the binding mode is two-way, but the CLR property that it is bound to is read-only... will cause problems! just keep in mind that you can't assume what the binding mode is!!! It is always a good idea to explicitly specify your binding mode. Also remember that OneWay is slightly lighter than TwoWay! 5) RelativeSourceMode.PreviousData If you bind to a collection of prices and need to show the change from the previous price to the current price then this little trick can be very useful... Pass the current item and the following binding into a IMultiValueConverter converter {Binding RelativeSource={RelativeSource PreviousData}}
The multi value converter now just need to work out what the difference is!
6) RelativeSourceMode.FindAncestor
This is a very cool hack I found... Lets assume that you have a ListBox showing data. Normally if you have a TextBlock inside your DataTemplate and you don't supply it with a foreground color, then it would inherit the parents Foreground property. What is cool about this is that then when you click on the item, the font color would change from black to white! Now assume that your DataTemplate also contains a custom control that do not rely on the Foreground property to determine its color (As a example, I will use a Ellipse which has a Fill and not a Foreground/Background). If I add a Ellipse to this DataTemplate and I do not set its fill, it would stay blank. Even if I give it a Fill color, it will fill with this color but if I now select this ListBox item, it will stay the provided color!
So how do I make my ellipse inherit the Foreground color and more importantly, how do I make it change to white once selected? Binding its Fill with the following {Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListBoxItem}}, Path=Foreground}
Now, it will inherit the parents Foreground and also change once selected...
7) Binding a ListBox to a custom object, What gets displayed in the ListBox?
When binding to a custom object, determining what is displayed in the ListBox can be one of 3 options
- Set the DisplayMemberPath on the ListBox to a path
- Create a DataTemplate
- Override the ToString() on the custom object. If no DisplayMemberPath or DataTemplate is found, the ToString() is called on the custom object.
8) {Binding Path=/}
Bind to the current item in the view! Just remember to set IsSynchronizedWithCurrentItem to true
[UPDATE] While reading Ian Griffiths blog, I found a entry detailing this behaviour in WPF databinding
9) Binding has a constructor that take Path as a parameter
This is just a small shortcut {Binding Path=Name}
Can be written like this {Binding Name}
10) {Binding}
This looks a little weird but all this means is that the source is defined somewhere up the tree... common place is Window.DataContext. By setting the DataContext to a collection, I can now add a ListBox to the visual tree and then binding this ListBox's ItemsSource to {Binding}. This will tell the ListBox that its ItemsSource is the DataContext of the Window!
http://edu.sina.com.cn/en/2008-06-02/105342486.shtml - Do you have any pet peeve? 你有什么样的怪毛病吗?
- Maybe I’m going out on a limb, but I think we still have to invest it.或许这么作有点冒险, 但我想我们还是要投资它.
- I don’t have skeleton in my closet.我没有什么不可告人的秘密.
- Are you sure you are going to set us up?你确定你要帮我们制造机会吗? (fix up, hook up)
- Probably. It’s still up in the air.大概吧. 但还不确定. "I haven’t decided yet." "I haven’t made my mind yet." 或是 "We’ll see." 就可以了, 不然的话你也可以小小地卖弄一下英文, "It’s up in the air."
- Okay. Just checking.好吧. 我只是随囗问问.
- Do we need to hit a shower first?我们需要先洗个澡吗?
- That’s OK.不用了.
- Just right place, right time.只不过是天时地利而已.
- Same here.我也是.
God works. 上帝的安排。 Not so bad. 不错。 No way! 不可能! Don't flatter me. 过奖了。 Hope so. 希望如此。 Go down to business. 言归正传。 I'm not going. 我不去了。 Does it serve your purpose? 对你有用吗? I don't care. 我不在乎。 None of my business. 不关我事。 It doesn't work. 不管用。 Your are welcome. 你太客气了。 It is a long story. 一言难尽。 Between us. 你知,我知。 Sure thing! 當然! Talk truly. 有话直说。 I'm going to go. 我這就去。 Never mind. 不要緊。 Why are you so sure? 怎么这样肯定? Is that so? 是这样吗? Come on, be reasonable. 嗨,你怎么不讲道理。 When are you leaving? 你什么时候走? You don't say so. 未必吧,不至于这样吧。 Don't get me wrong. 别误会我。 You bet! 一定,当然! It's up to you. 由你决定。 The line is engaged. 占线。 My hands are full right now. 我现在很忙。 Can you dig it? 你搞明白了吗? I'm afraid I can't. 我恐怕不能。 How big of you! 你真棒! Poor thing! 真可怜! How about eating out? 外面吃饭怎样? Don't over do it. 别太过分了。 You want a bet? 你想打赌吗? What if I go for you? 我替你去怎么样? Who wants? 谁稀罕? Follow my nose. 凭直觉做某事。 Cheap skate! 小气鬼! Come seat here. 来这边坐 Dinner is on me. 晚饭我请。 You ask for it! 活该! You don't say! 真想不到! Get out of here! 滚出去! How come… 怎么回事,怎么搞的。 Don't mention it. 没关系,别客气。 It is not a big deal! 没什么了不起! thousand times no! 绝对办不到! Who knows! 天晓得! Have a good of it.玩的很高兴。 Don't let me down. 别让我失望。 It is urgent. 有急事。 Can I have this. 可以给我这个吗? It doesn't take much of you time. 这不花你好多时间。 Drop it! 停止! Bottle it! 閉嘴! There is nobody by that name working here.這裡沒有這個人。 Easy does it. 慢慢来。 Don't push me. 别逼我。 Come on! 快点,振作起来! What is the fuss? 吵什么? Still up? 还没睡呀? It doesn't make any differences. 没关系。 It is a deal! 一言为定! Take a seat! 请坐! Here ye! 说得对! It can be a killer. 这是个伤脑筋的问题。 Don't take ill of me. 别生我气。 It's up in the air. 尚未确定。 I am all ears. 我洗耳恭听。 Right over there. 就在那里。 Get an eyeful. 看个够。 Here we are! 我们到了! I lost my way. 我迷路了 Say hello to everybody for me. 替我向大家问好。 Not precisely! 不见得,不一定! That is unfair. 这不公平! We have no way out. 我们没办法。 That is great! 太棒了! You are welcome! 别客气! I'm bored to death. 我无聊死了。 Bottoms up! 干杯! Big mouth! 多嘴驴! Can-do. 能人。 Don''t play possum! 別裝蒜! He neither drinks nor smokes. 他既不喝酒也不抽煙。 Make it up! 不记前嫌! Watch you mouth. 注意言辞。 Any urgent thing? 有急事吗? Good luck! 祝你好运! Make it. 达到目的,获得成功。 I'll be seeing you. 再见。 I wonder if you can give me a lift? 能让我搭一程吗? It is raining. 要下雨了。 I might hear a pin drop. 非常寂静。 Don't get loaded. 别喝醉了。 Stay away from him. 别*近他。 Don't get high hat. 别摆架子。 That rings a bell. 听起来耳熟。 Play hooky. 旷工、旷课。 I am the one wearing pants in the house. 我当家。 Get cold feet. 害怕做某事。 Good for you! 好得很! Go ahead. 继续。 Help me out. 帮帮我。 Let's bag it. 先把它搁一边。 Lose head. 丧失理智。 He is the pain on neck. 他真让人讨厌。 Do you have straw? 你有吸管吗? Don't make up a story. 不要捏造事实。 Absence makes the heart grow fonder. 小别胜新婚。 She make a mess of things. 她把事情搞得一塌糊涂。 He has a quick eye. 他的眼睛很锐利。 Shoot the breeze. 闲谈。 Tell me when! 随时奉陪! It is a small world! 世界真是小! Not at all. 根本就不(用)。 Let's play it by ear. 让我们随兴所至。 Wait and see. 等着瞧。 Why so blue? 怎么垂头丧气? What brought you here? 什么风把你吹来了? Hang on! 抓紧(别挂电话)! Leave me alone. 别理我。 Chin up. 不气 ,振作些。 You never know. 世事难料。 I stay at home a lot. 我多半在家里。 She'll be along in a few minutes. 他马上会过来。 I'm not it a good mood. 没有心情(做某事)。 He is a fast talker. 他是个吹牛大王。 Daring! 亲爱的! She is still mad at me. 她还在生我的气。 I'll get even with him one day. 我总有一天跟他扯平 Hit the ceiling. 大发雷霆。 She's got quite a wad. 她身怀巨款。 I don't have anywhere to be. 没地方可去。 I'm dying to see you. 我很想见你。 I swear by the God. 我对天发誓。 Nothing tricky. 别耍花招。 You might at least apologize. 你顶多道个歉就得了。 Price is soaring, if it goes on like this, we shall not be able to keep the pot boiling. 物价直线上升,这样子下去,我们锅里可没什么东西煮饭。 None of you keyhole. 不准偷看。 You don't seem to be quite yourself today. 你今天看起来不大对劲。 Do you have any money on you? 你身上带钱了吗? What is your major? 你学什么专业? My girlfriend and I broke up. 我和我的女朋友吹了。 It was something that happens once in the blue moon. 这是千载难逢的事。 I'll kick you out. 我将炒你鱿鱼。 I hate to be late and keep my date waiting. 我不喜欢迟到而让别人久等。 There is nobody by that name working here. 这里没有这个人。 He neither drinks nor smokes. 他既不喝酒也不抽烟。 He pushes his luck. 他太贪心了。 Nuts! 呸;胡说;混蛋! I can't make both ends meet. 我上个月接不到下个月,缺钱。 It is of high quality. 它质量上乘。 Dead end. 死胡同。 Would you mind making less noise. 能不能小声点
http://geekswithblogs.net/thibbard/archive/2008/05/20/wpf---collectionviewsource-that-updates-automatically.aspx public class AutoRefreshCollectionViewSource : CollectionViewSource
{
protected override void OnSourceChanged(object oldSource, object newSource)
{
if (oldSource != null)
{
SubscribeSourceEvents(oldSource, true);
}
if (newSource != null)
{
SubscribeSourceEvents(newSource, false);
}
base.OnSourceChanged(oldSource, newSource);
}
private void Item_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
bool refresh = false;
foreach (SortDescription sort in SortDescriptions)
{
if (sort.PropertyName == e.PropertyName)
{
refresh = true;
break;
}
}
if (!refresh)
{
foreach (GroupDescription group in GroupDescriptions)
{
PropertyGroupDescription propertyGroup = group as PropertyGroupDescription;
if (propertyGroup != null && propertyGroup.PropertyName == e.PropertyName)
{
refresh = true;
break;
}
}
}
if (refresh)
{
View.Refresh();
}
}
private void Source_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
if (e.Action == NotifyCollectionChangedAction.Add)
{
SubscribeItemsEvents(e.NewItems, false);
}
else if (e.Action == NotifyCollectionChangedAction.Remove)
{
SubscribeItemsEvents(e.OldItems, true);
}
else
{
// TODO: Support this
Debug.Assert(false);
}
}
private void SubscribeItemEvents(object item, bool remove)
{
INotifyPropertyChanged notify = item as INotifyPropertyChanged;
if (notify != null)
{
if (remove)
{
notify.PropertyChanged -= Item_PropertyChanged;
}
else
{
notify.PropertyChanged += Item_PropertyChanged;
}
}
}
private void SubscribeItemsEvents(IEnumerable items, bool remove)
{
foreach (object item in items)
{
SubscribeItemEvents(item, remove);
}
}
private void SubscribeSourceEvents(object source, bool remove)
{
INotifyCollectionChanged notify = source as INotifyCollectionChanged;
if (notify != null)
{
if (remove)
{
notify.CollectionChanged -= Source_CollectionChanged;
}
else
{
notify.CollectionChanged += Source_CollectionChanged;
}
}
SubscribeItemsEvents((IEnumerable)source, remove);
}
}
Using the CollectionViewSource is a good way of binding to a datasource and letting the XAML determine the sorting and grouping of the data. However, as your datasource changes, the grouping and sorting is not automatically "re-calculated", forcing your code to be smarter that it should be. I found a class today on MSDN forums that inherits from CollectionViewSource and adds automatic refresh capabilities. This code is smart enough to resort your items, regroup your items and even add new groupings as needed. Some good CollectionViewSource links:
http://channel9.msdn.com/wiki/default.aspx/SecurityWiki.RegExInputValCode // Decomposed method which actually creates the pattern object and determines the match. // Used by all of the other functions. static bool MatchString(string str, string regexstr) { str = str.Trim(); System.Text.RegularExpressions.Regex pattern = new System.Text.RegularExpressions.Regex(regexstr); return pattern.IsMatch(str); } static bool IsValidUserName(string strUsername) { // Allows word characters [A-Za-z0-9_], single quote, dash and period // must be at least two characters long and less then 128 string regExPattern = @"^[\w-'\.]{2,128}$"; // We also permit email address characters in user name. Set to false // if you don't permit email addresses as usernames. bool allowEmailUsernames = true; if (allowEmailUsernames) { return (MatchString(strUsername, regExPattern) || IsValidEmailAddress(strUsername)); } else { return MatchString(strUsername, regExPattern); } } static bool IsValidPassword(string strPassword) { // Allows any type of character // If complexity is enabled, the password must be longer // and contain at least one uppercase, one lowercase, // one numeric and one symbolic character. Set to false // if your requirements differ. bool passwordComplexity = true; // These are some proposed minimum password lengths. If // complexity is enabled (above), the stronger (longer) // minimum password rule applies. int minPasswordLen = 6; int strongPasswordLen = 8; if(passwordComplexity) { string regExPattern = @"^.*(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[`~!@#\$%\^\&\*\(\)-_\=\+\[\{\]\}\\\|;:',<\.>/?]).*$"; return(strPassword.Length >= strongPasswordLen && MatchString(strPassword, regExPattern)); } else { return(strPassword.Length >= minPasswordLen); } } static bool IsValidName(string strName) { // Allows alphabetical chars, single quote, dash and space // must be at least two characters long and caps out at 128 (database size) string regExPattern = @"^[a-zA-Z-'\.\s]{2,128}$"; return MatchString(strName, regExPattern); } static bool IsValidStreetAddress(string strAddress) { // Since so many different types of address formats we're just going to swing the bat at // this one for now and do a match against a series of digits (potentially containing // punctuation), followed by a series of characters representing the street name and then // potentially a type of street and unit number string regExPattern = @"\d{1,3}.?\d{0,3}\s[a-zA-Z]{2,30}(\s[a-zA-Z]{2,15})?([#\.0-9a-zA-Z]*)?"; return MatchString(strAddress, regExPattern); } static bool IsValidCity(string strCity) { // Here we simply treat city names like people names and defer to our name validation function. return IsValidName(strCity); } static bool IsValidUSState(string strState) { // Names of 50 US States string[] stateNames= {"ALABAMA","ALASKA","ARIZONA","ARKANSAS","CALIFORNIA","COLORADO","CONNECTICUT","DELAWARE","FLORIDA","GEORGIA","HAWAII","IDAHO","ILLINOIS","INDIANA","IOWA","KANSAS","KENTUCKY","LOUISIANA","MAINE","MARYLAND","MASSACHUSETTS","MICHIGAN","MINNESOTA","MISSISSIPPI","MISSOURI","MONTANA","NEBRASKA","NEVADA","NEW HAMPSHIRE","NEW JERSEY","NEW MEXICO","NEW YORK","NORTH CAROLINA","NORTH DAKOTA","OHIO","OKLAHOMA","OREGON","PENNSYLVANIA","RHODE ISLAND","SOUTH CAROLINA","SOUTHDAKOTA","TENNESSEE","TEXAS","UTAH","VERMONT","VIRGINIA","WASHINGTON","WEST VIRGINIA","WISCONSIN","WYOMING"}; // Postal codes of 50 US States string[] stateCodes = {"AL","AK","AZ","AR","CA","CO","CT","DE","DC","FL","GA","HI","ID","IL","IN","IA","KS","KY","LA","ME","MD","MA","MI","MN","MS","MO","MT","NE","NV","NH","NJ","NM","NY","NC","ND","OH","OK","OR","PA","RI","SC","SD","TN","TX","UT","VT","VA","WA","WV","WI","WY"}; // This one is somewhat easier because we have a finite set of values to check against. // We simply uppercase our value anc check against our list. strState = strState.ToUpper(); ArrayList stateCodesArray = new ArrayList(stateCodes); ArrayList stateNamesArray = new ArrayList(stateNames); return (stateCodesArray.Contains(strState) || stateNamesArray.Contains(strState)); } static bool IsValidZIPCode(string strZIP) { // Allows 5 digit, 5+4 digit and 9 digit zip codes // must be at least two characters long and caps out at 128 (database size) string regExPattern = @"^(\d{5}-\d{4}|\d{5}|\d{9})$"; return MatchString(strZIP, regExPattern); } static bool IsValidUSPhoneNumber(string strPhone) { // Allows phone number of the format: NPA = [2-9][0-8][0-9] Nxx = [2-9][0-9][0-9] Station = [0-9][0-9][0-9][0-9] string regExPattern = @"^[01]?[- .]?(\([2-9]\d{2}\)|[2-9]\d{2})[- .]?\d{3}[- .]?\d{4}$"; return MatchString(strPhone, regExPattern); } static bool IsValidCCNumber(string strCCNumber) { // This expression is basically looking for series of numbers confirming to the standards // for Visa, MC, Discover and American Express with optional dashes between groups of numbers string regExPattern = @"^((4\d{3})|(5[1-5]\d{2})|(6011))-?\d{4}-?\d{4}-?\d{4}|3[4,7][\d\s-]{15}$"; return MatchString(strCCNumber, regExPattern); } static bool IsValidSSN(string strSSN) { // Allows SSN's of the format 123-456-7890. Accepts hyphen delimited SSN’s or plain numeric values. string regExPattern = @"^\d{3}[-]?\d{2}[-]?\d{4}$"; return MatchString(strSSN, regExPattern); } static bool IsValidEmailAddress(string strEmail) { // Allows common email address that can start with a alphanumeric char and contain word, dash and period characters // followed by a domain name meeting the same criteria followed by a alpha suffix between 2 and 9 character lone string regExPattern = @"^([0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9})$"; return MatchString(strEmail, regExPattern); } static bool IsValidURL(string strURL) { // Allows HTTP and FTP URL's, domain name must start with alphanumeric and can contain a port number // followed by a path containing a standard path character and ending in common file suffixies found in URL's // and accounting for potential CGI GET data string regExPattern = @"^^(ht|f)tp(s?)\:\/\/[0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*(:(0-9)*)*(\/?)([a-zA-Z0-9\-\.\?\,\'\/\\\+&%\$#_=]*)?$"; return MatchString(strURL, regExPattern); } static bool IsValidIPAddress(string strIP) { // Allows four octets of numbers that contain values between 4 numbers in the IP address to 0-255 and are separated by periods string regExPattern = @"^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$"; return MatchString(strIP, regExPattern); } static bool IsValidAlphaText(string strAlpha) { // Allows one or more alphabetical characters. This is a more generic validation function. string regExPattern = @"^[A-Za-z]+$"; return MatchString(strAlpha, regExPattern); } static bool IsValidAlphaNumericText(string strAlphaNum) { // Allows one or more alphabetical and/or numeric characters. This is a more generic validation function. string regExPattern = @"^[A-Za-z0-9]+$"; return MatchString(strAlphaNum, regExPattern); } static bool IsValidNumericText(string strNumeric) { // Allows one or more positive or negative, integer or decimal numbers. This is a more generic validation function. string regExPattern = @"/[+-]?\d+(\.\d+)?$"; return MatchString(strNumeric, regExPattern); }
/// <summary>
/// Information about the currently executing assembly, this is used to determine
/// our version, etc.
/// </summary>
private System.Reflection.Assembly m_assemblyInfo;
public string version
{
get
{
string ourVersion = string.Empty;
//if running the deployed application, you can get the version
// from the ApplicationDeployment information. If you try
// to access this when you are running in Visual Studio, it will not work.
if (System.Deployment.Application.ApplicationDeployment.IsNetworkDeployed)
ourVersion = ApplicationDeployment.CurrentDeployment.CurrentVersion.ToString();
else
if (m_assemblyInfo != null)
ourVersion = m_assemblyInfo.GetName().Version.ToString();
return ourVersion;
}
}
http://www.developerfusion.co.uk/show/2936/4/
3: using System.Runtime.Serialization.Formatters.Soap;
4: using System.Reflection;
5: using System.Collections;
9: [ValidLength(4,8,Message="UserID should be between 4 and 8 characters long")]
10: public string userID;
12: [ValidLength(4,8,Message="Password should be between 4 and 6 characters long")]
13: public string password;
19: public void Save(string fileName){
20: FileStream s=new FileStream(fileName,FileMode.Create);
21: SoapFormatter sf=new SoapFormatter();
22: sf.Serialize(s,this);
25: static void Main(string[] args){
28: u.password="Zxfd12Qs";
31: Validator v=new Validator();
33: foreach(string message in v.Messages)
34: Console.WriteLine(message);
36: else {u.Save("user.txt");}
1: [AttributeUsage(AttributeTargets.Property|AttributeTargets.Field)] 2: public class ValidLengthAttribute : Attribute{ 3: private int _min; 4: private int _max; 5: private string _message; 6: 7: public ValidLengthAttribute(int min,int max){ 8: _min=min; 9: _max=max; 10: } 11: 12: public string Message{ 13: get {return(_message);} 14: set {_message=value;} 15: } 16: 17: public string Min{ 18: get{return _min.ToString();} 19: } 20: 21: public string Max{ 22: get{return _max.ToString();} 23: } 24: 25: public bool IsValid(string theValue){ 26: int length=theValue.Length; 27: if(length >= _min && length <= _max) return true; 28: return false; 29: } 30: }
1: public class Validator{ 2: public ArrayList Messages=new ArrayList(); 3: 4: public bool IsValid(object anObject){ 5: bool isValid=true; 6: FieldInfo[] fields = anObject.GetType().GetFields(BindingFlags.Public|BindingFlags.Instance); 7: foreach (FieldInfo field in fields) 8: if(!isValidField(field,anObject)) isValid=false; 9: return isValid; 10: } 11: 12: private bool isValidField(FieldInfo aField,object anObject){ 13: object[] attributes=aField.GetCustomAttributes(typeof(ValidLengthAttribute),true); 14: if(attributes.GetLength(0) ==0) return true; 15: return isValidField(aField,anObject,(ValidLengthAttribute)attributes[0]); 16: } 17: 18: private bool isValidField(FieldInfo aField, object anObject,ValidLengthAttribute anAttr){ 19: string theValue=(string)aField.GetValue(anObject); 20: if (anAttr.IsValid(theValue)) return true; 21: addMessages(aField,anAttr); 22: return false; 23: } 24: 25: private void addMessages(FieldInfo aField,ValidLengthAttribute anAttr){ 26: if(anAttr.Message !=null){ 27: Messages.Add(anAttr.Message); 28: return; 29: } 30: Messages.Add("Invalid range for "+aField.Name+". Valid range is between "+anAttr.Min+" and "+anAttr.Max); 31: } 32: }
First, make sure the OpenHandCursor.cur file is marked as Resource (not EmbeddedResource) in the referenced assembly. Code Block // use resource in local assembly // new Uri("pack://application:,,,/folder/filename.cur") // use resource in referenced assembly // new Uri("yourAssemblyName;component/folder/filename.cur" // ,UriKind.Relative) Stream cursorStream = Application.GetResourceStream(new Uri ("CursorLib;component/cursors/help.cur", UriKind.Relative)).Stream; this.Cursor = new Cursor(cursorStream);
Windows 2003 Server SP1 Firewall Modification for Passive or PASV FTP Connections (Portions of this document are parphrased from or directly copied from Microsoft KB article 555022 by Bernard Cheah, MVP.) Passive Mode FTP connections are normally required by clients connecting through a NAT firewall or router. The client connects on port 21 and issues a PASV command, the server responds with a port in the 1024-65535 range for the data connection. After a data connection command is issued by the client, the server connects to the client using the port immediately above the client-side port of the control connection. The Windows 2003 SP1 Firewall will prevent PASV FTP from working properly unless exceptions for the ports are created. A metabase property key named PassivePortRange can be configured to specify the port range the server will respond with. This can be used to limit the security risk for the FTP server. The property key only exists in IIS 6.0. Support for IIS 5.0 on Windows 2000 can be added, but the system administrator will need to install Service Pack 4 and add the PassivePortRange key in the system registry. Two ports must be opened for each concurrent FTP connection. On Windows 2003 Server with IIS6 - To Enable Direct Metabase Edit
- Open the IIS Microsoft Management Console (MMC).
- Right-click on the Local Computer node.
- Select Properties.
- Make sure the Enable Direct Metabase Edit checkbox is checked.
- Configure PassivePortRange via ADSUTIL script
- Click Start, click Run, type cmd, and then click OK.
- Type cd Inetpub\AdminScripts and then press ENTER.
- Type the following command where the range is specified in "..". cscript.exe adsutil.vbs set /MSFTPSVC/PassivePortRange "5001-5201"
- Restart the FTP Publishing Service.
You'll see the following output, when you configure via ADSUTIL script: Microsoft (R) Windows Script Host Version 5.6 Copyright (C) Microsoft Corporation 1996-2001. All rights reserved. PassivePortRange : (STRING) "5001-5201" It's crazy to add 201 exceptions rules. Just disable the windows firewall temporarily. Add each port to the Windows Firewall Click Start, click Control Panel, open Windows Firewall, and select the Exceptions tab. Click the Add Port button. Enter a Name for the Exception and the first number in the port range. Click TCP if not already selected and click OK. Repeat for each port in the range - for large ranges see the end of the document. Enable the Windows Firewall on the General Tab.
IIS 6 doesn't handle extensionless URLs. You'll need to change your routes to use the .mvc extension. For example, routes.Add(new Route("Links.mvc/{categoryName}",... Make sure that IIS 6 maps .mvc to the aspnet_isapi.dll.
http://www.xfront.com/REST-Web-Services.html What is REST?REST is a term coined by Roy Fielding in his Ph.D. dissertation [1] to describe an architecture style of networked systems. REST is an acronym standing for Representational State Transfer. REST - An Architectural Style, Not a StandardREST is not a standard. You will not see the W3C putting out a REST specification. You will not see IBM or Microsoft or Sun selling a REST developer's toolkit. Why? Because REST is just an architectural style. You can't bottle up that style. You can only understand it, and design your Web services in that style. (Analogous to the client-server architectural style. There is no client-server standard.) While REST is not a standard, it does use standards: - HTTP
- URL
- XML/HTML/GIF/JPEG/etc (Resource Representations)
- text/xml, text/html, image/gif, image/jpeg, etc (MIME Types)
The Classic REST SystemThe Web is a REST system! Many of those Web services that you have been using these many years - book-ordering services, search services, online dictionary services, etc - are REST-based Web services. Alas, you have been using REST, building REST services and you didn't even know it. REST is concerned with the "big picture" of the Web. It does not deal with implementation details (e.g., using Java servlets or CGI to implement a Web service). So let's look at an example of creating a Web service from the REST "big picture" perspective. REST Web Services CharacteristicsHere are the characteristics of REST: - Client-Server: a pull-based interaction style: consuming components pull representations.
- Stateless: each request from client to server must contain all the information necessary to understand the request, and cannot take advantage of any stored context on the server.
- Cache: to improve network efficiency responses must be capable of being labeled as cacheable or non-cacheable.
- Uniform interface: all resources are accessed with a generic interface (e.g., HTTP GET, POST, PUT, DELETE).
- Named resources - the system is comprised of resources which are named using a URL.
- Interconnected resource representations - the representations of the resources are interconnected using URLs, thereby enabling a client to progress from one state to another.
- Layered components - intermediaries, such as proxy servers, cache servers, gateways, etc, can be inserted between clients and resources to support performance, security, etc.
Principles of REST Web Service Design1. The key to creating Web Services in a REST network (i.e., the Web) is to identify all of the conceptual entities that you wish to expose as services. Above we saw some examples of resources: parts list, detailed part data, purchase order. 2. Create a URL to each resource. The resources should be nouns, not verbs. For example, do not use this: http://www.parts-depot.com/parts/getPart?id=00345
Note the verb, getPart. Instead, use a noun:
http://www.parts-depot.com/parts/00345
3. Categorize your resources according to whether clients can just receive a representation of the resource, or whether clients can modify (add to) the resource. For the former, make those resources accessible using an HTTP GET. For the later, make those resources accessible using HTTP POST, PUT, and/or DELETE.
4. All resources accessible via HTTP GET should be side-effect free. That is, the resource should just return a representation of the resource. Invoking the resource should not result in modifying the resource.
5. No man/woman is an island. Likewise, no representation should be an island. In other words, put hyperlinks within resource representations to enable clients to drill down for more information, and/or to obtain related information.
6. Design to reveal data gradually. Don't reveal everything in a single response document. Provide hyperlinks to obtain more details.
7. Specify the format of response data using a schema (DTD, W3C Schema, RelaxNG, or Schematron). For those services that require a POST or PUT to it, also provide a schema to specify the format of the response.
8. Describe how your services are to be invoked using either a WSDL document, or simply an HTML document.
http://www.infoq.com/articles/rest-introduction
Key REST principlesMost introductions to REST start with the formal definition and background. I’ll defer this for a while and provide a simplified, pragmatic definition: REST is a set of principles that define how Web standards, such as HTTP and URIs, are supposed to be used (which often differs quite a bit from what many people actually do). The promise is that if you adhere to REST principles while designing your application, you will end up with a system that exploits the Web’s architecture to your benefit. In summary, the five key principles are:
- Give every “thing” an ID
- Link things together
- Use standard methods
- Resources with multiple representations
- Communicate statelessly
The WIN key is actually very versatile and goes to the heart of being able to whizz around your desktop without the mouse. For example, if you do WIN + R, you can get the Run box (try it). WIN + E opens Explorer (your hard drive), WIN + D minimises all your windows and takes you to the desktop, WIN+L locks your screen and WIN + TAB moves you from one open application to another. CTRL + P Print
Using Visual Studio 2008 with IIS 7.0 Author: Mike Volodarsky Published on March 05, 2008 by mvolo Updated on March 12, 2008 by mvolo Average Rating          Rate It (0) Thank you for your feedback! - Tags
- IIS 7.0 Visual Studio 2008 debugging publishing web site web application
Introduction Visual Studio® provides several options for working with IIS when developing web sites and applications. These include the Web application and Web site projects. In Visual Studio 2008, these features receive a much awaited upgrade to properly support IIS 7.0 in Windows Vista® and Windows Server® 2008. In addition, the recently released Web Deployment Project 2008 also provides support for IIS 7.0. This article provides an overview of using Visual Studio 2008 Web development features with IIS 7.0, including information on the steps necessary to enable these features to work correctly. Prerequisites To use Visual Studio 2008 to work with Web sites and applications on your local machine, do the following: 1. Install IIS 7.0 2. Install ASP.NET 3. Install IIS 6.0 Metabase Compatibility On Windows Vista, open the Control Panel, click Programs and Features, click the Turn Windows features on and off link, check the “Internet Information Services” check box, as well as the “Web Management Tools \ IIS 6 Management Compatibility \ IIS Metabase and IIS 6 configuration compatibility” and “World Wide Web Services \ Application Development Features \ ASP.NET” check boxes under it.
 On Windows Server 2008, use the Server Manager tool to install the Web Server (IIS) role, and add the “Management Tools \ IIS 6 Management Compatibility \ IIS 6 Metabase Compatibility” and “Application Development \ ASP.NET“ role services. For more information, see Installing IIS 7.0 on Windows Server 2008.
To use Visual Studio 2008 to work with Web sites and applications on a remote machine, see the "Using Visual Studio 2008 with a Remote IIS 7.0 Server" section later in this article. Starting Visual Studio 2008 as Administrator Certain tasks, including debugging and creating local IIS applications, require starting Visual Studio as a user with Administrative privileges. On Windows Vista, and Windows Server 2008 when not running as the built-in Administrator account, this requires right-clicking the Visual Studio 2008 icon in the Start Menu and choosing “Run As Administrator”. To make this process easier, you can create a shortcut and check the “Run this program as an administrator” check box in the Compatibility tab of the shortcut properties. Create a New IIS 7.0 Web Site or Application Project Visual Studio provides two conceptual models for working with Web applications: the Web site project model, and the Web application project model. While both options allow you to create Web applications and publish them to an IIS 7.0 server, they do have significant differences in how the corresponding ASP.NET application is built and deployed. Some of the differences between the two models are: - The Web application project option requires the source application files to be located on the local file system, or, on a network share. However, you can subsequently publish the Web application to a remote IIS 7.0 Web site by using a network share, FTP, or Front Page Server Extensions.
- The Web site project option allows you to connect directly to a local IIS 7.0 Web site, or to a remote IIS 7.0 Web site by using a network share, FTP, or Front Page Server Extensions. With the Web site project, you work directly with the content of your IIS 7.0 Web site and there is no project file.
You can find the detailed explanation of the two models and their differences in http://msdn2.microsoft.com/en-us/library/aa730880(VS.80).aspx. Note: Visual Studio 2008 provides the options to create a New project and Open an existing project. This does not necessarily mean that you must create a new IIS web application or open an existing application – you can use either of the options with an existing IIS web application. To create a new project using the Web application project option: - In Visual Studio, use the “File menu \ New \ Project ...” option and select the “ASP.NET Web Application” template.
Note: Unlike the Web site project option, you must place the application files on the local file system or a network share, and later use the Publish option to publish the contents of your application to an IIS 7.0 Web site. To publish the project to an IIS 7.0 Web site: 1. Create the IIS 7.0 Web site using IIS Manager, AppCmd, or another configuration tool. For more information, see http://technet2.microsoft.com/windowsserver2008/en/library/f6c26eb7-ad7e-4fe2-9239-9f5aa4ff44ce1033.mspx?mfr=true. Alternatively, use an existing IIS 7.0 Web site. 2. In Visual Studio, use the "Build \ Publish" option to publish the contents of your Web application to an IIS 7.0 Web site.
Note: The Publish Web dialog by default publishes only the parts of your project that comprise your web application - it does not publish the project file, obj directory, and other files. This is important because exposing these components to your web users may be a security risk. By clicking the "…" button, you can chose one of the four options for publishing your Web site: - File System. When using this option, Visual Studio opens / creates the web application as a folder, and uses the built-in ASP.NET Development Server to host the Web site. This option may be sufficient for basic testing of ASP.NET applications – however, this mode does not support running ASP.NET applications in Integrated mode, and it does not support application technologies other than ASP.NET (such as PHP, ASP, CGI, etc).
- Local IIS. When using this option, Visual Studio allows you to publish your application files to a local IIS 7.0 Web site or application. You can also use the dialog to create new IIS 7.0 applications or virtual directories to publish your files to.
- FTP Site. When using this option, Visual Studio supports editing your application files if they are shared through FTP. You can still use Visual Studio to debug your applications by configuring the URL of your application in project start settings. For more information, see Using Visual Studio 2008 with a Remote IIS 7.0 Server section later in this article.
- Remote Site. Using this option, Visual Studio can connect to a remote IIS server. To use this option, you need to have Front Page Server Extensions installed on the remote server and configure your Web site to use FPSE. For more information on this, see the "Using Visual Studio 2008 with a Remote IIS 7.0 Server" section later in this article.
You can also map the Web application project directory as a virtual directory on the local IIS 7.0 installation by opening the project Properties, clicking the “Web” tab, and using the “Create Virtual Directory” button. You can use the “Create Virtual Directory” option as a quick way to host your Web application locally on IIS without going through the “Publish Web” option. However, this option is not generally recommended because it places all of the project files, source files, object files, and other temporary files in the servable namespace of the IIS 7.0 virtual directory, which may result in a security risk. Using the Publish options which by default only publish the web servable portions of the project is a better practice. 3. Configure debugging. By default, projects created using the Web application project model use the built-in ASP.NET Development Server when testing or debugging your project. This provides a convenient way to test your ASP.NET application without IIS 7.0 – however, we recommend that you instead configure Visual Studio to test your application in the IIS 7.0 environment. The reasons for this are: - The ASP.NET Development Server does not support hosting ASP.NET applications in Integrated mode, which is the default mode of operation used by IIS 7.0. This may introduce differences in application behavior.
- The ASP.NET Development Server does not support many of the IIS configuration features, so if your application relies or uses them, it’s behavior may be different or incorrect when hosted under the ASP.NET Development Server.
- The ASP.NET Development Server does not support hosting portions of your application that utilize application technologies other than ASP.NET, such as PHP, CGI, and other third party frameworks.
If you are developing on Windows Vista, you can easily take advantage of IIS 7.0 to test your application locally using the same environment it will be on when it is deployed - use the "Create Virtual Directory" option or the Publish Web dialog as discussed earlier in this article. Alternatively, you can configure Visual Studio to connect to the a remote IIS 7.0 server to which you publish your application. In those cases, you can configure Visual Studio to debug your application in the IIS 7.0 environment. To do this, right-click on the project node, chose "Properties …", and click the "Web" tab. In the "Web" tab, select the "Use IIS Web server" radio button and type in the base URL of your Web application on the remote server.
For more information on configuring remote debugging, see "Debugging IIS 7.0 Web Applications" later in this article. To create a new project using the Web site project option: 1. Create the IIS 7.0 Web site using IIS Manager, AppCmd, or another configuration tool. For more information, see http://technet2.microsoft.com/windowsserver2008/en/library/f6c26eb7-ad7e-4fe2-9239-9f5aa4ff44ce1033.mspx?mfr=true. Alternatively, use an existing IIS 7.0 Web site. 2. In Visual Studio, use the “File menu \ New \ Web Site …” option to create a new Web site project using the IIS 7.0 Web site you created. In the “New Web Site” dialog, select one of the Visual Studio Web site templates, such as the ASP.NET Web Site. Next, indicate where this web site should be located. To do this, click the “Browse …” button, which displays a dialog similar to what you get when publishing a Web application project. Here, click the “Local IIS” button again to select an existing Web site or application on the local machine, or create a new Web application or virtual directory to host your project files. Alternatively, you will have the option to place your new Web site project on the local File System for use with the ASP.NET Development Server, upload it to a remote server using FTP, or upload it to a remote IIS server using Front Page Extensions. For more information on connecting to a remote server, see the "Using Visual Studio 2008 with a Remote IIS 7.0 Server" section later in this article. To Open an Existing IIS 7.0 Web Site or Application To create a project based on an existing IIS 7.0 Web site: 1. Open the existing IIS 7.0 Web site using the “File menu \ Open \ Web Site …” option. Click “Local IIS” to connect to the local IIS 7.0 server. In the resulting dialog, you can select the Web site or a child application to open. Alternatively, you can use the “Create New Web Application”, “Create New Virtual Directory”, and “Delete” buttons in the top right hand corner to manage the web site hierarchy. Note: Be sure to back up your configuration first before making changes.
If you do not have IIS 7.0 or any of the prerequisites installed, Visual Studio 2008 displays a message when you attempt to connect to the Local IIS server telling you to install the required components. To do this, see the "Prerequisites" section earlier in this article.
Note: Visual Studio provides several different options for working with existing Web sites, in addition to connecting to an existing IIS 7.0 Web site. These options include: - File System. When using this option, Visual Studio opens / creates the web application as a folder, and uses the built-in ASP.NET Development Server to host the Web site. You can use this option to connect to an existing IIS 7.0 web site by opening its virtual directory’s root folder on the local file system or through a network share.
- FTP Site. When using this option, Visual Studio supports editing your application files if they are shared through FTP. For more information, see the "Using Visual Studio 2008 with a Remote IIS 7.0 Server" section later in this article.
- Remote Site. Using this option, Visual Studio can connect to a remote IIS server. To use this option, you need to have Front Page Server Extensions installed on the remote server and configure your Web site to use FPSE. For more information on this, see the "Using Visual Studio 2008 with a Remote IIS 7.0 Server" section later in this article.
2. Configure debugging. If you have opened an existing IIS 7.0 Web site using the Local IIS or Remote Site options, your project is automatically configured to use the IIS 7.0 Web site when debugging so no further action is necessary (the Remote Site option requires additional configuration to enable remote debugging, as explained later in the article). If you have opened your Web site project using the File System or FTP site options, it is by default configured to use the ASP.NET Development Server for testing and debugging. It is recommended that you configure Visual Studio to use the IIS 7.0 server on which the Web site is located for debugging. To do this, right-click on the Web site project node, chose "Start Options ...". In the dialog, select "Use custom server" radio button and type in the base URL of your Web application on the remote server.
Using Visual Studio 2008 with a Remote IIS 7.0 Server In order to open an existing Web site or create a new Web site on a remote IIS server, you can use many of the options mentioned earlier: -
File System. You can create a file share pointing to the root virtual directory of your Web application, and use the "File System" option to connect to it. To use this option, select the "File System" button in the “Open Web Site” dialog. You then have to configure the URL of your application in project start settings to be able to debug the application using Visual Studio. You cannot create new IIS Web sites, applications, or virtual directories on the remote machine using this option. -
FTP Site. If your Web site or application files are shared using FTP, you can access these files using this option. You then have to configure the URL of your application in project start settings to be able to debug the application using Visual Studio. To use this option, select the "FTP Site" button in the "Open Web Site" dialog. You cannot create new IIS Web sites, applications, or virtual directories on the remote machine using this option. -
Remote Site. This option uses Front Page Server Extensions to connect to a remote IIS server. To use this option to connect to a remote IIS 7.0 server on Windows Server 2008 or Windows Vista computers, you first need to install Front Page Server Extensions on the remote computer. Connect to an IIS 7.0 Web site using FTP You can use the FTP Site option if you have used FTP to share the IIS 7.0 virtual directory you want to publish to. Note: When using FTP, you cannot create or edit IIS 7.0 Web sites, applications, or virtual directories, but you can publish and edit files. To use this option, provide the address of the FTP server, the port, the directory to which you are connecting, and logon credentials if not using anonymous access.
For more information on using the FTP server included in Windows Vista and Windows Server 2008, see FTP Site Setup (IIS 6.0). To use the new FTP 7.0, which is available as a download from IIS.NET, see Adding FTP to a Web Site. Connect to an IIS 7.0 Web Site Using Front Page Server Extensions You can use the Remote Site option if you have shared the IIS 7.0 Web site you want to publish to using Front Page Server Extensions. Unlike the FTP Site option, you can create and edit IIS 7.0 applications and virtual directories when using this option. Front Page Server Extensions for IIS 7.0 are available as a free download for Windows Vista and Windows Server 2008. For more information on installing and enabling Front Page Server Extensions for IIS 7.0 Web sites, see Installing Front Page Server Extensions for IIS 7.0. To quickly enable a remote Web site to be used with the “Remote Site” option in Visual Studio, do the following: 1. Download and install FPSE on the remote IIS 7.0 server. The provided installer automatically installs all required IIS 7.0 components. 2. Create an IIS 7.0 web site to connect to (optional, if the site does not already exist). 3. Enable either Basic Authentication or Windows Authentication methods for the Web site. This is required for FPSE to be able to manage the site. Note: If you use Basic authentication, the username and password are transmitted in clear text so you should not use it for connecting to web sites over public networks unless you also use SSL to protect the communication. 4. Enable the web site to be managed with FPSE. You can do this by executing the following from the command line: > "%CommonProgramFiles%\Microsoft Shared\Web Server Extensions\50\bin\owsadm.exe" -o install -p LM/W3SVC/<SITEID> -u <USERNAME> Where <SITEID> is the site id of the Web site you want to enable for FPSE, and the <USERNAME> is the Windows account that can act as FPSE administrator. 5. Connect to the site Using the “Remote Site” option in the Open Web Site dialog or the New Site dialog. This allows you to connect to an existing Front Page Server Extensions – enabled web site, or create new Web applications and virtual directories.
If you receive the following error dialog during connection, double-check that you have installed FPSE on the remote server, and have enabled FPSE management for the Web site you are attempting to connect to.
If you are using Windows authentication for your FPSE-enabled Web site, Visual Studio attempts to authenticate using the account under which it was started. If this authentication fails, it prompts you to provide credentials for authentication with the remote server. If you are using Basic authentication, Visual Studio immediately prompts you for credentials. Note: Basic authentication sends credentials in clear text, so it can lead to unintended disclosure of your username and password if the site is not protected with SSL. For this reason, we recommend using Windows authentication for intranet environments, and using Basic authentication over SSL for internet environments. If you have not enabled a suitable authentication method (Windows Authentication, Basic Authentication, or Digest Authentication), you receive the following error dialog when connecting. Turn on one of the above authentication methods to fix this problem.
Note: The "New Web Site …" button in the "Remote Site" dialog cannot be used to create a new IIS 7.0 Web site. Instead, it is used to create a new Web application with the specified path for an existing Front Page Server Extensions – enabled IIS 7.0 Web site. Debugging IIS 7.0 Web Applications After you have opened a Web site or application in Visual Studio, you can take advantage of Visual Studio debugging features to test it. In doing so, you have the following options: - Use F5 debugging to debug from Visual Studio. If you have opened an IIS 7.0 Web site project using one of the options discussed earlier, this gives you the most convenient way to debug your web application. You can debug it simply by pressing F5, and then interacting with your application using a browser window. In the rest of this article, we will focus on this option.
- Attach to the IIS worker process directly. If you know which IIS worker process is hosting your application, you can use this option to attach directly to that process.
Use F5 to Debug a Local IIS 7.0 Web Application from Visual Studio F5 debugging provides the most convenient way to debug your Web application with Visual Studio. To use it, do the following: 1. Open an IIS 7.0 Web site using one of the options discussed earlier. 2. Select the project file to which you want to make the initial request (optional). 3. Set the desired breakpoints in your application source code (optional, you can also set them during debugging). 4. Press F5 to begin debugging. Visual Studio will make an initial request to the IIS 7.0 web application, attach to the hosting IIS worker process, and open a new browser window where you can interact with your application. In order to successfully debug a local IIS 7.0 Web application, you must meet the following requirements: 1. Be logged on as a user that has Administrative privileges on the local computer (Either the built-in Administrator account, or an account that is a member of the built-in Administrators group). 2. Start Visual Studio in Administrator mode by right-clicking the Visual Studio 2008 icon in the Start menu, and selecting “Run As Administrator”. If you do not do this, Visual Studio receives a filtered UAC token and cannot debug. If you have opened an ASP.NET application using the “File System” option, Visual Studio by default starts the ASP.NET Development Server to host your application. In this option, IIS 7.0 is not involved, and you are not required to be an Administrator to debug your application. However, when using the ASP.NET Development Server, you do not have the full range of features and services that IIS 7.0 environment provides, which may make your application behave differently from when it is deployed on IIS 7.0. This includes the following: - No support for ASP.NET Integrated Mode.
- No support for IIS 7.0 features such as compression, native URL authentication, request filtering, and others.
- No support for application technologies other than ASP.NET, such as PHP, ASP, CGI, and others.
Use F5 to Debug a Remote IIS 7.0 Web Application from Visual Studio You can use F5 to debug an IIS 7.0 Web application running on a remote server. The process is similar to what was described earlier for debugging local IIS 7.0 applications, but requires additional configuration to enable remote debugging to take place. In addition, you must open the remote IIS 7.0 Web site or application project using the File System, FTP Site or Remote Site options as discussed in the "Using Visual Studio 2008 with a Remote IIS 7.0 Server" section earlier in this article. In order to successfully debug a remote application, you must also meet the following requirements: 1. Install the Remote Debugging components on the server machine. For more information, see How to: Set Up Remote Debugging. 2. Run the Remote Debugging monitor (msvsmon.exe) on the server machine. See notes further about how to do this properly. 3. Open the required firewall ports for remote debugging. When you run msvsmon.exe for the first time on the remote machine, it warns you if the ports are not open, and offers to open them automatically. If you want to configure the firewall manually or to see which ports are opened, see How to: Manually Configure the Windows Vista Firewall for Remote Debugging. 4. If you are using a Web application project and publishing to a remote IIS 7.0 server, or if you have opened the remote Web site project using the "File System" or "FTP Site" options, you must configure Visual Studio project start options to enable debugging. To do this for a Web site project, right-click on the Web site project node, chose "Start Options …". In the dialog, select "Use custom server" radio button and type in the base URL of your Web application on the remote server. For a Web application project, right-click on the project node, chose "Properties …", and click the "Web" tab. In the "Web" tab, select the "Use IIS Web server" radio button and type in the base URL of your Web application on the remote server. This process is described in detail earlier in the article. 5. Configure permissions to allow debugging to take place. See notes further about how to do this properly. How you run the Remote Debugging monitor (msvsmon.exe) and configure your permissions depends on whether your are operating in a domain or workgroup environment. To set up remote debugging in a workgroup environment 1. Create an account with the same username and password on both the Visual Studio 2008 client computer and the remote server computer. This account must have Administrative rights on the remote server computer. Note: If you are using Windows Authentication in your application, this account must be the built-in Administrator account. This means that the built-in Administrator account must have the same password on both computers. 2. Log on to the remote server computer using the account created in Step 1, and run the Visual Studio 2008 Remote Debugger from the Start menu by right-clicking it, and choosing "Run As Administrator". This is important – otherwise the Remote Debugging monitor receives a UAC-filtered token and cannot debug IIS worker processes. Note: Do not use the RunAs.exe command to run the msvsmon.exe process, as this always results in a UAC-filtered token and prevents debugging from working. You also have an option to run the Remote Debugging monitor as a service by opening the Visual Studio 2008 Remote Debugger Configuration Wizard from the Start menu. If using this option, you must configure the Remote Debugging monitor to log on using the account created in Step 1. You then also must grant the corresponding account the "Log On As A Service" right in the computer’s Local Security Policy console. 3. Log on to the Visual Studio 2008 client computer with the account created in step #1. Run Visual Studio 2008 by right-clicking its icon in the Start menu, and choosing "Run As Administrator". Note: It is very important to both log in using the account created in Step 1, and use the "Run As Administrator" option when running Visual Studio. As mentioned in Step 1, the account you are using MUST be an Administrative user on the remote server machine. 4. Open the remote IIS 7.0 Web site (using the File System, FTP Site or the Remote Site option). If you are using Windows Authentication in your IIS 7.0 Web site, you must be running Visual Studio 2008 using the built-in Administrator account and therefore also running the Remote Debugging monitor on the remote computer using the built-in Administrator account. The password for the Administrator account must be the same on the client and remote server computers. In addition, you can do the following: -
Use the FTP Site option to connect to the remote IIS 7.0 Web site, and use Anonymous authentication. Then, you do not need to use the built-in Administrator account, as long as the account you are using is an Administrative user on the remote server computer. -
Use the Remote Site option to connect to the remote IIS 7.0 Web site, and use Basic or Digest authentication. Then, you do not need to use the built-in Administrator account, as long as the account you are using is an Administrative user on the remote server computer. If you need to use Windows Authentication in your IIS 7.0 Web site, and you cannot use synchronized Administrator accounts, you must turn off UAC on the remote server computer and reboot prior to attempting to debug. This is not recommended for production servers as it may negatively affect the security of your server. To set up remote debugging in a domain environment Debugging in a domain environment is simpler to configure. To debug in a domain environment, you must: 1. Make the domain account you will be using to run Visual Studio 2008 a member of the Administrators group on the remote server computer. 2. Log on to the remote server computer using the domain account, and run the Remote Debugging monitor (msvsmon.exe) using the "Run As Administrator" option. You also have an option to run the Remote Debugging monitor as a service by right clicking the Visual Studio 2008 Remote Debugger Configuration Wizard from the Start menu, and choosing "Run As Administrator". You can let the Remote Debugging monitor service run as LocalSystem. 3. Log on to the Visual Studio 2008 client computer with the domain account. Run Visual Studio 2008 by right-clicking its icon in the Start menu, and choosing "Run As Administrator". 4. Open the remote IIS 7.0 Web site using the FTP Site or the Remote Site option.
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
30+ Online Resources to Expand your English Vocabulary If you’ve got the desire to master the English language, the web is one of the best resources that’s available to you. Knowing the right sites and devoting some time, you can easily take the way you read, speak, and write English to the next level. Even if you’re a native speaker, it doesn’t hurt to improve your grammar every now and then. New words are being invented all the time courtesy of the Web, a prime example being “to google” for something. " src="http://www.makeuseof.com/wp-includes/images/smilies/icon_wink.gif"> Here, I have listed the resources I have used in the past, and those I’m currently using, for your own benefit. Online Dictionaries and Thesaurus
Reference.com - Comes with a dictionary and thesaurus, and is one of my favourite destinations to know the meaning and origin of a particular word. You can use it for free, although there’s a premium version of the site that you can pay for if you need pronounciation help. The Free Dictionary - Get ready to learn a lot of things at the Free Dictionary site. It’s an awesome resource that has information categorized, helps you with definitions, spelling bee games and lots more. The site also features a start page where you can add your favourite modules and learn things new every day. Visual Thesaurus - At Visual Thesaurus, you can have a great time exploring words and related terms and play around with them. Includes a pronunciation helper so you need not worry about getting a word wrongly pronounced. Some other features include examples of usages and additional tips to help you from mistakenly using the wrong word. Available as a download, it’s worth paying for. Google’s Define Operator - Since people have got used to Googling for everything that you can imagine, it’s not a surprise that they’ve included a little functionality to their search engine. If you want to know the meaning of a word, just type define: followed by the word in the Google search box, and get the definitions instantly on your screen. Example: define: intuitive. Definr - Definr calls itself an incredibly fast dictionary, and it really lives up to its name. Type in a word, and get the meaning instantly. Advantages - it loads really fast so you rarely have to wait. But it seems to have a smaller database of words when compared to the tools mentioned above. HowJSay.com - This is a brilliant web 2.0 tool, just type in a word and get it pronounced immediately. It might prove very useful in some situations. This site has a large database of words so you won’t be disappointed. Offline Dictionaries
WordWeb - WordWeb functions as a dictionary tool that comes packed with the features that you expect in a dictionary. Select a word from any application and then press a shortcut to find out its meaning in WordWeb. Something you’ll love is the way its interface has been designed. In case you need synonyms, related terms, etc, just click on the appropriate tab and you’re done. The Pro version includes a few more capabilites, although the free version might be more than enough for your needs. Merriam Webster - Puts the reputed Merriam Webster Dictionary tool on your PC. Get instant meanings, just a right-click away. Spell Checker included. Enso Dictionary and Spell Checker - Instantly check the spelling in your text by holding down a hotkey (works universally in Windows). Also included is a dictionary that can be activated using the command ‘define’ Grammar Resources The BBC Learning English site has loads of information on English grammar, such as FAQs, exercises and quizzes. If you still need more, you can test yourself with the aid of exercises in these sites: About.com Grammar Quiz, Interactive Grammar Quizzes, Grammar Self Tests, 40+ Resources to improve your Grammar and Punctuation Dedicated Portals
BBC Learning English - There’s just so many things here that you can retain for learning - quizzes, crosswords, podcasts, radio and many other useful resources all under one internationally-recognized brand. It’s a site that must be bookmarked. Wordie.Org - This is a social network centred around words. You can list your favourite words and phrases, see who else has your favourite word in their list, browse around their lists, tag them and have lots of fun. Create words you hate, words you find weird, words that make you laugh etc. Within a few minutes of wandering on the site, you’ll find lots of new terms that could improve your vocabulary skills. A Word A Day The following sites are updated every day with words that you might have never heard of. You can see their origin, etymology, pronunciation and a lot more. You could subscribe to their newsletters and spending less than a minute every day you can enrich your English vocabulary greatly. Wordsmith’s A Word A Day - One of the world’s most subscribed-to newsletters. Other “Word of the Day” sites: Yahoo! Education, Merriam Webster, Oxford’s Word Of the Day. Podcasts Podcasts are MP3 files that you can download and play on your computer or your portable media player such as your iPod. I listen to the Grammar’s Girl Podcast quite often. Maybe you want to tune in as well. eBooks
Project Gutenberg - 20,000+ downloadable books. An awesome project that has rich classic books included. Download and distribute, share the knowledge. You have content here that’ll take you a lot of time to read and quench your thirst for literature. Books from many languages are available, just take your pick from the online Gutenberg catalogue. There’s quite a lot of Shakespeare stuff as well, Google is your friend. Foxit Reader - Ok, you download a lot of eBooks in the PDF format, but do you find that your Adobe Reader software slows down your entire computer? Get this alternative instead. It’s called Foxit Educational Games
Jumble - A game I love to play when I see it in the newspapers every morning. It’s playable online and downloadable. BingoBinge - Play Scrabble Online ManyThings, Hangman Flash Game - Play Hangman Online Blogs
There are of course a few blogs that provide tips on improving your English. You can check these that I found: Daily Writing Tips, The Grammar Vandal, Triangle Grammar Guide. Start Pages These are quite great, and can save you loads of time. A Start Page is a page on the web that you can customize with stuff that you need to keep an eye on. For example, my start page contains modules that give me access to a few blogs, top news stories and weather:
Likewise, you too can create a start page with modules like a dictionary, word a day stuff, etc. Try Netvibes or iGoogle. Trust me, if you know how to use them, you’ll find them very helpful and fun to learn with. Let me know in the comments if you found the post useful. (By) Shankar Ganesh, a 16 year old guy from India who blogs about computers and soft at Killer Tech Tips. Digg It Del.icio.us
LATEST : 14 “OTHER” Ways to Use RSS Feeds
<ItemTemplate>
<tr class='<%# (Container.DataItemIndex % 2 == 0)?"even":"odd" %>'> <td> <asp:LinkButton ID="EditButton" CommandName="Edit" runat="server" Text="Edit"></asp:LinkButton>
<asp:LinkButton ID="DeleteButton" OnClientClick="return confirm('Delete Record?');" CommandName="Delete" CommandArgument='<%# Eval("CustomerID")%>' runat="server" Text="Delete"></asp:LinkButton>
</td>
<td>
<%# Eval("CustomerID") %>
</td>
<td>
<%# Eval("CompanyName") %>
</td>
<td>
<%# Eval("ContactName") %>
</td>
<td>
<%# Eval("ContactTitle") %>
</td>
<td>
<%# Eval("Address") %>
</td>
<td>
<%# Eval("City") %>
</td>
<td>
<%# Eval("Country") %>
</td>
<td>
<asp:LinkButton ID="lbOrders" runat="server" Text="Orders" CommandName="ViewOrders" CommandArgument='<%# Eval("CustomerID") %>' />
</td>
</tr>
<tr id="trOrders" runat="server" visible="false">
<td> </td>
<td colspan="8">
<asp:GridView id="gvOrders" runat="server" AutoGenerateColumns="False"
BackColor="White" BorderColor="#999999" BorderStyle="Solid" BorderWidth="1px" CellPadding="3" ForeColor="Black"
GridLines="Vertical" Width="500px" EnableViewState="false">
<FooterStyle BackColor="#CCCCCC" />
<Columns>
<asp:BoundField DataField="OrderID" HeaderText="OrderID"
SortExpression="OrderID" />
<asp:BoundField DataField="OrderDate" HeaderText="OrderDate"
SortExpression="OrderDate" HtmlEncode="false" DataFormatString="{0:d}" />
<asp:BoundField DataField="RequiredDate" HeaderText="RequiredDate"
SortExpression="RequiredDate" HtmlEncode="false" DataFormatString="{0:d}" />
<asp:BoundField DataField="ShippedDate" HeaderText="ShippedDate"
SortExpression="ShippedDate" HtmlEncode="false" DataFormatString="{0:d}" />
</Columns>
<AlternatingRowStyle BackColor="#eaeaea" />
</asp:GridView>
</td>
</tr>
</ItemTemplate>
Update: David Findley posted something that I hadn't thought of using that's even easier. Adding this to web.config will dump email messages sent from an ASP.NET application to the specified path: <system.net>
<mailSettings>
<!--
Production setting
<smtp deliveryMethod="Network">
<network host="localhost" port="25" />
</smtp>
-->
<smtp deliveryMethod="SpecifiedPickupDirectory">
<specifiedPickupDirectory pickupDirectoryLocation="C:\TestMessages" />
</smtp>
</mailSettings>
</system.net>
Top 10 Best Practices for Production ASP.NET Applications12 Feb, 2008. In no particular order, here are the top ten things I've learned to pay attention to when dealing with production ASP.NET applications. Hopefully they will help you save you some time and headaches. As always, your thoughts and additions are welcome. 1. Generate new encryption keys When moving an application to production for the first time it is a good idea to generate new encryption keys. This includes the machine validation key and decryption key as well as any other custom keys your application may be using. There is an article on CodeProject that talks about generating machineKeys specifically that should be helpful with this. 2. Encrypt sensitive sections of your web.config This includes both the connection string and machine key sections. See Scott Guthrie's post for some good references. Note that if your application runs in a clustered environment you will need to share a custom key using the RSA provider as described in an MSDN article. 3. Use trusted SQL connections Both Barry Dorrans and Alex Chang have articles which discuss this in detail. 4. Set retail="true" in your machine.config <configuration> <system.web> <deployment retail="true"/> </system.web> </configuration> This will kill three birds with one stone. It will force the 'debug' flag in the web.config to be false, it will disable page output tracing, and it will force the custom error page to be shown to remote users rather than the actual exception or error message. For more information you can read Scott Guthrie's post or the MSDN reference. 5. Create a new application pool for your site When setting up your new site for the first time do not share an existing application pool. Create a new application pool which will be used by only by the new web application. 6. Set the memory limit for your application pool When creating the application pool, specifically set the memory limit rather than the time limit which is set by default. Asp.net has a good whitepaper which explains the value of this: By default IIS 6.0 does not set a limit on the amount of memory that IIS is allowed to use. ASP.NET’s Cache feature relies on a limitation of memory so the Cache can proactively remove unused items from memory. It is recommended that you configure the memory recycling feature of IIS 6.0. 7. Create and appropriately use an app_Offline.htm file There are many benefits to using this file. It provides an easy way to take your application offline in a somewhat user friendly way (you can at least have a pretty explanation) while fixing critical issues or pushing a major update. It also forces an application restart in case you forget to do this for a deployment. Once again, ScottGu is the best source for more information on this. 8. Develop a repeatable deployment process and automate it It is way too easy to make mistakes when deploying any type of software. This is especially the case with software that uses configuration files that may be different between the development, staging, or production environments. I would argue that the process you come up with is not nearly as important as it being easily repeatable and automated. You can fine tune the process as needed, but you don't want a simple typo to bring a site down. 9. Build and reference release versions of all assemblies In addition to making sure ASP.NET is not configured in debug mode, also make sure that your assemblies are not debug assemblies. There are of course exceptions if you are trying to solve a unique issue in your production environment ... but in most cases you should always deploy with release builds for all assemblies. 10. Load test This goes without saying. Inevitably, good load testing will uncover threading and memory issues not otherwise considered.
http://developer.apple.com/iphone/devcenter/designingcontent.html http://www.practicalecommerce.com/blogs/developers-diary/archives/104 I'm getting ready to setup an HTC Excalibur and I wanted to post my list of favorite sites to visit with my Mobile Browser and a list of the apps I really need to install to make my Windows Mobile Smartphone complete. - Amazon Mobile - http://m.amazon.com - A basic, but very usable site, focused on search, that lets folks who've setup their Amazon account ahead of time purchase directly from the phone. Nice if you have Amazon Prime Free Shipping.
- BBC PDA - http://www.bbc.co.uk/mobile/pda or http://www.bbc.co.uk/mobile - BBC has a mobile site and a PDA site, but the PDA site looks best on Smartphones or Blackberries. The best of the BBC on my phone. The mobile site would look good on an old black-and-white WAP Nokia.
- CNN Mobile - http://m.cnn.com - Same here, mobile CNN, some pics, I use this site a lot.
- Engadget Mobile - http://m.engadget.com - My favorite tech and gadget blog, now with mobiley goodness. I wish I could see comments though.
- Hanselman.com - http://www.hanselman.com - Ha! See what I did right there? Back in the day, we taught dasBlog about mobile devices and if you hit hanselman.com from a Blackberry or Windows Mobile browser (and a number of other tiny browsers), we'll detect it and give you a mobile experience. Yay!
- Facebook - http://m.facebook.com - In terms of pure functionality, I'd say that Facebook's mobile site is, hands-down, the most functional. It feels like you can most everything you'd ever want to using only Tiny HTML. This site and this company continue to impress, probably because it's running entirely on Red Bull and 20-year-olds.
- Flight Stats - http://mobile.flightstats.com - This fine site has saved my tuckus a number of times while traveling. Their Airport Chatter section is interesting also.
- Google - http://www.google.com/xhtml - The Tiny XHTML version of Google includes location specific searches and personalization with News, Weather, Movies, etc.
- +1-800-GOOG-411 (+1-800-4664-411) - If you're able to call this number, either domestically or internationally, it's worth a try because it's amazing. Much better than the "1-800-Tell-Me stuff back in the day, but still of the same vein. I use this a LOT.
- Microsoft Live - http://wls.live.com or http://m.live.com - If you hit wls you'll get your browser detected and possible prompted to download a nice applet for your phone. If you hit m.live.com you'll get tiny Windows Live Search.
- Gmail - http://m.gmail.com - If you hit gmail with your phone you should get detected and sent over to the mobile version. If not, you can hit m.gmail.com or https://mail.google.com/mail/x/ where the x is magic. If you're running Google Apps for Your Domain (GAFYD) you can hack that URL also.
- Joystiq - http://m.joystiq.com - Tiny Gaming Site. Interestingly, while they use (I think) the same back end as Engadget, sometimes the fonts are all wonky.
- Mobile MSN - http://m.msn.com - A decent mobile portal and good jumping off point. The mobile stocks are particularly good.
- MSNBC - http://www.msnbc.msn.com - It's astonishingly LAME that you can't get to this site from http://m.msnbc.com but perhaps they'll read this and make that DNS change, because this is a really good tiny news site.
- Alarm.com - https://www.alarm.com/pda - I use Alarm.com to manage my security systems at the house and our rentals from my phone. If you've got a service available over the web, you really ought to have a minimal mobile website so kudos to them for having one.
- Twitter - http://m.twitter.com - Does exactly what it says it does...mobile twitter, although I'd like to be able to see Direct Replies in the interface.
- Wapedia (Mobile Wikipedia) - http://wapedia.mobi/en - Very useful for
winning arguments with the wife self-edification, it's the mobile Wikipedia. I think it's funny that folks thought that the ".mobi" top level domain extension was a good idea and that the internet just changed "www.foo.com" to "m.foo.com" and saved the registration fee. Plus, I don't have to tap out the "obi" which saves me, like minutes. What are your must-have mobile websites, Dear Reader?
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.
Things to think about if you want to be a consultant http://devlicio.us/blogs/derik_whittaker/archive/2008/01/02/things-to-think-about-if-you-want-to-be-a-consultant.aspx I was chatting a buddy recently and he was thinking about making the jump to the consulting world (not solo, through a consulting firm). As he has never been a consultant I gave him my 2cents on questions to ask during the interview as well as things he has to accept before making the jump. Questions to ask the consulting firm - What percent of travel is the norm?
This is very important to know up front. Because if you don't want to travel much and they tell you they are 100% travel, then move on. One thing you need to keep in mind, is that they can give you a number, that number is NOT in stone. It can/will change from client to client. In my 5 years of consulting, I never left the greater Chicago area. And for 2+ years I worked out of our home office. - What is your bench policy?
Ask what the policy is for being on the bench? More importantly ask the billable % expectation is for a consultant. This can be important because if they expect you to be billable 90% of the year then they may not be able to handle any rough patches. However, if they expect you to be billable for only 80% then they should be better set for rough patches. I also found that if a company has higher expectations about billable %, they may not be willing to provide non-billable training as it eats into the bottom line. If you are on the bench, do they have something for you to do? Can you go to training during that time? Or can you simply stay home and collect a check (i wish)? - What is your training policy?
Ask what type of training they budget for? Do they pay for conferences, weekly training classes? Do they EXPECT you to take some sort of training. A good firm will have a defined budged that will allow for adequate training of all there consultants. Actually, it is in their best interest to keep you trained as you become more marketable. - What is the 'standard' number of billable hours you expect?
What is the standard number of hours do they expect you to bill for in a giving year? Is it 1800, is it 2000? This makes a difference because if they tell you 2000+ then are telling you they EXPECT you to work over time (more on that below). A full year with no time off is 2080 hours (52 weeks * 40 hours). But if you get 2 weeks vacation and 10 paid holidays you are only at 1920 (48 weeks * 40 hours). Again, now keep in mind that the 'standard' number is just a rule of thumb, but it is good to know. The higher the number, the less room in the budget they may have for when times get tough. Also, keep in mind that during my 5 years consulting, my average work week was about 45-50 hours. So if you are looking for the 40 hours and go home, you may not want to do consulting. - How are bonuses/raises calculated?
Do they give bonuses/raises? Are they based on billable hours? If they are based on billable hours, that can be good and bad. Example. My old firm would give a flat bonus, but if you worked 200 extra hours a year you got a bump, if you worked 300 you got an extra bump, etc. This is good because i knew that the more i billed, the larger my bonus. This was bad because i only got a sliver of the extra billable hours and in the long run did not pay off in the end. - How does overtime work?
Some firms don't do anything special for overtime (as is the case in most salary positions). However, some will actually pay you extra for your overtime (these places typically don't give bonuses). Other places bank your overtime and build that into your vacation (worked out well for my buddy). But i would say that most common is that nothing happens with your overtime, except the companies profits increase at your expense. Thing you have to accept as part of the job - The tech/environment will change with every new client
With every new client/project your environment along with the technology will change. For some people this is a show stopper, for others it is just another chance to learn. Keep in mind that if you work on site at the client you will be expected to follow ALL their rules. So if they are business formal, you will be expected to dress in business formal. If they say you cannot come in till 9 and must stay till 6, then that is what you must do. If you are not willing to accept this, then consulting may not be for you. - You may not always be working on 'cool/fun' tech
Since each project may change technology you may not always be working on 'fun, cool' stuff. You may go from doing cutting edge development on project to doing report writing on the next one. If you are not willing to accept this, then consulting may not be for you. - You are the '***' of the client, at their mercy
Since you are a 'hired gun' you are the mercy of the client. Don't expect to have the same treatment as full timers (a lot of places today treat their consultants as part of the family, but not all). Don't expect to get subsidized meals (if offered) or gym memberships, etc. Also, be ready to work in some of the worst spaces you can think of. On place i worked the consultants all sat in a single 15-20 office. They basically lined up desks along the wall and filled it with 6 people. I felt bad for them :). - The people you will meet
The coolest part is the people you will meet, the connections you will make. This is great because networking is the best way to move ahead in this business. I have meet some great people and have made some great contacts. This was my 2cents to him. Did I miss anything? Am I wrong? Let me know Till next time,
http://msdn2.microsoft.com/en-us/library/dct97kc3.aspx Both master pages and content pages can contain event handlers for controls. For controls, events are handled locally—a control in a content page raises an event in the content page, and a control in the master page raises an event in the master page. Controls events are not sent from the content page to the master page. Similarly, you cannot handle an event from a master page control in a content page. In some cases, the same event is raised in both the content and the master page. For example, both pages raise Init and Load events. The general rule for how events are raised is that the initialization events are raised from the innermost control to the outermost one, and all other events are raised from the outermost control to the innermost one. It is helpful to remember that the master page is merged into the content page and treated as a control in the content page. The following is the sequence in which events occur when a master page is merged with a content page: -
Master page controls Init event. -
Content controls Init event. -
Master page Init event. -
Content page Init event. -
Content page Load event. -
Master page Load event. -
Content controls Load event. -
Content page PreRender event. -
Master page PreRender event. -
Master page controls PreRender event. -
Content controls PreRender event. The sequence of events in master and content pages rarely is important for you as page developer. However, if you are creating event handlers that depend on the availability of certain controls, you will find it helpful to understand the event sequence in master and content pages.
1.250定律
拉德认为:每一位顾客身后,大体有250名亲朋好友。如果您赢得了一位顾客的好感,
就意味着赢得了250个人的好感;反之,如果你得罪了一名顾客,也就意味着得罪了250
名顾客。 在你的网站访客中,一个访客可能可以带来一群访客,任何网站都有起步和
发展的过程,这个过程中此定律尤其重要。
2.达维多定律
达维多认为,一个企业要想在市场上总是占据主导地位,那么就要做到第一个开发出新
产品,又第一个淘汰自己的老产品。 国内网站跟风太严重,比如前段时间的格子网,
乞讨网,博客网,一个成功了,大家一拥而上。但实际效果是,第一个出名的往往最成
功,所以在网站的定位上,要动自己的脑筋,不是去捡人家剩下的客户。同理,买人家
出售的数据来建站效果是很糟糕的。
3.木桶定律
水桶定律是指,一只水桶能装多少水,完全取决于它最短的那块木板。这就是说任何一
个组织都可能面临的一个共同问题,即构成组织的各个部分往往决定了整个组织的水平
。 注意审视自己的网站,是速度最糟糕?美工最糟糕?宣传最糟糕?你首先要做的,
不是改进你最强的,而应该是你最薄弱的。
4.马太效应
《新约》中有这样一个故事,一个国王远行前,交给三个仆人每人一锭银子,吩咐他们
:“你们去做生意,等我回来时,再来见我。”国王回来时,第一个仆人说: “主人
,你交给我们的一锭银子,我已赚了10锭。”于是国王奖励他10座城邑。第二个仆人报
告说:“主人,你给我的一锭银子,我已赚了5锭。” 于是国王例奖励了他5座城邑。
第三个仆人报告说:“主人,你给我的一锭银子,我一直包在手巾里存着,我怕丢失,
一直没有拿出来。”于是国王命令将第三个仆人的一锭银子也赏给第一个仆人,并且说
:“凡是少的,就连他所有的也要夺过来。凡是多的,还要给他,叫他多多益善。”这
就是马太效应。 在同类网站中,马太效应是很明显的。一个出名的社区,比一个新建
的社区,更容易吸引到新客户。启示是,如果你无法把网站做大,那么你要做专。作专
之后再做大就更容易。
5.手表定理
手表定理是指一个人有一只表时,可以知道现在是几点钟,而当他同时拥有两只表时却
无法确定。一个网站,你只需要关注你特定的用户群需求。不要在意不相干人的看法。
6.不值得定律
不值得定律:不值得做的事情,就不值得做好 不要过度seo,如果你不是想只做垃圾站
。不要把时间浪费在美化再美化页面,优化再优化程序,在你网站能盈利后,这些事情
可以交给技术人员完成。
7.彼得原理
劳伦斯.彼得认为:在各种组织中,由于习惯于对在某个等级上称职的人员进行晋升提
拔,因而雇员总是趋向于晋升到其不称职的地位。不要轻易改变自己网站的定位。如博
客网想变门户,盛大想做娱乐,大家拭目以待吧。
8.零和游戏原理
当你看到两位对弈者时,你就可以说他们正在玩“零和游戏”。因为在大多数情况下,
总会有一个赢,一个输,如果我们把获胜计算为得1分,而输棋为-1分,那么,这两人
得分之和就是:1+(-1)=0 不要把目光一直盯在你的竞争网站上,不要花太多时间抢
它的访客。我们把这些时间用来寻找互补的合作网站,挖掘新访客。
9.华盛顿合作规律
华盛顿合作规律说的是: 一个人敷衍了事,两个人互相推诿, 三个人则永无成事之日
。如果你看准一个方向,你自己干,缺人手就招。不要轻易找同伴一起搞网站,否则你
会发现,日子似乎越过越快了,事情越做越慢了。
10.邦尼人力定律
一个人一分钟可以挖一个洞,六十个人一秒种却挖不了一个洞。合作是一个问题,如何
合作也是一个问题。你需要有计划。
11.牛蛙效应
把一只牛蛙放在开水锅里,牛蛙会很快跳出来;但当你把它放在冷水里,它不会跳出来
,然后慢慢加热,起初牛蛙出于懒惰,不会有什么动作,当水温高到它无法忍受的时候
,想出来,但已经没有了力气。 如果你是soho,注意关注你的财务。不要等到没钱了
再想怎么挣,你会发现那时候挣钱更难。
12.蘑菇管理
蘑菇管理是许多组织对待初出茅庐者的一种管理方法,初学者被置于阴暗的角落(不受
重视的部门,或打杂跑腿的工作),浇上一头大粪(无端的批评、指责、代人受过),
任其自生自灭(得不到必要的指导和提携)。 做网站毕竟要遭遇这样的阶段,搜索引
擎不理你,友情链接找不到,访客不上门。这是磨练。
13.奥卡姆剃刀定律
如无必要,勿增实体。把网站做得简单,再简单,简单到非常实用,而不是花俏。
google的首页为什么比雅虎好?
14.巴莱多定律(Paredo 也叫二八定律)
你所完成的工作里80%的成果,来自于你20%的付出;而80%的付出,只换来20%的成果。
随时衡量你所做的工作,哪些是最有效果的。
15.马蝇效应
林肯少年时和他的兄弟在肯塔基老家的一个农场里犁玉米地,林肯吆马,他兄弟扶犁,
而那匹马很懒,慢慢腾腾,走走停停。可是有一段时间马走得飞快。 林肯感到奇怪,
到了地头,他发现有一只很大的马蝇叮在马身上,他就把马蝇打落了。看到马蝇被打落
了,他兄弟就抱怨说:”哎呀,你为什么要打掉它,正是那家伙使马跑起来的嘛!”
在你心满意足的时候,去寻找你的马蝇。没有firefox,不会有ie7,firefox就是微软
的马蝇之一。马蝇不可怕,怕的是会一口吃掉你的东西,像 ie当初对网景干的那样。
16.最高气温效应
每天最热总是下午2 时左右,我们总认为这个时候太阳最厉害,其实这时的太阳早已偏
西,不再是供给最大热量的时候了。此时气温之所以最高,不过是源于此前的热量积累
。你今天的网站流量,是你一个星期或更长时间前所做的事带来的。
17.超限效应(溢出效应)
刺激过多、过强和作用时间过久而引起心理极不耐烦或反抗的心理现象,称之为“超限
效应”。 别到别人论坛里发太多广告。别在自己网站上放太多广告。别在自己的论坛
里太多地太明显地诱导话题。
18.懒蚂蚁效应
生物学家研究发现,成群的蚂蚁中,大部分蚂蚁很勤劳,寻找、搬运食物争先恐后,少
数蚂蚁却东张西望不干活。当食物来源断绝或蚁窝被破坏时,那些勤快的蚂蚁一筹莫展
。“懒蚂蚁”则“挺身而出”,带领众伙伴向它早已侦察到的新的食物源转移。 不要
把注意力仅仅放在一个网站上,即使这个网站现在为你带来一切。你要给自己一些时间
寻找新的可行的方向,以备万一。
19.长尾理论
ChrisAnderson认为,只要存储和流通的渠道足够大,需求不旺或销量不佳的产品共同
占据的市场份额就可以和那些数量不多的热卖品所占据的市场份额相匹敌甚至更大。
对于搜索引擎,未必你需要一个热门词排在第一位,如果有一千个冷门词排在第一位,
效果不但一样,还会更稳定更长远。
20.破窗理论
栋建筑上的一块玻璃,又没有及时修好,别人就可能受到某些暗示性的纵容,去打碎更
多的玻璃。 管理论坛时,如果你发现第一个垃圾贴,赶紧删掉他吧。想想:落伍现在
为什么那么多××贴?现在控制比最初控制难多了。
21.“羊群效应”,
又称复制原则(Copy Strategy)一个羊群(集体)是一个很散乱的组织,平时大家在一起
盲目地左冲右撞。如果一头羊发现了一片肥沃的绿草地,并在那里吃到了新鲜的青草,
后来的羊群就会一哄而上,争抢那里的青草,全然不顾旁边虎视眈眈的狼,或者看不到
其它地方还有更好的青草。不要轻易跟风,保持自己思考的能力。
22.墨菲定律
如果坏事情有可能发生,不管这种可能性多么小,它总会发生,并引起最大可能的损失
。除非垃圾站,否则不要作弊,对搜索引擎不要,对广告也不要。
23.光环效应
人们对人的某种品质或特点有清晰的知觉,印象比较深刻、突出, 这种强烈的知觉,
就像月晕形式的光环一样,向周围弥漫、扩散,掩盖了对这个人的其他品质或特点的认
识。不要轻易崇拜一个人或者公司、一个概念、一种做法。
24.蝴蝶效应
一只亚马逊河流域热带雨林中的蝴蝶,偶尔扇动几下翅膀,两周后,可能在美国德克萨
斯州引起一场龙卷风。不管你做什么,网站或者其他,你都应该关注新闻。机遇或者灾
难可能就在那。
25.阿尔巴德定理
一个企业经营成功与否,全靠对顾客的要求了解到什么程度。 我赞同别人的点评:看
到了别人的需要,你就成功了一半;满足了别人的需求,你就成功了全部。尤其是做网
站。
26.史密斯原则
如果你不能战胜他们,你就加入到他们之中去。 不要试图做孤胆英雄。如果潮流挡不
住,至少,你要去思考为什么。
http://forums.asp.net/t/1127834.aspx you can use the following javascript function to set the active tab: function SetActiveTab(tabControl, tabNumber) { var ctrl = $find(tabControl); ctrl.set_activeTab(ctrl.get_tabs()[tabNumber]); } tabControl: ID from the TabContainer Controls tabNumber: Number of the new Tab (starting at 0) Or $find('<%=TabContainer1.ClientID%>').get_activeTabIndex(); and $find('<%=TabContainer1.ClientID%>').set_activeTabIndex(2);
http://blenitz.blogspot.com/2007/09/hidden-columns-with-values-aspgridview.html (If you don't want to show empty headtitle, put the hidden filed in with other field in one grid colomn) If you set Column Visible property to false, this column won't rendered. But if you want these values available, What will you do? My trick was, set HeaderText to empty, convert the BoundField in TemplateField, and use a HiddenField control. The effect the column won't be visible. Also you can use the controls array to access to value property. <Columns><asp:BoundField DataField="CompanyCode" HeaderText="Company" SortExpression="CompanyCode" /> ... <Columns> <asp:TemplateField><ItemTemplate><asp:HiddenField id="hf1" Value='<%# Bind("CompanyCode") %>' runat="server"></asp:HiddenField></ItemTemplate> ... // accesing the value property int tmpID = Convert.ToInt32(((HiddenField)GridView1.SelectedRow.Cells[3].Controls[1]).Value);
Following are some of my observations got from the book: Chapter 1&2 - XAML is just a way to use .NET APIs. WPF and XAML can be used independently from each other.
- XAML specification defines rules that map .NET namespaces, types, properties, and events into XML namespaces, elements, and attributes.
- Markup extensions are just classes with default constructors.
- An object element can have three types of children: a value for a content property, collection items, or a value that can be type-converted to its parent.
Chapter 3 Important new Concepts in WPF Logic Tree The logical tree concept is straightforward, but why should you care about it? Because just about every aspect of WPF (properties, events, resources, and soon) has behavior tied to the logical tree. For example, property values are sometimes propagated down the tree to child elements automatically, and raised events can travel up or down the tree. Both of these behaviors are discussed later in this chapter. Visual Tree A similar concept to the logical tree is the visual tree. A visual tree is basically an expansion of a logical tree, in which nodes are broken down into their core visual components. Rather than leaving each element as a “black box,” a visual tree exposes the visual implementation details. For example, although a ListBox is logically a single control, its default visual representation is composed of more primitive WPF elements: a Border, two ScrollBars, and more. Dependency Properties A dependency property depends on multiple providers for determining its value at any point in time. These providers could be an animation continuously changing its value, a parent element whose property value trickles down to its children, and so on. Arguably the biggest feature of a dependency property is its built-in ability to provide change notification. Change Notification (Property Trigger) Property Value Inheritance Multiple Providers Attached Properties Routed Events (routing Strategies:tunneling, bubbling, Direct) Attached Events Commands: a more abstract and loosely-coupled version of events. 
From: http://www.mikeduncan.com/3-hot-uses-for-httpcontextcurrentitems-they-wont-tell-you-about/ Generally, HttpContext.Current.Items doesn’t get all that much hot blog press, but let me tell you, I’m here to change all that. For those out of the know, System.Web.HttpContext.Current.Items is a sweet key-value pair collection you can use to pass objects around up and through all components that participate in a single HTTP request. What does this mean? This means that in a way similar to sticking something in the Session or cache, you can jam some values into the HttpContext.Current.Items for your request, say in a HttpModule way down low before you’ve even begun to fetch a page, and have those values readable/writable later from your page and all its usercontrols. The Items only persist through this one-night-stand of a single request and then supposedly “lose your number” but that’s ok, because we don’t really need all their drama after that anyway. 1) Preparing objects down low, on the down-low. As alluded to earlier, one sweet use of HCI (as we call in on the street) is in HttpModules. Let’s say you are doing some url-rewriting for user-friendliness or SEO reasons. While you’re at it, why not do a little preparation for your page? If you have a query param of state abbreviation that comes in commonly, populate an additional full state name display field ahead of time. Clean up your strings with proper casing, do whatever utils you think you can get away with while you have the request in your hand. I have a little object of getters and setters that I populate in the the HttpModule, and stick it in the Current.Items for its way up the stack. Now my pages and usercontrols can pull out my cleaned up custom object from the Context.Items and act accordingly, pass it down the line to methods, whatever. The vibe is maybe a hint at a smidgen of a wee bit Model View Controller-ish, but not really. 2) Making params and pages more unit-testable. With something like #1 in place, you can pull objects of params and prepared goodness out of the request and process them in your code behind, presenter, usercontrol, whatever strikes your pattern fancy. If this bundle of params is a in a nice little object that implements an interface, this makes unit testing logic that under normal circumstances relies upon getting info from the System.Web namespace (querystring params mostly) nice and easily decoupled. Pros of this are that your view calling your presenter can stay super lean and mean without having to populate a bunch info from query strings which will end up going through standard transformations you could have handled earlier on. A con is that the population of these params might be a bit mysterious to other devs who don’t see the HttpModule in action, sort of a like a table that gets populated from somewhere or other, but you don’t know what trigger where. I hate that. 3) Populating usercontrols without the hassle. If you know you have values in your hand at page on_load or earlier, it’s pretty damn convenient to stick them in the HttpContext.Current.Items and then just read them out from whatever usercontrols may or may not be dynamically included on the page. No finding child controls from the page, no finding parent info from the controls. No casting, scoping or otherwise thinking about precisely what order what will fire. If you have the data at page_load, your controls can get it. Don’t call me, and I won’t call you either. Ta-dow (does anyone say that anymore?). So there you have it, HttpContext.Current.Items, arcane enough to give you guru-cred to the mid-range noobs, simple enough that it can be leveraged for good and / or evil. Awesome.
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
<asp:GridView ID="GridViewYardSales" runat="server" CssClass="yui-datatable-theme" AutoGenerateColumns="false" DataSourceID="YardSaleDataSource" AllowSorting="true" OnRowCommand="GridViewYardSales_RowCommand" OnRowCreated="GridViewYardSales_RowCreated" DataKeyNames="ItemId"> <RowStyle CssClass="data-row" /> <AlternatingRowStyle CssClass="alt-data-row" /> <Columns> <asp:BoundField DataField="ItemId" HeaderText="ItemId" ReadOnly="True" SortExpression="ItemId" Visible="false"></asp:BoundField> <asp:TemplateField ItemStyle-HorizontalAlign="Center" ItemStyle-Width="20px"> <ItemTemplate> <asp:LinkButton ID="LinkButtonViewOnMap" runat="server" OnClientClick=<%# String.Format("javascript:ViewOnMapById('{0}');", Eval("ItemId")) %>> Map</asp:LinkButton><br /> <asp:LinkButton ID="LinkButtonItinerary" runat="server" CommandName="Command_Itinerary" CommandArgument='<%# Eval("ItemId") %>'>Itinerary </asp:LinkButton><br /> <asp:LinkButton ID="LinkButtonViewDetail" runat="server" CommandName="Command_ViewItemDetail" CommandArgument='<%# Eval("ItemId") %>'>Detail </asp:LinkButton> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="Title"> <ItemTemplate> <%# Eval("Title") %><br /> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="Date"> <ItemTemplate> <%# Eval("Time") %> </ItemTemplate> </asp:TemplateField> </Columns> </asp:GridView> protected void GridViewYardSales_RowCreated(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { //Retrieve LinkButton control int m_RowIndex = e.Row.RowIndex; string id = GridViewYardSales.DataKeys[m_RowIndex].Value.ToString(); LinkButton lb = (LinkButton)e.Row.FindControl("LinkButtonItinerary"); if (IsItemAlreadyInItinerary(id)) { lb.Text = "Remove"; } else { lb.Text = "Add"; } } } protected void GridViewYardSales_RowCommand(object sender, GridViewCommandEventArgs e) { if (e.CommandName == "Command_Itinerary") { string id = e.CommandArgument.ToString(); GridViewRow selectedRow = (GridViewRow)(((Control)e.CommandSource).NamingContainer); LinkButton lb = (LinkButton)selectedRow.FindControl("LinkButtonItinerary"); if (!IsItemAlreadyInItinerary(id)) { AddItemToItinerary(id); lb.Text = "Remove"; } else { RemoveItemFromItinerary(id); lb.Text = "Add"; } } else if (e.CommandName == "Command_ViewItemDetail") { string id = e.CommandArgument.ToString(); Response.Redirect("ViewSale.aspx?id=" + id); } }
<asp:GridView ID="GridViewYardSales" runat="server" CssClass="yui-datatable-theme" AutoGenerateColumns="false" DataSourceID="YardSaleDataSource" AllowSorting="true" OnRowCommand="GridViewYardSales_RowCommand" OnRowCreated="GridViewYardSales_RowCreated" DataKeyNames="ItemId"> <RowStyle CssClass="data-row" /> <AlternatingRowStyle CssClass="alt-data-row" /> <Columns> <asp:BoundField DataField="ItemId" HeaderText="ItemId" ReadOnly="True" SortExpression="ItemId" Visible="false"></asp:BoundField> <asp:TemplateField ItemStyle-HorizontalAlign="Center" ItemStyle-Width="20px"> <ItemTemplate> <asp:LinkButton ID="LinkButtonViewOnMap" runat="server" OnClientClick=<%# String.Format("javascript:ViewOnMapById('{0}');", Eval("ItemId")) %>> Map</asp:LinkButton><br /> <asp:LinkButton ID="LinkButtonItinerary" runat="server" CommandName="Command_Itinerary" CommandArgument='<%# Eval("ItemId") %>'>Itinerary </asp:LinkButton><br /> <asp:LinkButton ID="LinkButtonViewDetail" runat="server" CommandName="Command_ViewItemDetail" CommandArgument='<%# Eval("ItemId") %>'>Detail </asp:LinkButton> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="Title"> <ItemTemplate> <%# Eval("Title") %><br /> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="Date"> <ItemTemplate> <%# Eval("Time") %> </ItemTemplate> </asp:TemplateField> </Columns> </asp:GridView>
<asp:TemplateField ItemStyle-HorizontalAlign="Center" ItemStyle-Width="20px"> <ItemTemplate> <%# Convert.ToInt32(DataBinder.Eval(Container, "DataItemIndex")) + 1 %>. </ItemTemplate> </asp:TemplateField>
nextdooryardsale(s) yardsalenextdoor yardsalecitymap(s) yardsaleminer yardsaledailymap yardsalemapplet
- Add map check button on addnew page
- Add error page
- Add search page
- Add date check service (Remove or archive old items)
- Add admin management notification.
- Add gui for operator
- Add configuration to allow user to add ad in Craigslist way
- Update grid code
- Update layout and style
- Add Logo
- Decide domain name
- Add small icon for sale types
今天看了一篇关于网站运作、服务器负载的文章,讲得很独到,也很有意义,很现实,建议大家都看看,这些问题我相关很多创业项目忽略或处理得不够深。 这个文章中提到的问题很多看起来是很细的一件事情,但恰恰这就直接导致运作的成败 大家讨论,一定要仔细看完! 原文: 我做过多个2.0公司的技术顾问,简单的谈谈2.0公司遇到的问题(涉及隐私,我用A B C D代替),这里就不再赘述大家众所周知的页面静态化,缓存和代码安全等问题了,有点技术的2.0公司的CTO都知道这些东西,我们谈点发展之后的问题 A公司 A公司做的是SNS网站,程序是两个毛头小伙子做的,目标直指51,程序开发是一帆风顺,功能也比51牛多了,推广也是一帆风顺(A公司有自己独到的推广方式。但是当ALEXA到2W的时候问题出来了,每天下午4点左右,网站速度慢的惊人,基本上打不开,公司三台服务器CPU100%,让人郁闷的是公司的网络配置方式,居然是双WEB的集群,而单独一台DB数据库。整个瓶颈在数据库,于是我建议做DB的集群,分析了一下数据结构,MD,典型的WEB程序员的作品,没有一点数据库设计规范,功能实现是可以,如果要扩展,不可能,集群基本上是不可能的,怎么办?不能办,于是,一个月的时间修改程序,数据结构基本上换了一遍 前期砸进去的几十万打了水飘,用户走光了。 结论:WEB2.0前期设计的时候不应该只考虑功能,应该认真考虑一下底层和数据结构了。 B公司 B公司也是做的SNS网站,程序是3个人开发的,CEO是某名牌大学的经济学硕士,有点知己网的味道,又有一些特色出来,说实话,公司的潜力不错,CEO 有很强的运作能力,感觉前景不错。系统架构还行,但是---但是系统崩溃了,why?系统没有考虑到用户有个海量的说法,文件也有个海量的说法,用户的相册,图片全部存贮在WEB服务器的一个分区上,每个用户一个目录,而打开性能监视器,磁盘的IO高的惊人,基本上无暇响应。众所周知,文件系统也是一个数据库,单独大文件无所谓,关键是整个是300多个G的零碎文件,大量的读写操作,系统崩溃,数据丢失,文件系统的一个链断了,用户数据全部丢失!!!这是一个非常沉重的问题,系统整整停了一个月来做数据恢复(单独文件很容易,但是海量文件目前还没有一个软件能组织起来软件架构)。解决方案:修改程序架构,做分布式文件存贮(程序修改用了8天,但是文件转移却又用去了将近一个月),20万用户损失殆尽 结论:WEB2.0前期的设计应该有应付海量存贮的考虑,整个涉及了程序架构的修改,前期规划不好的话基本上思路一条。 C公司 C公司是一个值得尊敬的公司,CEO技术出身,和比尔盖茨一样,大学未毕业出来做网络,01到03年做短信狠赚了一笔,后来做的小项目也小有所成,说实话,我很佩服。公司做的是校友方面,但是更偏重myspace风格,注重个人主页,推广方面也下了大手笔。系统崩溃的原因其实很简单,由于采用的是微软的 SqlServer,而微软直接就告诉了我们,SQLSERVER不支持集群,他们的数据库超负载,100%就没有下去过,只能横向增加配置,采用了4路 4核CPU系统,但是系统还是崩溃了... 高互动注定了高负载。解决方案:现从基本入手,解决掉几个程序耗能大户,对数据库采用横向切割,将用户每10万进行分组,同时对数据库系统进行散列,将多个表垂直分割,同时进行文件分组,解决问题. 因为修改了数据结构,程序也基本上大动了一下。 好在系统没有出大错,损失不算很大,不过对用户体验造成了很坏的影响。 结论:WEB2.0前期设计应该有良好的散列考虑,程序应该能有配合的扩充性,符合数据库的扩充 D公司 D公司是一个各个方面做的比较好的公司,做了CDN加速,图片也独立分出了N个服务器,数据库不错的一个,(CTO是个数据库专家),系统崩溃的原因在于 WEB,按道理说WEB很容易做集群的,但是发现集群并解决不掉问题,他们的集群只允许做4台的WEB集群,但是4台都当掉了。仔细分析,找到原因,我估计整个也是大部分CTO最容易犯的一个错误,或者说他们根本就想不到的问题,就是WEB上传的问题,上传的时候由于时间的原因,线程是保持链接的,300 个线程就可以把一个WEB Server当掉了。解决方案:这个最简单,把上传和其他耗能大户分离出独立出来。程序改动不是很大,但是之前半个月速度满对用户体验的损失也不可小视。 结论:没有什么结论了,毕竟有海量访问经验的CTO不多,也就是那几个大站的。 总结:不是泼冷水,模仿其实是很容易的,随便找几个WEB程序员就能做到,并且很简单,速度可能还很高效,因为WEB2.0无非就是跟数据库打交道,会操作数据库就会做。但是真正做大并不容易,因为能应付海量访问的程序并不简单,现在的程序员都太自命不凡,其实真正有经验的并不多,不要相信一个月薪5K- -10K的程序员能给你多大的惊喜,能应付海量访问的程序员不是那个价格。如果您想做2.0,想做大,有几个个建议: 一.找DBMS的专家设计好数据库,大部分程序员都不知道分区视图,数据散列,数据组的概念 二.设计好程序架构(这个其实不难,有个高人指导就行了),保持良好的扩展性,成本考虑可以找兼职的系统架构设计师做好系统架构,确定将来的发展瓶颈。 三.考虑好文件存贮的问题。文件存贮的技术含量看起来很低,其实是很高的,可以考虑反向代理的方案。文件存贮出问题了,站点基本上就完蛋了,不仅仅是RAID的问题和存贮服务器的问题,不过道理倒是一点就破的 四.中国国情考虑,这个最致命,需要考虑电信和网通的问题,CDN并不能解决所有问题。互动性的东西并CDN并不是很有效。最关键的是,现有的双线机房遇到DDOS攻击基本上都会当掉,原因很简单,双线机房都是私人机房,本身就不会有太高的带宽,随便攻击一下就可以D掉(顺带提一个笑话,我知道一个双线机房的老总总共1G的带宽却买了4G的金盾墙,很简单800M的攻击就可以搞定)。 五.网络延迟的问题,这是分布式系统必须要考虑的,程序要能容忍0到100秒的数据延迟的功能,也就是同步的问题。不要小看这几十秒,问题很大的,如果你的站点有交互式功能,比如即时聊天,你可以想象一下是个什么结果。对于即时聊天的东西,可以用反向代理来解决(成本较高)。但是对于留言和评论的影响不大,但是如果系统为了健壮做了缓存和静态化的时候,这个东西可能就是灾难性的了。 六.分散你的程序,如果你没有太多的资金构筑动辄百万的服务器,建议把功能分散开来,比如相册一台服务器,留言一台服务器 七.看好你的程序员,如果没有很好的激励措施的话你的程序员很容易写出敷衍性的代码,而这个可能就是将来的大患,程序架构定下来后要修改可能就要费牛劲了。最好你的CTO能对你100%的衷心,100%的负责。 八.文件同步的问题,这个问题可能你觉得没有必要,如果你看一下网通和电信的TTL就明白了,同步要支持续传,并且不能是持续的,否则你的成本会高出N倍,不要期望能通过你的软件实现,交给你的程序员吧,把上面的话告诉他他就知道怎么做了。 九.最狠的一个问题了,也是吃亏最大的问题,不管您跟网警的关系多好,看好你的用户,审核好你的东西,一被停机可能就致命,本人就吃过N次亏。 十.最后,祝各位站长一番风顺,大展宏图。 朋友发的,不知道哪里看到的
1. Generate Yard Sale flyer (html and pdf) 2. Generate route map (list and directions) 3. RSS subscription
Chapter2 New Management Responsibilities ScrumMaster The ScrumMaster fills the position normally occupied by the project manager. I’ve taken the liberty of redefining this role. While the traditional project manager is responsible for defining and managing the work, the ScrumMaster is responsible for managing the Scrum process. To put it simply, ScrumMasters make Scrum work. The Scrum process defines practices, meetings, artifacts, and terminology. The ScrumMaster is responsible for knowing these and knowing how to apply them correctly. Scrum can be applied incorrectly, as we will see. But because the ScrumMaster has a clear understanding of how Scrum works and has experience applying Scrum, the ScrumMaster knows how to guide a Scrum project through the shoals of complexity. Like sheep in an open field, individuals in a project tend to stray. The ScrumMaster’s job is to keep the flock together. In fact, I often compare a ScrumMaster to a sheepdog, responsible for keeping the flock together and the wolves away. Product Owner The Product Owner’s focus is return on investment (ROI). The Product Backlog provides the Product Owner with a powerful tool for directing the project, Sprint by Sprint, to provide the greatest value and ROI to the organization. The Product Owner uses the Product Backlog to give the highest priority to the requirements that are of highest value to the business, to insert nonfunctional requirements that lead to opportunistic releases and implementations of functionality, and to constantly adjust the product in response to changing business conditions, including new competitive offerings. Team In a huge reversal of ordinary management practices, Scrum makes the team responsible for managing development activities. Traditionally, the project manager tells the team what to do and manages its work. In Scrum, however, the team selects the work that it will do during each Sprint. After that initial selection is made, it is up to the team to figure out how to do the work at hand. The team decides how to turn the selected requirements into an increment of potentially shippable product functionality. The team devises its own tasks and figures out who will do them. The pressure inherent in a 30-day Sprint, the commitment the team members make to each other to accomplish something, and the principles of self- organization and cross-functional responsibilities all help the team successfully fulfill this responsibility. The team unfailingly rises to the occasion and manages itself. When anyone outside the team tries to tell the team what to do, more damage than good usually results. I don’t know why Scrum’s self-organization works so well, but that hardly matters. After all, I know of hundreds of successful Scrum projects encompassing thousands of successful Sprints.
http://mattberseth.com/blog/2007/06/aspnet_ajax_use_pagemethods_pr.html (Good Solution) Matt Berseth is always the best. http://forums.asp.net/p/1104368/1717972.aspx You could put a Hidden control on a form, set it's value at the server and then read it with JavaScript at the client. You can do this in javascript, but you will not be able to put the javascript in an external (*.js) file. Put the following code in your <head> section and it will work: <script type="text/javascript" language="javascript">
window.onload = function() {
var a = '<%=Session["lon"]%>';
alert(a);
}
</script> Use <%# ...%> instead.
Chapter 1: There are three legs that hold up every implementation of empirical process control: visibility, inspection, and adaptation. I've limited my enumeration of complexity in software development to the three most significant dimensions: requirements, technology, and people. The skeleton operates this way: At the start of an iteration, the team reviews what it must do. It then selects what it believes it can turn into an increment of potentially shippable functionality by the end of the iteration. The team is then left alone to make its best effort for the rest of the iteration. At the end of the iteration, the team presents the increment of functionality it built so that the stakeholders can inspect the functionality and timely adaptations to the project can be made. The heart of Scrum lies in the iteration. The team takes a look at the requirements, considers the available technology, and evaluates its own skills and capabilities. It then collectively determines how to build the functionality, modifying its approach daily as it encounters new complexities, difficulties, and surprises. The team figures out what needs to be done and selects the best way to do it. This creative process is the heart of the Scrum's productivity. There are only three Scrum roles: the Product Owner, the Team, and the ScrumMaster. "Ham and Eggs!" - Monthly Sprint planning meeting
- Daily Scrum meeting
- monthly Sprint review meeting
- Sprint retrospective meeting
Tasks should be divided so that each takes roughly 4 to 16 hours to finish. Tasks longer than 4 to 16 hours are considered mere placeholders for tasks that haven't yet been appropriately defined.
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.
Introduction to workflow http://en.wikipedia.org/wiki/Workflow http://www.e-workflow.org/bookstore/introduction_to_workflow02.pdf http://blogs.msdn.com/davegreen/archive/2005/09/17/470704.aspx http://www.aboutworkflow.com/WorkflowTutorial/index.htm http://www.sqldts.com/287.aspx http://www.e-workflow.org/standards/index.htm Workflow Control-Flow Patterns http://www.workflowpatterns.com/documentation/documents/BPM-06-22.pdf http://www.workflowpatterns.com/patterns/control/index.php http://www.workflowpatterns.com/documentation/index.php http://en.wikipedia.org/wiki/Workflow_patterns (Good) BPEL Is BPEL the same as BPM, workflow or integration? http://searchwebservices.techtarget.com/ateQuestionNResponse/0,289625,sid26_cid565868_tax292928,00.html Service-Oriented Architecture-Concepts, Technology, and Design (book) web Services Platform Arthitecture - SOAP, WSDL, WS-Policy, WS-Addressing, WS-BPEL, (book) Implementation Deploy distributed business processes with windows workflow and web service http://msdn.microsoft.com/msdnmag/issues/06/10/webserviceworkflows/ http://blogs.msdn.com/publicsector/archive/2005/10/27/485691.aspx Orchestrating Web Service http://www.ftponline.com/xmlmag/2002_06/magazine/focus/sjohnston/default.aspx Orchestration and Choreography Service-Oriented Architecture - Concepts, Technology, and Design Business processes and workflow in the Web services world http://www.ibm.com/developerworks/webservices/library/ws-work.html
http://www.doshdosh.com/learn-from-adsense-millionaire-markus-frind/ The quoted text is extracted from some of Markus’s blog posts as well as interviews over the past few years. All of the specific references are left at the bottom of the post and do visit them to read more, if you’re interested. - Enter the Market at the Right Time. “As for the growth, a think a lot of that was accidental or first-mover advantage. Here in Canada LavaLife was the only real dating site, and they had a monopoly. I had a couple of my friends sign up from the major cities and after that the site just started to grow and spread.”
- Free is a Powerful Business Model. “I always liked free sites and couldn’t see why companies had to change insane amounts of money for something that was trivial to make.”
“The community was really built by word of mouth. There was a need for a free site and because no one else was providing it, it just grew like a weed. A lot of people just don’t want to pay for dating sites.” - You Don’t Need a Team. “It’s just me right now, my girlfriend helps with some of the customer service stuff when I don’t want to do it. I am planning on expanding into other markets but I don’t think I need to hire any employees any time soon. Nearly all the work can be automated away except for user stupidity that leads to crazy questions.”
- Offline Marketing is Not Essential. “Offline promo works well when marketing to huge existing customer base. It does not work well when trying to grow big…Like nearly every other site I sort of ignore offline marketing, as it is far too expensive when you don’t have huge numbers of people in your target market already using your service.”
- Success Doesn’t Just Depend on One Thing. “I like simplicity, and I am not a graphic designer at all. Success doesn’t come down to just one thing. Its not like Microsoft can clone Google’s layout and be the largest search engine. Success is a combination of things and having the right idea at the right time.”
- Uptime is Just as Important as Innovation. “I redesign my site every couple of weeks so it doesn’t get crushed by the sheer number of users online. As for front-end design I could care less, lots of users are using my site and more are coming every day, my number one focus is making sure the site stays up for another day.”
- Create Unique Sites that Stand Out. “Google pays out $500 million a quarter to AdSense users. That money is going somewhere, and if you look at the top 1000 sites not a hell of a lot of them have AdSense.
Statistically speaking those sites that have low numbers of users and high EPC [Earnings Per Click] will make the most money. Build sites that no one else has done before, stuff only goes viral the first 1 or 2 times after that you have to buy your way into a market.” - You Need to Have a Rigorous Work Ethic. “When I came home from work I sat down and I forced myself to code for a hour or 2. The enemy was thinking, whenever I paused or started to think I would force myself to type something, its amazing how much you can get done when you just type.
For that business its just a matter of repetition and fighting boredom. At the end of the day you just need to sit down and DO it. Most people don’t.” - Site Value and Functions Trump Design. “Function over form to build an emotional connection with the user. Blend ads into content, No flashing crap, make the site useful. Basically all those things that everyone knows you are supposed to do, but very few people actually do.
There is no magic bullet, but you should always test new designs or new text etc to get the result that you want. You will never have the worst design and never the best, but through testing you can always improve.” - Think of Monetization Potential Before Starting a Site. “Build something useful, simple in ways that people will use. Explore things like Ad Sense, affiliate programs, and just explore ways of making money. Most 2.0 companies will never make a dime and they’re not built to make a dime.
So I would start looking at how to make money before you even design or think about starting a business.” - Don’t be Discouraged With Low Income. “I had a single affiliate program but it didn’t even make $40/month. I went and added Adsense pretty quick, I made a whole $5.63 cents my first month, but that was more then enough for me to realize that I wouldn’t go broke running the site and I could make a business out of this with enough traffic.”
- Learn What You Need to Know. “Basically I spent every waking minute when I wasn’t at my day job reading, studying, and learning. I picked out “enemies” and did everything I could to defeat them which meant being bigger then them. I refused to accept defeat of any kind, and I constantly forced myself to test new things.”
- When You Have Traffic, Look Beyond Adsense. “The main goal is to start replacing adsense/dating ads and hire sales people. I spent the last few weeks working long days optimizing my ad revenue and as a result adding over a million a year net per week of work.
At the end of the day its not possible for me optimize revenues myself or to outsource sales as no one vender could sell more than 3% of my inventory. I am at a size now were there are no off the shelf solutions and everything has to be built from the ground up.” - Know the Limits of Your Business Model. “If I wanted to generate $100 million in revenues per year it would be pretty easy, all I need to do is convert to a paid site. To generate 100 million a year as a free site is virtually impossible as the market isn’t big enough.
I’m already the largest player in the UK, Canada, and US. Growing the company another 10 to 20 fold just isn’t realistic.” - Always Have a Goal to Work Towards. “If you are working in a cubicle, your goal may be to experience the world outside of your cage, or stay at a 5 star whenever you want, or to go on vacation whenever you want.
For me i’d set my goal to owning the whole resort and the yacht out front and making 100 million a year instead of just millions. Just because you are already successful doesn’t mean you don’t need a goal to work towards. Don’t assume that anyone successful thinks differently then you.” - Success Doesn’t Happen, It’s Created. “Now I know most of the people reading this are aspiring to create a business of some kind. Many will just day dream all day but never actually do anything.
I was like that a few years ago, then I finally sat down and did something, and kept forcing myself to do it till it became a pattern and it turned out hugely successful.” - Weigh Your Costs to Estimate Profitability. “In my opinion if the cost of your operations are 2-3 cents a unique visitor chances are plain advertising will bring you to profitability. If your costs are over 10 cents a unique visitor then you will need to sell a product or service.
This of course assumes a high traffic site with at least 100k uniques per day. In about 2 years from now we will probably see a 30-50% decrease in operational costs as hardware and software costs continue to fall.”
Silverlight should be a good choice to create such a web site. Main function includes: Category AD management Drag and Drop RSS
Go to Tools->Connect To Device. From the platform select Windows mobile 5.0 Pocket PC SDK. Now start Windows Mobile 5.0 Pocket PC Emulator. This will start the WM5.0 PPC emulator. You will probably need to copy your html files to emulator. For this you need to have Active sync 4.0 on your matchine installed. Preview version is available on Microsoft site. In active sync, open File->Connection Settings. In this dialog box make sure "Allow connections to be one of the following:" has DMA. Now in Visual Studio, Tools->Device emulator manager. This will launch Device Emulator Manager. In this Go to the emulator which you need and right click and cradle. This will establish a partnership with AS. Now using AS->Explore you can copy your files as appropriately.
Get Label control text value in java script code: var x = document.getElementById('<%= Label1.ClientID %>').innerText; Get text value of textbox in java script code: Say you have a textbox like follows: <asp:TextBox id="txtMyTextBox" runat="Server" Text="1234"></asp:TextBox> In javascript do the following to get value: var value = document.getElementById('<%=txtMyTextBox.ClientID%>').value; As TextBox is server control, so on runtime this control have different client id '<%=txtMyTextBox.ClientID%>' will return control clientid on runtime Get value of dropdownlist in java script code:
var statePickerDropDownList = document.getElementById('<%=statePicker.ClientID%>'); var state = statePickerDropDownList.options[statePickerDropDownList.selectedIndex].value;
pass field value in Grdview to java script http://forums.asp.net/t/1099098.aspx <asp:TemplateField> <ItemTemplate> <asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl=<%# String.Format("javascript:void(window.open('http://www.{0}.com'))", Eval("ProductID")) %>> HyperLink</asp:HyperLink> </ItemTemplate> </asp:TemplateField>
Thank you for signing up for a Google Maps API key! Your key is: ABQIAAAADZOzmiiLzElWWoxN2P0pkBTcZS7Uqt_rAOCulJ-gP9vRrY3NIxTTATiB-tV0huJd34SsU0poHxkbFw
This key is good for all URLs in this directory: http://lulu.gotdns.org/
Here is an example web page to get you started on your way to mapping glory:
Check out the API documentation for more information.
Implementing the Singleton Pattern in C#http://www.yoda.arachsys.com/csharp/singleton.html Five implementations are given. The author also compared their pros and cons. Bestone is: public sealed class Singleton { Singleton() { }
public static Singleton Instance { get { return Nested.instance; } } class Nested { static Nested() { }
internal static readonly Singleton instance = new Singleton(); } }
I don't know how much Google pays out for the top Ad Wordsbut I have compiled my own top-paying keyword word list by using the free, public Overture Bid Tool, which is now gone. However, you can now check your words using the Free Google AdWords . Incorporating high paying keywords into your site is critical to maximizing your income. Who has the time to figure it all out? How much are you willing to pay for this type of information? The secret is out: Here are 99 keywords you can use with payouts averaging $2-$100 per click: 1. Structured settlements 2. Mesothelioma 3. Acne 4. Life Insurance 5. Death Insurance 6. Bextra 7. Asbestos 8. Car Insurance 9. Dental Plans 10. Private Jets 11. Debt Consolidation 12. Credit Cards 13. Rewards Cards 14. Equity Loans 15. Equity Line Credit 16. Loans 17. Mortgages 18. Pay Day Loans 19. Cash Advance 20. Bankruptcy 21. Reduce Debt 22. Refinance 23. Jet Charter 24. Vioxx 25. Wrongful death 26. Legal Advice 27. Taxes 28. Investing 29. Bonds 30. Online Trading 31. IRA Rollover 32. Refinance Quotes 33. Adult Education 34. Distance Learning 35. Alcohol Treatment 36. Rehab 37. Drug Rehab 38. Spyware 39. Cell Phone Plans 40. Calling Cards 41. VOIP 42. Weight Loss 43. Canadian Pharmacy 44. Depression 45. Spam Filter 46. Lasik 47. Facelift 48. Teeth Whitening 49. Annuity 50. Anti Virus Protection 51. Adult Diaper 52. Free Credit Report 53. Credit Score 54. Satellite 55. Anti Spam Software 56. Dedicated Hosting 57. Domain Name 58. Need Money 59. Bachelor Degree 60. Master Degree 61. Doctorate Degree 62. Work at Home 63. Quick Book 64. Extra Money 65. Eloan 66. Malpractice Lawyer 67. Lenox China 68. Cancer 69. Payperclick 70. Personal Injury Attorney 71. Lexington Law 72. Video Conferencing 73. Transfer Money 74. Windstar Cruise 75. Casinos Online 76. Term Life 77. Online Banking 78. Borrow Money 79. Low Interest Credit Cards 80. Personal Domain Name 81. Cellular Phone Rental 82. Internet Broker 83. Trans Union 84. Cheap Hosting 85. University Degrees Online 86. Online Marketing 87. Consolidate 88. Helpdesk Software 89. Web Host 90. Homeowner's Insurance 91. Yellow Page Advertising 92. Travel Insurance 93. Register Domain 94. Credit Counseling 95. Email Hosting 96. Business Credit 97. Consumer Credit 98. Blue Cross 99. Laptop Computer Actual payouts vary depending on whose PPC program you belong to and on the amount that has been bid per click by advertisers. Still, the savvy web administrator will take good care to incorporate some of these key words and reap results higher than they ever expected.
You probably want to watch TV and movies more often. Turn the caption on, follow the characters to read those dialogs. If you keep doing this, although at the very beginning you may not be able to follow them, those sentences could become yours eventually when you talk to people. And pay more attention to the sentences used by people or in books. Remember them and try to use them in your daily life. This is what I did when I first came here. I rented DVDs, watched TV shows. I could not say I am the one who can speak English as a native speaker. This is a life-long goal to achieve. But I am confident and feel comfortable to speak English.
From : http://www.cnblogs.com/reonlyrun/archive/2007/04/05/CSharp_25_Question.html C#基础概念二十五问 注:本文部份资料来自网络,如有侵权,请与我联系,我会在第一时间声明引用或将其删除! 当初学 C# 时是找个人大概问了一下数据类型和分支语句就开始做项目了。这两天又全面的看了一下相关的基础知识(学而时习之嘛),总结了25个问题: 1.静态成员和非静态成员的区别? 2.const 和 static readonly 区别? 3.extern 是什么意思? 4.abstract 是什么意思? 5.internal 修饰符起什么作用? 6.sealed 修饰符是干什么的? 7.override 和 overload 的区别? 8.什么是索引指示器? 9.new 修饰符是起什么作用? 10.this 关键字的含义? 11.可以使用抽象函数重写基类中的虚函数吗? 12.密封类可以有虚函数吗? 13.什么是属性访问器? 14.abstract 可以和 virtual 一起使用吗?可以和 override 一起使用吗? 15.接口可以包含哪些成员? 16.类和结构的区别? 17.接口的多继承会带来哪些问题? 18.抽象类和接口的区别? 19.别名指示符是什么? 20.如何手工释放资源? 21.P/Invoke是什么? 22.StringBuilder 和 String 的区别? 23.explicit 和 implicit 的含义? 24.params 有什么用? 25.什么是反射? 以下是我做的一份参考答案(C# 语言范畴之内),如果有不准确、不全面的,欢迎各位朋友指正! 1.静态成员和非静态成员的区别? 答: 静态变量使用 static 修饰符进行声明,在类被实例化时创建,通过类进行访问 不带有 static 修饰符声明的变量称做非静态变量,在对象被实例化时创建,通过对象进行访问 一个类的所有实例的同一静态变量都是同一个值,同一个类的不同实例的同一非静态变量可以是不同的值 静态函数的实现里不能使用非静态成员,如非静态变量、非静态函数等 示例: using System; using System.Collections.Generic; using System.Text; namespace Example01 { class Program { class Class1 { public static String staticStr = "Class"; public String notstaticStr = "Obj"; } static void Main(string[] args) { //静态变量通过类进行访问,该类所有实例的同一静态变量都是同一个值 Console.WriteLine("Class1's staticStr: {0}", Class1.staticStr); Class1 tmpObj1 = new Class1(); tmpObj1.notstaticStr = "tmpObj1"; Class1 tmpObj2 = new Class1(); tmpObj2.notstaticStr = "tmpObj2"; //非静态变量通过对象进行访问,不同对象的同一非静态变量可以有不同的值 Console.WriteLine("tmpObj1's notstaticStr: {0}", tmpObj1.notstaticStr); Console.WriteLine("tmpObj2's notstaticStr: {0}", tmpObj2.notstaticStr); Console.ReadLine(); } } }
结果: Class1's staticStr: Class tmpObj1's notstaticStr: tmpObj1 tmpObj2's notstaticStr: tmpObj2
2.const 和 static readonly 区别?
答:
const
用 const 修饰符声明的成员叫常量,是在编译期初始化并嵌入到客户端程序
static readonly
用 static readonly 修饰符声明的成员依然是变量,只不过具有和常量类似的使用方法:通过类进行访问、初始化后不可以修改。但与常量不同的是这种变量是在运行期初始化
示例:
测试类: using System; using System.Collections.Generic; using System.Text; namespace Example02Lib { public class Class1 { public const String strConst = "Const"; public static readonly String strStaticReadonly = "StaticReadonly"; //public const String strConst = "Const Changed"; //public static readonly String strStaticReadonly = "StaticReadonly Changed"; } } 客户端代码: using System; using System.Collections.Generic; using System.Text; using Example02Lib; namespace Example02 { class Program { static void Main(string[] args) { //修改Example02中Class1的strConst初始值后,只编译Example02Lib项目 //然后到资源管理器里把新编译的Example02Lib.dll拷贝Example02.exe所在的目录,执行Example02.exe //切不可在IDE里直接调试运行因为这会重新编译整个解决方案!! //可以看到strConst的输出没有改变,而strStaticReadonly的输出已经改变 //表明Const变量是在编译期初始化并嵌入到客户端程序,而StaticReadonly是在运行时初始化的 Console.WriteLine("strConst : {0}", Class1.strConst); Console.WriteLine("strStaticReadonly : {0}", Class1.strStaticReadonly); Console.ReadLine(); } } }
结果: strConst : Const strStaticReadonly : StaticReadonly
修改后的示例:
测试类: using System; using System.Collections.Generic; using System.Text; namespace Example02Lib { public class Class1 { //public const String strConst = "Const"; //public static readonly String strStaticReadonly = "StaticReadonly"; public const String strConst = "Const Changed"; public static readonly String strStaticReadonly = "StaticReadonly Changed"; } }
结果
strConst : Const strStaticReadonly : StaticReadonly Changed
3.extern 是什么意思?
答:
extern 修饰符用于声明由程序集外部实现的成员函数
经常用于系统API函数的调用(通过 DllImport )。注意,和DllImport一起使用时要加上 static 修饰符
也可以用于对于同一程序集不同版本组件的调用(用 extern 声明别名)
不能与 abstract 修饰符同时使用
示例: using System; using System.Collections.Generic; using System.Text; using System.Runtime.InteropServices; namespace Example03 { class Program { //注意DllImport是一个Attribute Property,在System.Runtime.InteropServices命名空间中定义 //extern与DllImport一起使用时必须再加上一个static修饰符 [DllImport("User32.dll")] public static extern int MessageBox(int Handle, string Message, string Caption, int Type); static int Main() { string myString; Console.Write("Enter your message: "); myString = Console.ReadLine(); return MessageBox(0, myString, "My Message Box", 0); } } }
结果:
4.abstract 是什么意思?
答:
abstract 修饰符可以用于类、方法、属性、事件和索引指示器(indexer),表示其为抽象成员
abstract 不可以和 static 、virtual 一起使用
声明为 abstract 成员可以不包括实现代码,但只要类中还有未实现的抽象成员(即抽象类),那么它的对象就不能被实例化,通常用于强制继承类必须实现某一成员
示例: using System; using System.Collections.Generic; using System.Text; namespace Example04 { #region 基类,抽象类 public abstract class BaseClass { //抽象属性,同时具有get和set访问器表示继承类必须将该属性实现为可读写 public abstract String Attribute { get; set; } //抽象方法,传入一个字符串参数无返回值 public abstract void Function(String value); //抽象事件,类型为系统预定义的代理(delegate):EventHandler public abstract event EventHandler Event; //抽象索引指示器,只具有get访问器表示继承类必须将该索引指示器实现为只读 public abstract Char this[int Index] { get; } } #endregion #region 继承类 public class DeriveClass : BaseClass { private String attribute; public override String Attribute { get { return attribute; } set { attribute = value; } } public override void Function(String value) { attribute = value; if (Event != null) { Event(this, new EventArgs()); } } public override event EventHandler Event; public override Char this[int Index] { get { return attribute[Index]; } } } #endregion class Program { static void OnFunction(object sender, EventArgs e) { for (int i = 0; i < ((DeriveClass)sender).Attribute.Length; i++) { Console.WriteLine(((DeriveClass)sender)[i]); } } static void Main(string[] args) { DeriveClass tmpObj = new DeriveClass(); tmpObj.Attribute = "1234567"; Console.WriteLine(tmpObj.Attribute); //将静态函数OnFunction与tmpObj对象的Event事件进行关联 tmpObj.Event += new EventHandler(OnFunction); tmpObj.Function("7654321"); Console.ReadLine(); } } }
结果: 1234567 7 6 5 4 3 2 1
5.internal 修饰符起什么作用?
答:
internal 修饰符可以用于类型或成员,使用该修饰符声明的类型或成员只能在同一程集内访问
接口的成员不能使用 internal 修饰符
值得注意的是,如果为 internal 成员加上了 protected 修饰符,这时的访问级别为 internal 或 protected。只是看字面意思容易弄错,许多人认为 internal protected 应该是“只有同一个程序集中的子类可以访问”,但其实它表示“同一个程序集中的所有类,以及所有程序集中的子类都可以访问”
示例
Example05Lib 项目的 Class1 using System; using System.Collections.Generic; using System.Text; namespace Example05Lib { public class Class1 { internal String strInternal = null; public String strPublic; internal protected String strInternalProtected = null; } }
结果 Example05Lib 项目的 Class2 类可以访问到 Class1 的 strInternal 成员,当然也可以访问到 strInternalProtected 成员,因为他们在同一个程序集里
Example05 项目里的 Class3 类无法访问到 Class1 的 strInternal 成员,因为它们不在同一个程序集里。但却可以访问到 strInternalProtected 成员,因为 Class3 是 Class1 的继承类
Example05 项目的 Program 类既无法访问到 Class1 的 strInternal 成员,也无法访问到 strInternalProtected 成员,因为它们既不在同一个程序集里也不存在继承关系
6.sealed 修饰符是干什么的?
答:
sealed 修饰符表示密封
用于类时,表示该类不能再被继承,不能和 abstract 同时使用,因为这两个修饰符在含义上互相排斥
用于方法和属性时,表示该方法或属性不能再被继承,必须和 override 关键字一起使用,因为使用 sealed 修饰符的方法或属性肯定是基类中相应的虚成员
通常用于实现第三方类库时不想被客户端继承,或用于没有必要再继承的类以防止滥用继承造成层次结构体系混乱
恰当的利用 sealed 修饰符也可以提高一定的运行效率,因为不用考虑继承类会重写该成员
示例: using System; using System.Collections.Generic; using System.Text; namespace Example06 { class Program { class A { public virtual void F() { Console.WriteLine("A.F"); } public virtual void G() { Console.WriteLine("A.G"); } } class B : A { public sealed override void F() { Console.WriteLine("B.F"); } public override void G() { Console.WriteLine("B.G"); } } class C : B { public override void G() { Console.WriteLine("C.G"); } } static void Main(string[] args) { new A().F(); new A().G(); new B().F(); new B().G(); new C().F(); new C().G(); Console.ReadLine(); } } }
结果: 类 B 在继承类 A 时可以重写两个虚函数,如图所示:
由于类 B 中对 F 方法进行了密封, 类 C 在继承类 B 时只能重写一个函数,如图所示:
控制台输出结果,类 C 的方法 F 只能是输出 类B 中对该方法的实现:
A.F A.G B.F B.G B.F C.G
7.override 和 overload 的区别?
答:
override 表示重写,用于继承类对基类中虚成员的实现
overload 表示重载,用于同一个类中同名方法不同参数(包括类型不同或个数不同)的实现
示例: using System; using System.Collections.Generic; using System.Text; namespace Example07 { class Program { class BaseClass { public virtual void F() { Console.WriteLine("BaseClass.F"); } } class DeriveClass : BaseClass { public override void F() { base.F(); Console.WriteLine("DeriveClass.F"); } public void Add(int Left, int Right) { Console.WriteLine("Add for Int: {0}", Left + Right); } public void Add(double Left, double Right) { Console.WriteLine("Add for int: {0}", Left + Right); } } static void Main(string[] args) { DeriveClass tmpObj = new DeriveClass(); tmpObj.F(); tmpObj.Add(1, 2); tmpObj.Add(1.1, 2.2); Console.ReadLine(); } } }
结果: BaseClass.F DeriveClass.F Add for Int: 3 Add for int: 3.3
8.什么是索引指示器?
答:
实现索引指示器(indexer)的类可以象数组那样使用其实例后的对象,但与数组不同的是索引指示器的参数类型不仅限于int
简单来说,其本质就是一个含参数属性
示例: using System; using System.Collections.Generic; using System.Text; namespace Example08 { public class Point { private double x, y; public Point(double X, double Y) { x = X; y = Y; } //重写ToString方法方便输出 public override string ToString() { return String.Format("X: {0} , Y: {1}", x, y); } } public class Points { Point[] points; public Points(Point[] Points) { points = Points; } public int PointNumber { get { return points.Length; } } //实现索引访问器 public Point this[int Index] { get { return points[Index]; } } } //感谢watson hua(http://huazhihao.cnblogs.com/)的指点 //索引指示器的实质是含参属性,参数并不只限于int class WeatherOfWeek { public string this[int Index] { get { //注意case段使用return直接返回所以不需要break switch (Index) { case 0: { return "Today is cloudy!"; } case 5: { return "Today is thundershower!"; } default: { return "Today is fine!"; } } } } public string this[string Day] { get { string TodayWeather = null; //switch的标准写法 switch (Day) { case "Sunday": { TodayWeather = "Today is cloudy!"; break; } case "Friday": { TodayWeather = "Today is thundershower!"; break; } default: { TodayWeather = "Today is fine!"; break; } } return TodayWeather; } } } class Program { static void Main(string[] args) { Point[] tmpPoints = new Point[10]; for (int i = 0; i < tmpPoints.Length; i++) { tmpPoints[i] = new Point(i, Math.Sin(i)); } Points tmpObj = new Points(tmpPoints); for (int i = 0; i < tmpObj.PointNumber; i++) { Console.WriteLine(tmpObj[i]); } string[] Week = new string[] { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Staurday"}; WeatherOfWeek tmpWeatherOfWeek = new WeatherOfWeek(); for (int i = 0; i < 6; i++) { Console.WriteLine(tmpWeatherOfWeek[i]); } foreach (string tmpDay in Week) { Console.WriteLine(tmpWeatherOfWeek[tmpDay]); } Console.ReadLine(); } } }
结果: X: 0 , Y: 0 X: 1 , Y: 0.841470984807897 X: 2 , Y: 0.909297426825682 X: 3 , Y: 0.141120008059867 X: 4 , Y: -0.756802495307928 X: 5 , Y: -0.958924274663138 X: 6 , Y: -0.279415498198926 X: 7 , Y: 0.656986598718789 X: 8 , Y: 0.989358246623382 X: 9 , Y: 0.412118485241757 Today is cloudy! Today is fine! Today is fine! Today is fine! Today is fine! Today is thundershower! Today is cloudy! Today is fine! Today is fine! Today is fine! Today is fine! Today is thundershower! Today is fine!
9.new 修饰符是起什么作用?
答:
new 修饰符与 new 操作符是两个概念
new 修饰符用于声明类或类的成员,表示隐藏了基类中同名的成员。而new 操作符用于实例化一个类型
new 修饰符只能用于继承类,一般用于弥补基类设计的不足
new 修饰符和 override 修饰符不可同时用在一个成员上,因为这两个修饰符在含义上互相排斥
示例: using System; using System.Collections.Generic; using System.Text; namespace Example09 { class BaseClass { //基类设计者声明了一个PI的公共变量,方便进行运算 public static double PI = 3.1415; } class DervieClass : BaseClass { //继承类发现该变量的值不能满足运算精度,于是可以通过new修饰符显式隐藏基类中的声明 public new static double PI = 3.1415926; } class Program { static void Main(string[] args) { Console.WriteLine(BaseClass.PI); Console.WriteLine(DervieClass.PI); Console.ReadLine(); } } }
结果: 3.1415 3.1415926
10.this 关键字的含义?
答:
this 是一个保留字,仅限于构造函数和方法成员中使用
在类的构造函数中出现表示对正在构造的对象本身的引用,在类的方法中出现表示对调用该方法的对象的引用,在结构的构造上函数中出现表示对正在构造的结构的引用,在结构的方法中出现表示对调用该方法的结果的引用
this 保留字不能用于静态成员的实现里,因为这时对象或结构并未实例化
在 C# 系统中,this 实际上是一个常量,所以不能使用 this++ 这样的运算
this 保留字一般用于限定同名的隐藏成员、将对象本身做为参数、声明索引访问器、判断传入参数的对象是否为本身
示例: using System; using System.Collections.Generic; using System.Text; namespace Example10 { class Class1 { private double c; private string value; public double C { get { return c; } } public Class1(double c) { //限定同名的隐藏成员 this.c = c; } public Class1(Class1 value) { //用对象本身实例化自己没有意义 if (this != value) { c = value.C; } } public override string ToString() { //将对象本身做为参数 return string.Format("{0} Celsius = {1} Fahrenheit", c, UnitTransClass.C2F(this)); } //由于好奇,在这做了一个效率测试,想看看到底哪种方式访问成员变量更快,结论:区别不大。。。 public string Test1() { long vTickCount = Environment.TickCount; for (int i = 0; i < 10000000; i++) this.value = i.ToString(); return string.Format("Have this.: {0} MSEL", Environment.TickCount - vTickCount); } public string Test2() { long vTickCount = Environment.TickCount; for (int i = 0; i < 10000000; i++) value = i.ToString(); return string.Format("Don't have this.: {0} MSEL", Environment.TickCount - vTickCount); } } class UnitTransClass { public static double C2F(Class1 value) { //摄氏到华氏的转换公式 return 1.8 * value.C + 32; } } class Program { static void Main(string[] args) { Class1 tmpObj = new Class1(37.5); Console.WriteLine(tmpObj); Console.WriteLine(tmpObj.Test1()); Console.WriteLine(tmpObj.Test2()); Console.ReadLine(); } } }
结果: 37.5 Celsius = 99.5 Fahrenheit Have this.: 4375 MSEL Don't have this.: 4406 MSEL
11.可以使用抽象函数重写基类中的虚函数吗?
答:
可以
需使用 new 修饰符显式声明,表示隐藏了基类中该函数的实现
或增加 override 修饰符,表示抽象重写了基类中该函数的实现
示例: class BaseClass { public virtual void F() { Console.WriteLine("BaseClass.F"); } } abstract class DeriveClass1 : BaseClass { public abstract new void F(); } //感谢watson hua(http://huazhihao.cnblogs.com/)的指点 //是他提醒了我还可以用这种方法抽象重写基类的虚方法 abstract class DeriveClass2 : BaseClass { public abstract override void F(); }
12.密封类可以有虚函数吗?
答:
可以,基类中的虚函数将隐式的转化为非虚函数,但密封类本身不能再增加新的虚函数
示例: class BaseClass { public virtual void F() { Console.WriteLine("BaseClass.F"); } } sealed class DeriveClass : BaseClass { //基类中的虚函数F被隐式的转化为非虚函数 //密封类中不能再声明新的虚函数G //public virtual void G() //{ // Console.WriteLine("DeriveClass.G"); //} }
13.什么是属性访问器?
答:
属性访问器(Property Accessor),包括 get 访问器和 set 访问器分别用于字段的读写操作
其设计目的主要是为了实现面向对象(OO)中的封装思想。根据该思想,字段最好设为private,一个精巧的类最好不要直接把字段设为公有提供给客户调用端直接访问
另外要注意属性本身并不一定和字段相联系
14.abstract 可以和 virtual 一起使用吗?可以和 override 一起使用吗?
答:
abstract 修饰符不可以和 static、virtual 修饰符一起使用
abstract 修饰符可以和 override 一起使用,参见第11点
示例: using System; using System.Collections.Generic; using System.Text; namespace Example14 { class BaseClass { public virtual void F() { Console.WriteLine("BaseClass.F"); } } abstract class DeriveClass1 : BaseClass { //在这里, abstract是可以和override一起使用的 public abstract override void F(); } class Program { static void Main(string[] args) { } } }
15.接口可以包含哪些成员?
答:
接口可以包含属性、方法、索引指示器和事件,但不能包含常量、域、操作符、构造函数和析构函数,而且也不能包含任何静态成员
16.类和结构的区别?
答: 类:
类是引用类型在堆上分配,类的实例进行赋值只是复制了引用,都指向同一段实际对象分配的内存
类有构造和析构函数
类可以继承和被继承
结构:
结构是值类型在栈上分配(虽然栈的访问速度比较堆要快,但栈的资源有限放),结构的赋值将分配产生一个新的对象。
结构没有构造函数,但可以添加。结构没有析构函数
结构不可以继承自另一个结构或被继承,但和类一样可以继承自接口
示例:
根据以上比较,我们可以得出一些轻量级的对象最好使用结构,但数据量大或有复杂处理逻辑对象最好使用类。
如:Geoemtry(GIS 里的一个概论,在 OGC 标准里有定义) 最好使用类,而 Geometry 中点的成员最好使用结构 using System; using System.Collections.Generic; using System.Text; namespace Example16 { interface IPoint { double X { get; set; } double Y { get; set; } double Z { get; set; } } //结构也可以从接口继承 struct Point: IPoint { private double x, y, z; //结构也可以增加构造函数 public Point(double X, double Y, double Z) { this.x = X; this.y = Y; this.z = Z; } public double X { get { return x; } set { x = value; } } public double Y { get { return x; } set { x = value; } } public double Z { get { return x; } set { x = value; } } } //在此简化了点状Geometry的设计,实际产品中还包含Project(坐标变换)等复杂操作 class PointGeometry { private Point value; public PointGeometry(double X, double Y, double Z) { value = new Point(X, Y, Z); } public PointGeometry(Point value) { //结构的赋值将分配新的内存 this.value = value; } public double X { get { return value.X; } set { this.value.X = value; } } public double Y { get { return value.Y; } set { this.value.Y = value; } } public double Z { get { return value.Z; } set { this.value.Z = value; } } public static PointGeometry operator +(PointGeometry Left, PointGeometry Rigth) { return new PointGeometry(Left.X + Rigth.X, Left.Y + Rigth.Y, Left.Z + Rigth.Z); } public override string ToString() { return string.Format("X: {0}, Y: {1}, Z: {2}", value.X, value.Y, value.Z); } } class Program { static void Main(string[] args) { Point tmpPoint = new Point(1, 2, 3); PointGeometry tmpPG1 = new PointGeometry(tmpPoint); PointGeometry tmpPG2 = new PointGeometry(tmpPoint); tmpPG2.X = 4; tmpPG2.Y = 5; tmpPG2.Z = 6; //由于结构是值类型,tmpPG1 和 tmpPG2 的坐标并不一样 Console.WriteLine(tmpPG1); Console.WriteLine(tmpPG2); //由于类是引用类型,对tmpPG1坐标修改后影响到了tmpPG3 PointGeometry tmpPG3 = tmpPG1; tmpPG1.X = 7; tmpPG1.Y = 8; tmpPG1.Z = 9; Console.WriteLine(tmpPG1); Console.WriteLine(tmpPG3); Console.ReadLine(); } } }
结果: X: 1, Y: 2, Z: 3 X: 4, Y: 5, Z: 6 X: 7, Y: 8, Z: 9 X: 7, Y: 8, Z: 9
17.接口的多继承会带来哪些问题?
答:
C# 中的接口与类不同,可以使用多继承,即一个子接口可以有多个父接口。但如果两个父成员具有同名的成员,就产生了二义性(这也正是 C# 中类取消了多继承的原因之一),这时在实现时最好使用显式的声明
示例: using System; using System.Collections.Generic; using System.Text; namespace Example17 { class Program { //一个完整的接口声明示例 interface IExample { //属性 string P { get; set; } //方法 string F(int Value); //事件 event EventHandler E; //索引指示器 string this[int Index] { get; set; } } interface IA { int Count { get; set;} } interface IB { int Count(); } //IC接口从IA和IB多重继承 interface IC : IA, IB { } class C : IC { private int count = 100; //显式声明实现IA接口中的Count属性 int IA.Count { get { return 100; } set { count = value; } } //显式声明实现IB接口中的Count方法 int IB.Count() { return count * count; } } static void Main(string[] args) { C tmpObj = new C(); //调用时也要显式转换 Console.WriteLine("Count property: {0}", ((IA)tmpObj).Count); Console.WriteLine("Count function: {0}", ((IB)tmpObj).Count()); Console.ReadLine(); } } }
结果: Count property: 100 Count function: 10000
18.抽象类和接口的区别?
答:
抽象类(abstract class)可以包含功能定义和实现,接口(interface)只能包含功能定义
抽象类是从一系列相关对象中抽象出来的概念, 因此反映的是事物的内部共性;接口是为了满足外部调用而定义的一个功能约定, 因此反映的是事物的外部特性
分析对象,提炼内部共性形成抽象类,用以表示对象本质,即“是什么”
为外部提供调用或功能需要扩充时优先使用接口
19.别名指示符是什么?
答:
通过别名指示符我们可以为某个类型起一个别名
主要用于解决两个命名空间内有同名类型的冲突或避免使用冗余的命名空间
别名指示符在所有命名空间最外层定义,作用域为整个单元文件。如果定义在某个命名空间内,那么它只在直接隶属的命名空间内起作用
示例:
Class1.cs: using System; using System.Collections.Generic; using System.Text; namespace com.nblogs.reonlyrun.CSharp25QExample.Example19.Lib01 { class Class1 { public override string ToString() { return "com.nblogs.reonlyrun.CSharp25QExample.Example19.Lib01's Class1"; } } }
Class2.cs: using System; using System.Collections.Generic; using System.Text; namespace com.nblogs.reonlyrun.CSharp25QExample.Example19.Lib02 { class Class1 { public override string ToString() { return "com.nblogs.reonlyrun.CSharp25QExample.Example19.Lib02's Class1"; } } }
主单元(Program.cs): using System; using System.Collections.Generic; using System.Text; //使用别名指示符解决同名类型的冲突 //在所有命名空间最外层定义,作用域为整个单元文件 using Lib01Class1 = com.nblogs.reonlyrun.CSharp25QExample.Example19.Lib01.Class1; using Lib02Class2 = com.nblogs.reonlyrun.CSharp25QExample.Example19.Lib02.Class1; namespace Example19 { namespace Test1 { //Test1Class1在Test1命名空间内定义,作用域仅在Test1之内 using Test1Class1 = com.nblogs.reonlyrun.CSharp25QExample.Example19.Lib01.Class1; class Class1 { //Lib01Class1和Lib02Class2在这可以正常使用 Lib01Class1 tmpObj1 = new Lib01Class1(); Lib02Class2 tmpObj2 = new Lib02Class2(); //TestClass1在这可以正常使用 Test1Class1 tmpObj3 = new Test1Class1(); } } namespace Test2 { using Test1Class2 = com.nblogs.reonlyrun.CSharp25QExample.Example19.Lib01.Class1; class Program { static void Main(string[] args) { //Lib01Class1和Lib02Class2在这可以正常使用 Lib01Class1 tmpObj1 = new Lib01Class1(); Lib02Class2 tmpObj2 = new Lib02Class2(); //注意这里,TestClass1在这不可以正常使用。 //因为,在Test2命名空间内不能使用Test1命名空间定义的别名 //Test1Class1 tmpObj3 = new Test1Class1(); //TestClass2在这可以正常使用 Test1Class2 tmpObj3 = new Test1Class2(); Console.WriteLine(tmpObj1); Console.WriteLine(tmpObj2); Console.WriteLine(tmpObj3); Console.ReadLine(); } } } }
结果: com.nblogs.reonlyrun.CSharp25QExample.Example19.Lib01's Class1 com.nblogs.reonlyrun.CSharp25QExample.Example19.Lib02's Class1 com.nblogs.reonlyrun.CSharp25QExample.Example19.Lib01's Class1
20.如何手工释放资源?
答:
.NET 平台在内存管理方面提供了GC(Garbage Collection),负责自动释放托管资源和内存回收的工作。但在以下两种情况需要我们手工进行资源释放:一、由于它无法对非托管资源进行释放,所以我们必须自己提供方法来释放对象内分配的非托管资源,比如你在对象的实现代码中使用了一个COM对象;二、你的类在运行是会产生大量实例(象 GIS 中的Geometry),必须自己手工释放这些资源以提高程序的运行效率
最理想的办法是通过实现一个接口显式的提供给客户调用端手工释放对象,System 命名空间内有一个 IDisposable 接口,拿来做这事非常合适,省得我们自己再声明一个接口了
示例: using System; using System.Collections.Generic; using System.Text; namespace Example20 { class Program { class Class1 : IDisposable { //析构函数,编译后变成 protected void Finalize(),GC会在回收对象前会调用调用该方法 ~Class1() { Dispose(false); } //通过实现该接口,客户可以显式地释放对象,而不需要等待GC来释放资源,据说那样会降低效率 void IDisposable.Dispose() { Dispose(true); } //将释放非托管资源设计成一个虚函数,提供在继承类中释放基类的资源的能力 protected virtual void ReleaseUnmanageResources() { //Do something... } //私有函数用以释放非托管资源 private void Dispose(bool disposing) { ReleaseUnmanageResources(); //为true时表示是客户显式调用了释放函数,需通知GC不要再调用对象的Finalize方法 //为false时肯定是GC调用了对象的Finalize方法,所以没有必要再告诉GC你不要调用我的Finalize方法啦 if (disposing) { GC.SuppressFinalize(this); } } } static void Main(string[] args) { //tmpObj1没有手工释放资源,就等着GC来慢慢的释放它吧 Class1 tmpObj1 = new Class1(); //tmpObj2调用了Dispose方法,传说比等着GC来释放它效率要调一些 //个人认为是因为要逐个对象的查看其元数据,以确认是否实现了Dispose方法吧 //当然最重要的是我们可以自己确定释放的时间以节省内存,优化程序运行效率 Class1 tmpObj2 = new Class1(); ((IDisposable)tmpObj2).Dispose(); } } }
21.P/Invoke是什么?
答:
在受控代码与非受控代码进行交互时会产生一个事务(transition) ,这通常发生在使用平台调用服务(Platform Invocation Services),即P/Invoke
如调用系统的 API 或与 COM 对象打交道,通过 System.Runtime.InteropServices 命名空间
虽然使用 Interop 非常方便,但据估计每次调用事务都要执行 10 到 40 条指令,算起来开销也不少,所以我们要尽量少调用事务
如果非用不可,建议本着一次调用执行多个动作,而不是多次调用每次只执行少量动作的原则
22.StringBuilder 和 String 的区别?
答:
String 在进行运算时(如赋值、拼接等)会产生一个新的实例,而 StringBuilder 则不会。所以在大量字符串拼接或频繁对某一字符串进行操作时最好使用 StringBuilder,不要使用 String
另外,对于 String 我们不得不多说几句:
1.它是引用类型,在堆上分配内存
2.运算时会产生一个新的实例
3.String 对象一旦生成不可改变(Immutable)
3.定义相等运算符(== 和 !=)是为了比较 String 对象(而不是引用)的值
示例: using System; using System.Collections.Generic; using System.Text; namespace Example22 { class Program { static void Main(string[] args) { const int cycle = 10000; long vTickCount = Environment.TickCount; String str = null; for (int i = 0; i < cycle; i++) str += i.ToString(); Console.WriteLine("String: {0} MSEL", Environment.TickCount - vTickCount); vTickCount = Environment.TickCount; //看到这个变量名我就生气,奇怪为什么大家都使它呢? :) StringBuilder sb = new StringBuilder(); for (int i = 0; i < cycle; i++) sb.Append(i); Console.WriteLine("StringBuilder: {0} MSEL", Environment.TickCount - vTickCount); string tmpStr1 = "A"; string tmpStr2 = tmpStr1; Console.WriteLine(tmpStr1); Console.WriteLine(tmpStr2); //注意后面的输出结果,tmpStr1的值改变并未影响到tmpStr2的值 tmpStr1 = "B"; Console.WriteLine(tmpStr1); Console.WriteLine(tmpStr2); Console.ReadLine(); } } }
结果: String: 375 MSEL StringBuilder: 16 MSEL A A B A
23.explicit 和 implicit 的含义?
答:
explicit 和 implicit 属于转换运算符,如用这两者可以让我们自定义的类型支持相互交换
explicti 表示显式转换,如从 A -> B 必须进行强制类型转换(B = (B)A)
implicit 表示隐式转换,如从 B -> A 只需直接赋值(A = B)
隐式转换可以让我们的代码看上去更漂亮、更简洁易懂,所以最好多使用 implicit 运算符。不过!如果对象本身在转换时会损失一些信息(如精度),那么我们只能使用 explicit 运算符,以便在编译期就能警告客户调用端
示例: using System; using System.Collections.Generic; using System.Text; namespace Example23 { class Program { //本例灵感来源于大话西游经典台词“神仙?妖怪?”--主要是我实在想不出什么好例子了 class Immortal { public string name; public Immortal(string Name) { name = Name; } public static implicit operator Monster(Immortal value) { return new Monster(value.name + ":神仙变妖怪?偷偷下凡即可。。。"); } } class Monster { public string name; public Monster(string Name) { name = Name; } public static explicit operator Immortal(Monster value) { return new Immortal(value.name + ":妖怪想当神仙?再去修炼五百年!"); } } static void Main(string[] args) { Immortal tmpImmortal = new Immortal("紫霞仙子"); //隐式转换 Monster tmpObj1 = tmpImmortal; Console.WriteLine(tmpObj1.name); Monster tmpMonster = new Monster("孙悟空"); //显式转换 Immortal tmpObj2 = (Immortal)tmpMonster; Console.WriteLine(tmpObj2.name); Console.ReadLine(); } } }
结果: 紫霞仙子:神仙变妖怪?偷偷下凡即可。。。 孙悟空:妖怪想当神仙?再去修炼五百年!
24.params 有什么用?
答:
params 关键字在方法成员的参数列表中使用,为该方法提供了参数个数可变的能力
它在只能出现一次并且不能在其后再有参数定义,之前可以
示例: using System; using System.Collections.Generic; using System.Text; namespace ConsoleApplication1 { class App { //第一个参数必须是整型,但后面的参数个数是可变的。 //而且由于定的是object数组,所有的数据类型都可以做为参数传入 public static void UseParams(int id, params object[] list) { Console.WriteLine(id); for (int i = 0; i < list.Length; i++) { Console.WriteLine(list[i]); } } static void Main() { //可变参数部分传入了三个参数,都是字符串类型 UseParams(1, "a", "b", "c"); //可变参数部分传入了四个参数,分别为字符串、整数、浮点数和双精度浮点数数组 UseParams(2, "d", 100, 33.33, new double[] { 1.1, 2.2 }); Console.ReadLine(); } } }
结果: 1 a b c 2 d 100 33.33 System.Double[]
25.什么是反射?
答:
反射,Reflection,通过它我们可以在运行时获得各种信息,如程序集、模块、类型、字段、属性、方法和事件
通过对类型动态实例化后,还可以对其执行操作
简单来说就是用string可以在runtime为所欲为的东西,实际上就是一个.net framework内建的万能工厂
一般用于插件式框架程序和设计模式的实现,当然反射是一种手段可以充分发挥其能量来完成你想做的任何事情(前面好象见过一位高人用反射调用一个官方类库中未说明的函数。。。)
示例: using System; using System.Collections.Generic; using System.Text; namespace Example25Lib { public class Class1 { private string name; private int age; //如果显式的声明了无参数构造函数,客户端只需要用程序集的CreateInstance即可实例化该类 //在此特意不实现,以便在客户调用端体现构造函数的反射实现 //public Class1() //{ //} public Class1(string Name, int Age) { name = Name; age = Age; } public void ChangeName(string NewName) { name = NewName; } public void ChangeAge(int NewAge) { age = NewAge; } public override string ToString() { return string.Format("Name: {0}, Age: {1}", name, age); } } }
反射实例化对象并调用其方法,属性和事件的反射调用略去 using System; using System.Collections.Generic; using System.Text; //注意添加该反射的命名空间 using System.Reflection; namespace Example25 { class Program { static void Main(string[] args) { //加载程序集 Assembly tmpAss = Assembly.LoadFile(AppDomain.CurrentDomain.BaseDirectory + "Example25Lib.dll"); //遍历程序集内所有的类型,并实例化 Type[] tmpTypes = tmpAss.GetTypes(); foreach (Type tmpType in tmpTypes) { //获取第一个类型的构造函数信息 ConstructorInfo[] tmpConsInfos = tmpType.GetConstructors(); foreach (ConstructorInfo tmpConsInfo in tmpConsInfos) { //为构造函数生成调用的参数集合 ParameterInfo[] tmpParamInfos = tmpConsInfo.GetParameters(); object[] tmpParams = new object[tmpParamInfos.Length]; for (int i = 0; i < tmpParamInfos.Length; i++) { tmpParams[i] = tmpAss.CreateInstance(tmpParamInfos[i].ParameterType.FullName); if (tmpParamInfos[i].ParameterType.FullName == "System.String") { tmpParams[i] = "Clark"; } } //实例化对象 object tmpObj = tmpConsInfo.Invoke(tmpParams); Console.WriteLine(tmpObj); //获取所有方法并执行 foreach (MethodInfo tmpMethod in tmpType.GetMethods()) { //为方法的调用创建参数集合 tmpParamInfos = tmpMethod.GetParameters(); tmpParams = new object[tmpParamInfos.Length]; for (int i = 0; i < tmpParamInfos.Length; i++) { tmpParams[i] = tmpAss.CreateInstance(tmpParamInfos[i].ParameterType.FullName); if (tmpParamInfos[i].ParameterType.FullName == "System.String") { tmpParams[i] = "Clark Zheng"; } if (tmpParamInfos[i].ParameterType.FullName == "System.Int32") { tmpParams[i] = 27; } } tmpMethod.Invoke(tmpObj, tmpParams); } //调用完方法后再次打印对象,比较结果 Console.WriteLine(tmpObj); } } Console.ReadLine(); } } }
结果: Name: Clark, Age: 0 Name: Clark Zheng, Age: 27
示例下载:http://www.cnblogs.com/Files/reonlyrun/CSharp25QExample07.rar
如果你认为还有哪些概念比较重要或容易混淆,可以在回复中提出,我会及时更新这篇随笔 
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://technicalsupport.businessobjects.com/KanisaSupportSite/search.do?cmd=displayKC&docType=kc&externalId=c2005119&sliceId=&dialogID=2998976&stateId=1%200%203000588 Use the 'Underlay following section' formatting option to achieve this. 1. Create an additional Page Header section: · Right-click the gray area to the left of the Page Header section - Select 'Insert section below' This inserts a second Page Header, so you now have a Page Header - a and a Page Header - b. 2. Re-size the Page Header - a section so it is the height of the page. 3. Insert the bitmap image (a .BMP file) of the pre-printed form or logo for the watermark into the Page Header -a section. 4. Go to Format | Section to open the Section Expert window, and select the Page Header - a section. 5. Select the 'Underlay following section' option. 6. Close the Section Expert. The bitmap image in Page Header - a now appears beneath all the sections that come after it, up to the Page Footer. The Page Headers and Page Footers cannot exceed the vertical size of the report. NOTE: ===== Ensure that you suppress the Page Footer of the report because the Page Header cannot underlay the Page Footer.
I create this new category for studying WPF.
CTP - community technology preview - this is just a point in time release to get more bits into hands of customers between beta releases, for those hard core people who want to be as close to the action as possible. Beta - these releases get special attention from the QA Team, we plan for them, treat as a milestone, etc. RC - release candidate, this is the one we hope will become an RTM. Testing additional RC candidates can get to be like a baseball game in extra innings. When we finally say "ship it" everyone celebrates. RTM - release to manufacture, this is the RC that gets shrink wrapped.
http://support.microsoft.com/kb/312629/EN-US/ SYMPTOMS If you use the Response.End, Response.Redirect, or Server.Transfer method, a ThreadAbortException exception occurs. You can use a try-catch statement to catch this exception. Back to the top
CAUSE The Response.End method ends the page execution and shifts the execution to the Application_EndRequest event in the application's event pipeline. The line of code that follows Response.End is not executed. This problem occurs in the Response.Redirect and Server.Transfer methods because both methods call Response.End internally. Back to the top
RESOLUTION To work around this problem, use one of the following methods: For Response.End, call the HttpContext.Current.ApplicationInstance.CompleteRequest method instead of Response.End to bypass the code execution to the Application_EndRequest event.
For Response.Redirect, use an overload, Response.Redirect(String url, bool endResponse) that passes false for the endResponse parameter to suppress the internal call to Response.End. For example: Response.Redirect ("nextpage.aspx", false);
If you use this workaround, the code that follows Response.Redirect is executed.
For Server.Transfer, use the Server.Execute method instead.
www.yardsaleportal.org free posting, multiple cities, searching, categories, knowledge base, sign selling, RSS subscription, featured listing
This category will record information for all projects I am going to develop.
http://aspalliance.com/774 Title: Repopulating checkboxes in GridView solution Name: Anonymous Date: 8/13/2006 8:30:45 PM Comment: This is a great solution! However, when I first tested I get the same problem as everyone where the checkboxes get reset after every page changed. In order to solve this problem, you need to add DataBound event to repopulate the checkboxes states. Below is the solution: protected void GridView1_DataBound(Object sender, EventArgs e) { RePopulateValues(); } protected void GridView1_PageIndexChanging(Object sender, GridViewPageEventArgs e) { RememberOldValues(); } Note: This is done in .Net 2.0 and the reason the author code doesn't work is because the databound event is called after pageindexchanging and pageindexchanged and therefore it clears the checkboxes states.
<!----connection string for SQL 2005 Express -----------> <!-- <add key="DBConnStr" value="Provider=SQLOLEDB;Data Source=(local)\SQLExpress; Initial Catalog= SMARTBRIDGE; Integrated Security=SSPI;"/> --> <!-- <add key="DBConnStrMaster" value="Provider=SQLOLEDB;Data Source=(local)\SQLExpress; Initial Catalog= master; Integrated Security=SSPI;"/> -->
The Page class includes a property called the IsPostBack property, which you can use to detect whether the page has already been posted back to the server. Because of View State, when you initialize a control property, you do not want to initialize the property every time a page loads. Because View State saves the state of control properties across page posts, you typically initialize a control property only once, when the page first loads. In fact, many controls don't work correctly if you re-initialize the properties of the control with each page load. In these cases, you must use the IsPostBack property to detect whether or not the page has been posted. if(!Page.isPostBack)
{
//not postback means first time initiation.
}
Here is the sequence of events that are raised whenever you request a page: - PreInit
- Init
- InitComplete
- PreLoad
- Load
- LoadComplete
- PreRender
- PreRenderComplete
- SaveStateComplete
- Unload
Ninety-nine percent of the time, you won't handle any of these events except for the Load and the PreRender events. The difference between these two events is that the Load event happens before any control events and the PreRender event happens after any control events.
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
Web 2.0 affirms that you can develop a better application, faster, with a handful of developers who know what they are doing. Conversely, nine mothers cannot make a baby in one month.
The most popular mashups and remixes follow a similar pattern. For example, Google Maps (which kick-started the rich browser application movement) was developed by a very small company in approximately two weeks. Productivity and, consequently, business impact is so high because developers have the tools they need on hand, and because, at the end of the day, the developers know what they’re doing.
Amazon as a company has adopted the Web 2.0 line of thinking with open arms. Having weathered the dot-com bubble, it has its sights fixed firmly on the future, and is making great strides toward defining the direction of its company and, to some degree, the Internet itself.
Amazon allows customers to review products, tag and categorize them, rate products, and even rate product reviews by other customers.
The Web is alive and well and more compelling than ever. I once sat in a conference room where one CEO likened the creation of the Internet to the discovery of fire. Now, even with my best propeller hat firmly in place, I think fire was a little more significant. Nevertheless, there is a wealth of opportunity on the Web for developers and business people alike.
http://msdn2.microsoft.com/en-us/library/ms178116.aspx ApplicationPath Gets the root path of the current application, regardless of where in the application you request it. For the example, the property returns the following: / CurrentExecutionFilePath Gets the virtual path of the current request. Differs from the FilePath property in that CurrentExecutionFilePath is correct if the request has been redirected in server code. For the example, the property returns the following: /MyApplication/MyPages/Default.aspx If you get the property in code that is running as a result of a call to Transfer or Execute, the path reflects the location of the code. FilePath Gets the virtual path of the current request. For the example, the property returns the following: /MyApplication/MyPages/Default.aspx Unlike the CurrentExecutionFilePath property, FilePath does not reflect server-side transfers. Path Gets the virtual path of the current request. For the example, the property returns the following: /MyApplication/MyPages/default.aspx PhysicalApplicationPath Gets the physical file system path of the currently executing application's root directory. For the example, the property returns the following: C:\inetpub\wwwroot\ PhysicalPath Gets the physical file-system path that corresponds to the requested URL. For the example, the property returns the following: C:\inetpub\wwwroot\MyApplication\MyPages\default.aspx
http://en.csharp-online.net/BCL_Generics%E2%80%94S... using System;
using System.Collections.Generic;
using System.Collections;
using System.Text;
namespace SortedListTest
{
public class Customer
{
private int id;
private string name;
private string category;
public int Id
{
get
{
return id;
}
set
{
if (id == value)
return;
id = value;
}
}
public string Name
{
get
{
return name;
}
set
{
if (name == value)
return;
name = value;
}
}
public string Category
{
get
{
return category;
}
set
{
if (category == value)
return;
category = value;
}
}
/// <summary>
/// Creates a new instance of customer
/// </summary>
/// <param name="id"></param>
/// <param name="name"></param>
/// <param name="category"></param>
public Customer(int id, string name, string category)
{
this.id = id;
this.name = name;
this.category = category;
}
public override string ToString()
{
return string.Format("{0}-{1}-{2}", id, name, category);
}
}
class Program
{
static void Main(string[] args)
{
List<Customer> collCustList =
new List<Customer>();
collCustList.Add(new Customer(99,
"Happy Gillmore", "Platinum"));
collCustList.Add(new Customer(77,
"Billy Madison", "Gold"));
collCustList.Add(new Customer(55,
"Bobby Boucher", "Gold"));
collCustList.Add(new Customer(88,
"Barry Egan", "Platinum"));
collCustList.Add(new Customer(11,
"Longfellow Deeds", "Other"));
Console.Out.WriteLine("Before:");
foreach (Customer cust in collCustList)
Console.Out.WriteLine(cust);
collCustList.Sort
(delegate(Customer cust1,
Customer cust2)
{
return Comparer<int>.Default.Compare
(cust1.Id, cust2.Id);
});
Console.Out.WriteLine("After:");
foreach (Customer cust in collCustList)
Console.Out.WriteLine(cust);
collCustList.Reverse();
Console.Out.WriteLine("Reversed:");
foreach (Customer cust in collCustList)
Console.Out.WriteLine(cust);
Console.In.ReadLine();
}
}
}
In the configuration file the connection string of MySQL should use ip address as the server address. In installation package, the error "cannot find specified types" is said to be related with the framework version. But I have no luck of it. The alternation is to divide the installation package to two part. One part install the crystal report merge module, the copy the reportengine service files to the server and use command "installutil" to install the service manually. When running the service, "Can not find keycodeV2.dll" pops out, the main reason to cause is to assign the invalid code to one of the merge modules. Anyway, here are some useful links I found when diagnosing the problems I got today: Application Deployment (CR report for VS.Net) http://support.businessobjects.com/ "Cannot find KeycodeV2.dll or invalid keycode" http://technicalsupport.businessobjects.com/ "unable to get installer types" (no answers can solve my problem)
Normally you cannot get the size of an object in the managed heap. This is because that size doesn't make sense in the managed world due to different reasons. One of them could be that the size of the same object is not guaranteed to be the same between two starts of the application. The JIT compiler is free to layout the objects as it sees fit. The layouting can be different due to different configuration of the machine, different version of the CLR, etc. Furthermore, your type may reference other reference types. Even two objects can cross-reference the same object. How can you possibly tell what is the size of the object Using Marshal.SizeOf returns the size of the marshaled (unmanaged) equivalent of the provided type. I said "normally" back then because there is an operator that returns the managed size for a type (only for valuetypes). In C# it is represented by the *sizeof* operator. However *sizeof* operator has some limitations in addition to its syntax I don't think that is what you need.
About sizeof operator you can read at MSDN ms-help://MS.MSDNQTR.2003FEB.1033/csref/html/vclrfSizeofPG.htm To demonstrate the difference between Marshal.SizeOf and *sizeof* operator run the following simple code
class Class1
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
unsafe static void Main(string[] args)
{
Console.WriteLine("Managed size: {0}", sizeof(char));
Console.WriteLine("Unmanaged size: {0}", Marshal.SizeOf(typeof(char)));
Console.ReadLine();
}
}
The result is: Managed size: 2 Unmanaged size: 1
Unmanaged size is 1 because System.Char struct is set to be marshaled as ANSI char by default.
Working with google map. Following functions should be provided:
- Navigation and Location.
- User Login and management
- Create their own page (Pictures and Text)
- Menu Management (Normal and Special)
- Announcement Management.
- UserForum (and search) (Optional)
- Service Fee (Golden and Silver)
A similar website: http://www.toeat.com/
You notice the Ticket object changes state as it moves through this activity diagram. When the Ticket Agent performs the Generate Pass activity, the Ticket object has the valid state. After the Boarding Agent performs the Stamp Pass activity the Ticket changes to the used state.
Tip Use a connector when you run out of space in an activity diagram. For example, we ran out of room at the Receive Pass activity that the passenger performs. So, we placed a connector with the label A. Then we drew a control-flow line from Receive Pass to the A connector. Using the same technique, you can pick up the control-flow path at the connector with the same label A at the top of the Passenger’s swim lane, and then proceed to the Wait in line activity.
// XMLsample.cs
// compile with: /doc:XMLsample.xml
using System;
/// <summary>
/// Class level summary documentation goes here.</summary>
/// <remarks>
/// Longer comments can be associated with a type or member
/// through the remarks tag</remarks>
public class SomeClass
{
/// <summary>
/// Store for the name property</summary>
private string myName = null;
/// <summary>
/// The class constructor. </summary>
public SomeClass()
{
// TODO: Add Constructor Logic here
}
/// <summary>
/// Name property </summary>
/// <value>
/// A value tag is used to describe the property value</value>
public string Name
{
get
{
if ( myName == null )
{
throw new Exception("Name is null");
}
return myName;
}
}
/// <summary>
/// Description for SomeMethod.</summary>
/// <param name="s"> Parameter description for s goes here</param>
/// <seealso cref="String">
/// You can use the cref attribute on any tag to reference a type or member
/// and the compiler will check that the reference exists. </seealso>
public void SomeMethod(string s)
{
}
/// <summary>
/// Some other method. </summary>
/// <returns>
/// Return results are described through the returns tag.</returns>
/// <seealso cref="SomeMethod(string)">
/// Notice the use of the cref attribute to reference a specific method </seealso>
public int SomeOtherMethod()
{
return 0;
}
/// <summary>
/// The entry point for the application.
/// </summary>
/// <param name="args"> A list of command line arguments</param>
public static int Main(String[] args)
{
// TODO: Add code to start application here
return 0;
}
}
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.
The Five Steps are as follows:
-
Define. Identify the requirements of your system via Use Case Diagrams. Add other diagrams where they shed light on the use cases.
-
Refine. Detail the steps in each requirement via scenarios captured in Activity Diagrams. Add other diagrams where they shed light on the activities.
-
Assign. Use the Activity Diagrams to assign the steps to elements of your system.
-
Design. Show the relations among the elements with Component Diagrams. Add other diagrams where they shed light on the components.
-
Repeat/iterate/drill down/divide and conquer. Narrow the scope of your process to individual elements (designed with Class Diagrams); or expand it out to whole systems (designed with Deployment Diagrams). Add other diagrams wherever they help you understand the system. Repeat Steps 1 through 4 as appropriate for the current scope. Like Boehm's Spiral development process, Evolutionary Development, and many other modern processes, Five-Step UML is an incremental, recursive approach.
(Picked from book "UML Applied - A .Net Perspective")
A more important benefit of classes and objects is that they form a nice syntactic mechanism for achieving some classic aspects of well-designed code: [2]
-
Encapsulation. The goal of encapsulation is to expose only enough of a module or subsystem to allow other modules to make use of it. Object-Oriented Programming allows you to specify the degree of visibility of elements of your code, so that client code is restricted in what it can access. Thus, you can syntactically seal off implementation details, leading to more flexibility and maintainability in your system.
-
Loose coupling. Coupling refers to the ways in which and degrees to which one part of the system relies on the details of another part. The tighter the coupling, the more changes in one part of the system will ripple throughout the system. With loose coupling, the interfaces between subsystems are well defined and restricted. What lies beyond those interfaces can change without any changes needed in the client sub-systems. Object-Oriented Programming supports loose coupling by allowing you to define and publish a class's methods without publishing how those methods are carried out. This principle goes even further in OO languages that support interfaces (described later in this section).
-
Strong cohesion. Cohesion refers to the degree in which elements within a subsystem form a single, unified concept, with no excess elements. Where there is high cohesion, there is easier comprehension and thus more reliable code. Object-Oriented Programming supports strong cohesion by allowing you to design classes in which the data and the functions that operate on them are tightly bound together.
Does OO force you to have these quality attributes in your code? I wish! No matter the language, you can write shoddy code with no encapsulation, pathological coupling, and no cohesion. Furthermore, some OO languages are less rigid than others in how much they require you to design around objects. But OO languages certainly support these quality attributes if you take the time to pursue them.
The key concepts in Object-Oriented Programming are these:
-
Classes. A class is the definition of the behavior and properties of one or more objects within your system. A class binds the data (attributes) of an object to the behavior (operations) that it can perform.
-
Attributes. An attribute is a data value or state that describes an object and helps you to tell one object from another of the same class. It seems that every new OO language author feels the need to distinguish their language by coming up with new terminology. In some OO languages, these data values are called properties or member variables or member data; but in UML, the proper term is attributes.
-
Operations. An operation is a behavior or function that an object can perform. Depending on the OO language, these might be called methods or member functions or even messages. The last term, messages, comes from Smalltalk, one of the earliest OO languages, in which all objects communicated by sending messages to each other. You'll see a similar use of the term message when we study Sequence Diagrams.
-
Objects. An object is an instance or specific example of a class. If Dog is the class, then Betsy, Ladi, Patches, Jake, Radar, and Frosty are specific instances of the class found in my house. The attributes of the class have specific values within an object of that class; and the operations of a class operate on the attributes of individual objects.
-
Inheritance. This concept indicates that one class (the superclass) provides some common or general behavior inherited by one or more specific classes (the subclasses). The subclasses then provide more or different behavior beyond that defined in the superclass. For example, besides the Dogs, I have Cat objects and Horse objects that live on my property. Each class has unique behaviors: Dogs must be walked, Cats use the litter box, and Horses drop manure that must be scooped up and thrown in the manure pile. Yet all classes have some common behavior: they must be fed, and they must have vet visits. So I can define a superclass, Pet, and have my subclasses, Dog, Cat, and Horse, derive their shared behavior from the Pet class. In UML, this concept is known under the slightly different term of generalization, in which a superclass provides the generalized behavior of the subclasses. It's really the same concept, but just looking at it the other way up.
-
Components. A component is a collection of related classes that together provide a larger set of services. Components in your system might include applications, libraries, ActiveX controls, JavaBeans, daemons, and services. In the .NET environment, most of your projects will require component development.
-
Interfaces. An interface is a definition of a set of services provided by a component or by a class. This allows further encapsulation: the author of a component can publish just the interfaces to the component, completely hiding any implementation details.
Use the formula to control the background color: if recordnumber mod 2 = 0 then crSilver else crNoColor
Finally got the response from 1and1 technical support. You have to setup a proxy server to make it work:
Use the following in web.config to establish a connection to the proxy server:
<system.net> <defaultProxy> <proxy usesystemdefault = "false" bypassonlocal="false" proxyaddress="http://ntproxy.1and1.com:3128" /> </defaultProxy> </system.net>
Snap Preview provide free service to let your website animated and show the small neat snapshots of links on web page.
http://www.snap.com

Not having touched CSLA.NET framework for couple of months, I am requested to write a simple tutorial for developers at our China office. Great Rocky released CSKA.NET 2.1.3 two weeks ago. Several new features have been added. So I decided to read the book again and write some important notes here. Hope this could also improve my DotNet knowledge and OO Thinking. Here are some useful points I picked from the book: - To enable the objects for Data Binding, the business objects must implement following three interfaces: IEditableObject, INotifyPropertyChanged, IBindingList
- Generic types are not polymorphic like normal types. That's the primary reason for pulling the functionality out of the generic class into a normal class in CSLA.Net. ( BusinessBase<T> inherits from Csla.Core.BusinessBase)
- The goal in object design is to ensure that a given behavior exists only once with the object model while the relational modeling requires that a given data element should exist exactly once in the data model.
Note: For visitors of your site, this entry is only displayed for users with the preselected language English/English (en) CSLA.Net 2.1 has been released. It comes with several new features. Some useful ones I am going to use in Smart Bridge SA is :
- Per-type validation rules.
- Per-type authorization rules.
- Severity Classification.
|
Copyright © 2010 Kevin Mocha. All rights reserved.
DasBlog 'Portal' theme by Johnny Hughes.
Pick a theme:
|
|