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.
| |