Sunteți pe pagina 1din 69

Methods (C# Programming Guide)

Send Feedback on this topic to Microsoft. View this topic online in your default browser.

A method is a code block that contains a series of statements. A program causes the statements to be executed by calling the method and specifying any required method arguments. In C#, every executed instruction is performed in the context of a method. The Main method is the entry point for every C# application and it is called by the common language runtime (CLR) when the program is started.

Note This topic discusses named methods. For information about anonymous functions, see Anonymous Functions (C# Programming Guide). Method Signatures

Methods are declared in a class or struct by specifying the access level such as public or private, optional modifiers such as abstract or sealed, the return value, the name of the method, and any method parameters. These parts together are the signature of the method.

Note A return type of a method is not part of the signature of the method for the purposes of method overloading. However, it is part of the signature of the method when determining the compatibility between a delegate and the method that it points to. Method parameters are enclosed in parentheses and are separated by commas. Empty parentheses indicate that the method requires no parameters. This class contains three methods: JavaScript C# C++ F# JScript VB Copy to Clipboard
abstract class Motorcycle { // Anyone can call this. public void StartEngine() {/* Method statements here */ }

// Only derived classes can call this. protected void AddGas(int gallons) { /* Method statements here */ } // Derived classes can override the base class implementation. public virtual int Drive(int miles, int speed) { /* Method statements here */ return 1; } // Derived classes must implement this. public abstract double GetTopSpeed(); }

Method Access

Calling a method on an object is like accessing a field. After the object name, add a period, the name of the method, and parentheses. Arguments are listed within the parentheses, and are separated by commas. The methods of the Motorcycle class can therefore be called as in the following example: JavaScript C# C++ F# JScript VB Copy to Clipboard
class TestMotorcycle : Motorcycle { public override double GetTopSpeed() { return 108.4; } static void Main() { TestMotorcycle moto = new TestMotorcycle(); moto.StartEngine(); moto.AddGas(15); moto.Drive(5, 20); double speed = moto.GetTopSpeed(); Console.WriteLine("My top speed is {0}", speed); } }

Method Parameters vs. Arguments

The method definition specifies the names and types of any parameters that are required. When calling code calls the method, it provides concrete values called arguments for each parameter. The arguments must be compatible with the parameter type but the argument name (if any) used in the calling code does not have to be the same as the parameter named defined in the method. For example: JavaScript C# C++ F# JScript VB Copy to Clipboard
public void Caller() { int numA = 4; // Call with an int variable. int productA = Square(numA); int numB = 32; // Call with another int variable. int productB = Square(numB); // Call with an integer literal. int productC = Square(12); // Call with an expression that evaulates to int. productC = Square(productA * 3); } int Square(int i) { // Store input argument in a local variable. int input = i; return input * input; }

Passing by Reference vs. Passing by Value

By default, when a value type is passed to a method, a copy is passed instead of the object itself. Therefore, changes to the argument have no effect on the original copy in the calling method. You can pass a value-type by reference by using the ref keyword. For more information, see Passing Value-Type Parameters (C# Programming Guide). For a list of built-in value types, see Value Types Table (C# Reference). When an object of a reference type is passed to a method, a reference to the object is passed. That is, the method receives not the object itself but an argument that indicates the location of the object. If you change a member of the object by using this reference, the change is reflected in the argument in the calling method, even if you pass the object by value.

You create a reference type by using the class keyword, as the following example shows. JavaScript C# C++ F# JScript VB Copy to Clipboard
public class SampleRefType { public int value; }

Now, if you pass an object that is based on this type to a method, a reference to the object is passed. The following example passes an object of type SampleRefType to method ModifyObject. JavaScript C# C++ F# JScript VB Copy to Clipboard
public static void TestRefType() { SampleRefType rt = new SampleRefType(); rt.value = 44; ModifyObject(rt); Console.WriteLine(rt.value); } static void ModifyObject(SampleRefType obj) { obj.value = 33; }

The example does essentially the same thing as the previous example in that it passes an argument by value to a method. But, because a reference type is used, the result is different. The modification that is made in ModifyObject to the value field of the parameter, obj, also changes the value field of the argument, rt, in the TestRefType method. The TestRefType method displays 33 as the output. For more information about how to pass reference types by reference and by value, see Passing Reference-Type Parameters (C# Programming Guide) and Reference Types (C# Reference). Return Values

Methods can return a value to the caller. If the return type, the type listed before the method name, is not void, the method can return the value by using the return keyword. A statement with the return keyword followed by a value that matches the return type will return that value to the method caller. The return keyword also stops the execution of the method. If the return type is void, a return statement without a value is still useful to stop the execution of the method. Without the return keyword, the method will stop executing when it reaches the end of the code block. Methods with a non-void return type are required to use the return keyword to return a value. For example, these two methods use the return keyword to return integers: JavaScript C# C++ F# JScript VB Copy to Clipboard
class SimpleMath { public int AddTwoNumbers(int number1, int number2) { return number1 + number2; } public int SquareANumber(int number) { return number * number; } }

To use a value returned from a method, the calling method can use the method call itself anywhere a value of the same type would be sufficient. You can also assign the return value to a variable. For example, the following two code examples accomplish the same goal: JavaScript C# C++ F# JScript VB Copy to Clipboard
int result = obj.AddTwoNumbers(1, 2); result = obj.SquareANumber(result); // The result is 9. Console.WriteLine(result);

JavaScript C# C++ F# JScript

VB Copy to Clipboard
result = obj.SquareANumber(obj.AddTwoNumbers(1, 2)); // The result is 9. Console.WriteLine(result);

Using a local variable, in this case, result, to store a value is optional. It may help the readability of the code, or it may be necessary if you need to store the original value of the argument for the entire scope of the method. For more information, see return (C# Reference). Async Methods

By using the async feature, you can invoke asynchronous methods without using explicit callbacks or manually splitting your code across multiple methods or lambda expressions. The async feature was introduced Visual Studio 2012. If you mark a method with the async modifier, you can use the await operator in the method. When control reaches an await expression in the async method, control returns to the caller, and progress in the method is suspended until the awaited task completes. When the task is complete, execution can resume in the method.

Note An async method returns to the caller when either it encounters the first awaited object thats not yet complete or it gets to the end of the async method, whichever occurs first. An async method can have a return type of Task< TResult> , Task, or void. The void return type is used primarily to define event handlers, where a void return type is required. An async method that returns void can't be awaited, and the caller of a void-returning method can't catch exceptions that the method throws. In the following example, DelayAsync is an async method that has a return type of Task< TResult> .DelayAsync has a return statement that returns an integer. Therefore the method declaration of DelayAsync must have a return type of Task<int>. Because the return type is Task<int>, the evaluation of the await expression in DoSomethingAsync produces an integer as the following statement demonstrates: int result = await delayTask. The startButton_Click method is an example of an async method that has a return type of void. Because DoSomethingAsync is an async method, the task for the call to DoSomethingAsync must be awaited, as the following statement shows: await DoSomethingAsync();. The startButton_Click method must be defined with the async modifier because the method has an await expression.

JavaScript C# C++ F# JScript VB Copy to Clipboard


// using System.Diagnostics; // using System.Threading.Tasks; // This Click event is marked with the async modifier. private async void startButton_Click(object sender, RoutedEventArgs e) { await DoSomethingAsync(); } private async Task DoSomethingAsync() { Task<int> delayTask = DelayAsync(); int result = await delayTask; // The previous two statements may be combined into // the following statement. //int result = await DelayAsync(); Debug.WriteLine("Result: " + result); } private async Task<int> DelayAsync() { await Task.Delay(100); return 5; } // Output: // Result: 5

An async method can't declare any ref or out parameters, but it can call methods that have such parameters. For more information about async methods, see Asynchronous Programming with Async and Await (C# and Visual Basic), Control Flow in Async Programs (C# and Visual Basic), and Async Return Types (C# and Visual Basic). Iterators

An iterator performs a custom iteration over a collection, such as a list or an array. An iterator uses the yield return statement to return each element one at a time. When a yield return statement is reached, the current location in code is remembered. Execution is restarted from that location when the iterator is called the next time.

You call an iterator from client code by using a foreach statement. The return type of an iterator can be IEnumerable, IEnumerable< T> , IEnumerator, or IEnumerator< T> . For more information, see Iterators (C# and Visual Basic). Passing Parameters (C# Programming Guide) Send Feedback on this topic to Microsoft. View this topic online in your default browser.

In C#, arguments can be passed to parameters either by value or by reference. Passing by reference enables function members, methods, properties, indexers, operators, and constructors to change the value of the parameters and have that change persist in the calling environment. To pass a parameter by reference, use the ref or out keyword. For simplicity, only the ref keyword is used in the examples in this topic. For more information about the difference between ref and out, see ref (C# Reference), out (C# Reference), and Passing Arrays Using ref and out (C# Programming Guide). The following example illustrates the difference between value and reference parameters. JavaScript C# C++ F# JScript VB Copy to Clipboard
class Program { static void Main(string[] args) { int arg; // Passing by value. // The value of arg in Main is not changed. arg = 4; squareVal(arg); Console.WriteLine(arg); // Output: 4 // Passing by reference. // The value of arg in Main is changed. arg = 4; squareRef(ref arg); Console.WriteLine(arg); // Output: 16

} static void squareVal(int valParameter) { valParameter *= valParameter; } // Passing by reference static void squareRef(ref int refParameter) { refParameter *= refParameter; }

Passing Value-Type Parameters (C# Programming Guide) Send Feedback on this topic to Microsoft. View this topic online in your default browser.

A value-type variable contains its data directly as opposed to a reference-type variable, which contains a reference to its data. Passing a value-type variable to a method by value means passing a copy of the variable to the method. Any changes to the parameter that take place inside the method have no affect on the original data stored in the argument variable. If you want the called method to change the value of the parameter, you must pass it by reference, using the ref or out keyword. For simplicity, the following examples use ref. Passing Value Types by Value

The following example demonstrates passing value-type parameters by value. The variable n is passed by value to the method Square It. Any changes that take place inside the method have no affect on the original value of the variable. JavaScript C# C++ F# JScript VB Copy to Clipboard
class PassingValByVal { static void SquareIt(int x) // The parameter x is passed by value. // Changes to x will not affect the original value of x. { x *= x; System.Console.WriteLine("The value inside the method: {0}", x); } static void Main()

{ int n = 5; System.Console.WriteLine("The value before calling the method: {0}", n); SquareIt(n); // Passing the variable by value. System.Console.WriteLine("The value after calling the method: {0}", n); // Keep the console window open in debug mode. System.Console.WriteLine("Press any key to exit."); System.Console.ReadKey(); } } /* Output: The value before calling the method: 5 The value inside the method: 25 The value after calling the method: 5 */

The variable n is a value type. It contains its data, the value 5. When SquareIt is invoked, the contents of n are copied into the parameter x, which is squared inside the method. In Main, however, the value of n is the same after calling the SquareIt method as it was before. The change that takes place inside the method only affects the local variable x. Passing Value Types by Reference

The following example is the same as the previous example, except that the argument is passed as a ref parameter. The value of the underlying argument, n, is changed when x is changed in the method. JavaScript C# C++ F# JScript VB Copy to Clipboard
class PassingValByRef { static void SquareIt(ref int x) // The parameter x is passed by reference. // Changes to x will affect the original value of x. { x *= x; System.Console.WriteLine("The value inside the method: {0}", x); } static void Main() { int n = 5;

System.Console.WriteLine("The value before calling the method: {0}", n); SquareIt(ref n); // Passing the variable by reference. System.Console.WriteLine("The value after calling the method: {0}", n); // Keep the console window open in debug mode. System.Console.WriteLine("Press any key to exit."); System.Console.ReadKey(); } } /* Output: The value before calling the method: 5 The value inside the method: 25 The value after calling the method: 25 */

In this example, it is not the value of n that is passed; rather, a reference to n is passed. The parameter x is not an int; it is a reference to an int, in this case, a reference to n. Therefore, when x is squared inside the method, what actually is squared is what x refers to, n. Swapping Value Types

A common example of changing the values of arguments is a swap method, where you pass two variables to the method, and the method swaps their contents. You must pass the arguments to the swap method by reference. Otherwise, you swap local copies of the parameters inside the method, and no change occurs in the calling method. The following example swaps integer values. JavaScript C# C++ F# JScript VB Copy to Clipboard
static void SwapByRef(ref int x, ref int y) { int temp = x; x = y; y = temp; }

When you call the SwapByRef method, use the ref keyword in the call, as shown in the following example. JavaScript C#

C++ F# JScript VB Copy to Clipboard


static void Main() { int i = 2, j = 3; System.Console.WriteLine("i = {0} SwapByRef (ref i, ref j); System.Console.WriteLine("i = {0} j = {1}" , i, j);

j = {1}" , i, j);

// Keep the console window open in debug mode. System.Console.WriteLine("Press any key to exit."); System.Console.ReadKey(); } /* Output: i = 2 j = 3 i = 3 j = 2 */

See Also Passing Reference-Type Parameters (C# Programming Guide) Send Feedback on this topic to Microsoft. View this topic online in your default browser.

A variable of a reference type does not contain its data directly; it contains a reference to its data. When you pass a reference-type parameter by value, it is possible to change the data pointed to by the reference, such as the value of a class member. However, you cannot change the value of the reference itself; that is, you cannot use the same reference to allocate memory for a new class and have it persist outside the block. To do that, pass the parameter using the ref or out keyword. For simplicity, the following examples use ref. Passing Reference Types by Value

The following example demonstrates passing a reference-type parameter, arr, by value, to a method, Change. Because the parameter is a reference to arr, it is possible to change the values of the array elements. However, the attempt to reassign the parameter to a different memory location only works inside the method and does not affect the original variable, arr. JavaScript C# C++

F# JScript VB Copy to Clipboard


class PassingRefByVal { static void Change(int[] pArray) { pArray[0] = 888; // This change affects the original element. pArray = new int[5] {-3, -1, -2, -3, -4}; // This change is local. System.Console.WriteLine("Inside the method, the first element is: {0}", pArray[0]); } static void Main() { int[] arr = {1, 4, 5}; System.Console.WriteLine("Inside Main, before calling the method, the first element is: {0}", arr [0]); Change(arr); System.Console.WriteLine("Inside Main, after calling the method, the first element is: {0}", arr [0]); } } /* Output: Inside Main, before calling the method, the first element is: 1 Inside the method, the first element is: -3 Inside Main, after calling the method, the first element is: 888 */

In the preceding example, the array, arr, which is a reference type, is passed to the method without the ref parameter. In such a case, a copy of the reference, which points to arr, is passed to the method. The output shows that it is possible for the method to change the contents of an array element, in this case from 1 to 888. However, allocating a new portion of memory by using the new operator inside the Change method makes the variable pArray reference a new array. Thus, any changes after that will not affect the original array, arr, which is created inside Main. In fact, two arrays are created in this example, one inside Main and one inside the Change method. Passing Reference Types by Reference

The following example is the same as the previous example, except that the ref keyword is added to the method header and call. Any changes that take place in the method affect the original variable in the calling program. JavaScript C# C++

F# JScript VB Copy to Clipboard


class PassingRefByRef { static void Change(ref int[] pArray) { // Both of the following changes will affect the original variables: pArray[0] = 888; pArray = new int[5] {-3, -1, -2, -3, -4}; System.Console.WriteLine("Inside the method, the first element is: {0}", pArray[0]); } static void Main() { int[] arr = {1, 4, 5}; System.Console.WriteLine("Inside Main, before calling the method, the first element is: {0}", arr[0]); Change(ref arr); System.Console.WriteLine("Inside Main, after calling the method, the first element is: {0}", arr[0]); } } /* Output: Inside Main, before calling the method, the first element is: 1 Inside the method, the first element is: -3 Inside Main, after calling the method, the first element is: -3 */

All of the changes that take place inside the method affect the original array in Main. In fact, the original array is reallocated using the new operator. Thus, after calling the Change method, any reference to arr points to the five-element array, which is created in the Change method. Swapping Two Strings

Swapping strings is a good example of passing reference-type parameters by reference. In the example, two strings, str1 and str2, are initialized in Main and passed to the SwapStrings method as parameters modified by the ref keyword. The two strings are swapped inside the method and inside Main as well. JavaScript C# C++ F# JScript VB

Copy to Clipboard
class SwappingStrings { static void SwapStrings(ref string s1, ref string s2) // The string parameter is passed by reference. // Any changes on parameters will affect the original variables. { string temp = s1; s1 = s2; s2 = temp; System.Console.WriteLine("Inside the method: {0} {1}", s1, s2); } static void Main() { string str1 = "John"; string str2 = "Smith"; System.Console.WriteLine("Inside Main, before swapping: {0} {1}", str1, str2); SwapStrings(ref str1, ref str2); // Passing strings by reference System.Console.WriteLine("Inside Main, after swapping: {0} {1}", str1, str2); } } /* Output: Inside Main, before swapping: John Smith Inside the method: Smith John Inside Main, after swapping: Smith John */

In this example, the parameters need to be passed by reference to affect the variables in the calling program. If you remove the ref keyword from both the method header and the method call, no changes will take place in the calling program. For more information about strings, see string. See Also Passing Arrays Using ref and out (C# Programming Guide) Send Feedback on this topic to Microsoft. View this topic online in your default browser.

Like all out parameters, an out parameter of an array type must be assigned before it is used; that is, it must be assigned by the callee. For example: JavaScript C#

C++ F# JScript VB Copy to Clipboard


static void TestMethod1(out int[] arr) { arr = new int[10]; // definite assignment of arr }

Like all ref parameters, a ref parameter of an array type must be definitely assigned by the caller. Therefore, there is no need to be definitely assigned by the callee. A ref parameter of an array type may be altered as a result of the call. For example, the array can be assigned the null value or can be initialized to a different array. For example: JavaScript C# C++ F# JScript VB Copy to Clipboard
static void TestMethod2(ref int[] arr) { arr = new int[10]; // arr initialized to a different array }

The following two examples demonstrate the difference between out and ref when used in passing arrays to methods. Example

In this example, the array theArray is declared in the caller (the Main method), and initialized in the FillArray method. Then, the array elements are returned to the caller and displayed. JavaScript C# C++ F# JScript VB Copy to Clipboard
class TestOut { static void FillArray(out int[] arr) { // Initialize the array:

arr = new int[5] { 1, 2, 3, 4, 5 }; } static void Main() { int[] theArray; // Initialization is not required // Pass the array to the callee using out: FillArray(out theArray); // Display the array elements: System.Console.WriteLine("Array elements are:"); for (int i = 0; i < theArray.Length; i++) { System.Console.Write(theArray[i] + " "); } // Keep the console window open in debug mode. System.Console.WriteLine("Press any key to exit."); System.Console.ReadKey(); } } /* Output: Array elements are: 1 2 3 4 5 */

In this example, the array theArray is initialized in the caller (the Main method), and passed to the FillArray method by using the ref parameter. Some of the array elements are updated in the FillArray method. Then, the array elements are returned to the caller and displayed. JavaScript C# C++ F# JScript VB Copy to Clipboard
class TestRef { static void FillArray(ref int[] arr) { // Create the array on demand: if (arr == null) { arr = new int[10]; } // Fill the array: arr[0] = 1111; arr[4] = 5555; } static void Main() {

// Initialize the array: int[] theArray = { 1, 2, 3, 4, 5 }; // Pass the array using ref: FillArray(ref theArray); // Display the updated array: System.Console.WriteLine("Array elements are:"); for (int i = 0; i < theArray.Length; i++) { System.Console.Write(theArray[i] + " "); } // Keep the console window open in debug mode. System.Console.WriteLine("Press any key to exit."); System.Console.ReadKey(); } } /* Output: Array elements are: 1111 2 3 4 5555 */

Object and Collection Initializers (C# Programming Guide) Send Feedback on this topic to Microsoft. View this topic online in your default browser.

Object initializers let you assign values to any accessible fields or properties of an object at creation time without having to explicitly invoke a constructor. The following example shows how to use an object initializer with a named type, Cat. Note the use of auto-implemented properties in the Cat class. For more information, see Auto-Implemented Properties (C# Programming Guide). JavaScript C# C++ F# JScript VB Copy to Clipboard
class Cat { // Auto-implemented properties. public int Age { get; set; } public string Name { get; set; } }

JavaScript C# C++ F#

JScript VB Copy to Clipboard


Cat cat = new Cat { Age = 10, Name = "Fluffy" };

Object Initializers with anonymous types

Although object initializers can be used in any context, they are especially useful in LINQ query expressions. Query expressions make frequent use of anonymous types, which can only be initialized by using an object initializer, as shown in the following declaration. Copy to Clipboard
var pet = new { Age = 10, Name = "Fluffy" };

Anonymous types enable the select clause in a LINQ query expression to transform objects of the original sequence into objects whose value and shape may differ from the original. This is useful if you want to store only a part of the information from each object in a sequence. In the following example, assume that a product object (p) contains many fields and methods, and that you are only interested in creating a sequence of objects that contain the product name and the unit price. JavaScript C# C++ F# JScript VB Copy to Clipboard
var productInfos = from p in products select new { p.ProductName, p.UnitPrice };

When this query is executed, the productInfos variable will contain a sequence of objects that can be accessed in a foreach statement as shown in this example: Copy to Clipboard
foreach(var p in productInfos){...}

Each object in the new anonymous type has two public properties which receive the same names as the properties or fields in the original object. You can also rename a field when you are creating an anonymous type; the following example renames the UnitPrice field to Price. Copy to Clipboard
select new {p.ProductName, Price = p.UnitPrice};

Object initializers with nullable types

It is a compile-time error to use an object initializer with a nullable struct. Collection Initializers

Collection initializers let you specify one or more element initializers when you initialize a collection class that implements IEnumerable. The element initializers can be a simple value, an expression or an object initializer. By using a collection initializer you do not have to specify multiple calls to the Add method of the class in your source code; the compiler adds the calls. The following examples shows two simple collection initializers: Copy to Clipboard
List<int> digits = new List<int> { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; List<int> digits2 = new List<int> { 0 + 1, 12 % 3, MakeInt() };

The following collection initializer uses object initializers to initialize objects of the Cat class defined in a previous example. Note that the individual object initializers are enclosed in braces and separated by commas. JavaScript C# C++ F# JScript VB Copy to Clipboard
List<Cat> cats { new Cat(){ new Cat(){ new Cat(){ }; = new List<Cat> Name = "Sylvester", Age=8 }, Name = "Whiskers", Age=2 }, Name = "Sasha", Age=14 }

You can specify null as an element in a collection initializer if the collection's Add method allows it. JavaScript C# C++ F# JScript VB Copy to Clipboard
List<Cat> moreCats = new List<Cat> { new Cat(){ Name = "Furrytail", Age=5 }, new Cat(){ Name = "Peaches", Age=4 },

null };

Example JavaScript C# C++ F# JScript VB Copy to Clipboard


// The following code consolidates examples from the topic. class ObjInitializers { class Cat { // Auto-implemented properties. public int Age { get; set; } public string Name { get; set; } } static void Main() { Cat cat = new Cat { Age = 10, Name = "Fluffy" }; List<Cat> cats { new Cat(){ new Cat(){ new Cat(){ }; = new List<Cat> Name = "Sylvester", Age=8 }, Name = "Whiskers", Age=2 }, Name = "Sasha", Age=14 }

List<Cat> moreCats = new List<Cat> { new Cat(){ Name = "Furrytail", Age=5 }, new Cat(){ Name = "Peaches", Age=4 }, null }; // Display results. System.Console.WriteLine(cat.Name); foreach (Cat c in cats) System.Console.WriteLine(c.Name); foreach (Cat c in moreCats) if (c != null) System.Console.WriteLine(c.Name); else System.Console.WriteLine("List element has null value."); } // Output: //Fluffy //Sylvester

//Whiskers //Sasha //Furrytail //Peaches //List element has null value. }

Anonymous Types (C# Programming Guide) Send Feedback on this topic to Microsoft. View this topic online in your default browser.

Anonymous types provide a convenient way to encapsulate a set of read-only properties into a single object without having to explicitly define a type first. The type name is generated by the compiler and is not available at the source code level. The type of each property is inferred by the compiler. You create anonymous types by using the new operator together with an object initializer. For more information about object initializers, see Object and Collection Initializers (C# Programming Guide). The following example shows an anonymous type that is initialized with two properties named Amount and Message. JavaScript C# C++ F# JScript VB Copy to Clipboard
var v = new { Amount = 108, Message = "Hello" }; // Rest the mouse pointer over v.Amount and v.Message in the following // statement to verify that their inferred types are int and string. Console.WriteLine(v.Amount + v.Message);

Anonymous types typically are used in the select clause of a query expression to return a subset of the properties from each object in the source sequence. For more information about queries, see LINQ Query Expressions (C# Programming Guide). Anonymous types contain one or more public read-only properties. No other kinds of class members, such as methods or events, are valid. The expression that is used to initialize a property cannot be null, an anonymous function, or a pointer type. The most common scenario is to initialize an anonymous type with properties from another type. In the following example, assume that a class exists that is named Product. Class Product includes Color and Price properties, together with other properties that you are not interested in. Variable products is a collection of Product objects. The anonymous type declaration starts with

the new keyword. The declaration initializes a new type that uses only two properties from Product. This causes a smaller amount of data to be returned in the query. If you do not specify member names in the anonymous type, the compiler gives the anonymous type members the same name as the property being used to initialize them. You must provide a name for a property that is being initialized with an expression, as shown in the previous example. In the following example, the names of the properties of the anonymous type are Color and Price. JavaScript C# C++ F# JScript VB Copy to Clipboard
var productQuery = from prod in products select new { prod.Color, prod.Price }; foreach (var v in productQuery) { Console.WriteLine("Color={0}, Price={1}", v.Color, v.Price); }

Typically, when you use an anonymous type to initialize a variable, you declare the variable as an implicitly typed local variable by using var. The type name cannot be specified in the variable declaration because only the compiler has access to the underlying name of the anonymous type. For more information about var, see Implicitly Typed Local Variables (C# Programming Guide). You can create an array of anonymously typed elements by combining an implicitly typed local variable and an implicitly typed array, as shown in the following example. JavaScript C# C++ F# JScript VB Copy to Clipboard
var anonArray = new[] { new { name = "apple", diam = 4 }, new { name = "grape", diam = 1 }};

Remarks

Anonymous types are class types that derive directly from object, and that cannot be cast to any type except object. The compiler provides a name for each anonymous type, although your

application cannot access it. From the perspective of the common language runtime, an anonymous type is no different from any other reference type. If two or more anonymous object initializers in an assembly specify a sequence of properties that are in the same order and that have the same names and types, the compiler treats the objects as instances of the same type. They share the same compiler-generated type information. You cannot declare a field, a property, an event, or the return type of a method as having an anonymous type. Similarly, you cannot declare a formal parameter of a method, property, constructor, or indexer as having an anonymous type. To pass an anonymous type, or a collection that contains anonymous types, as an argument to a method, you can declare the parameter as type object. However, doing this defeats the purpose of strong typing. If you must store query results or pass them outside the method boundary, consider using an ordinary named struct or class instead of an anonymous type. Because the Equals and GetHashCode methods on anonymous types are defined in terms of the Equals and GetHashcode methods of the properties, two instances of the same anonymous type are equal only if all their properties are equal. See Also How to: Handle Exceptions in Parallel Loops Send Feedback on this topic to Microsoft. View this topic online in your default browser.

The ParallelFor() and ForEach() overloads do not have any special mechanism to handle exceptions that might be thrown. In this respect, they resemble regularfor and foreach loops (For and For Each in Visual Basic). When you add your own exception-handling logic to parallel loops, handle the case in which similar exceptions might be thrown on multiple threads concurrently, and the case in which an exception thrown on one thread causes another exception to be thrown on another thread. You can handle both cases by wrapping all exceptions from the loop in a System. AggregateException. The following example shows one possible approach.

Note When "Just My Code" is enabled, Visual Studio in some cases will break on the line that throws the exception and display an error message that says "exception not handled by user code." This error is benign. You can press F5 to continue from it, and see the exception-handling behavior that is demonstrated in the example below. To prevent Visual Studio from breaking on the first error, just uncheck the "Just My Code" checkbox under Tools, Options, Debugging, General.

Example

In this example, all exceptions are caught and then wrapped in an System. AggregateException which is thrown. The caller can decide which exceptions to handle. JavaScript C# C++ F# JScript VB Copy to Clipboard
class ExceptionDemo2 { static void Main(string[] args) { // Create some random data to process in parallel. // There is a good probability this data will cause some exceptions to be thrown. byte[] data = new byte[5000]; Random r = new Random(); r.NextBytes(data); try { ProcessDataInParallel(data); } catch (AggregateException ae) { // This is where you can choose which exceptions to handle. foreach (var ex in ae.InnerExceptions) { if (ex is ArgumentException) Console.WriteLine(ex.Message); else throw ex; } } Console.WriteLine("Press any key to exit."); Console.ReadKey(); } private static void ProcessDataInParallel(byte[] data) { // Use ConcurrentQueue to enable safe enqueueing from multiple threads. var exceptions = new ConcurrentQueue<Exception>(); // Execute the complete loop and capture all exceptions. Parallel.ForEach(data, d =>

{ try { // Cause a few exceptions, but not too many. if (d < 0x3) throw new ArgumentException(String.Format("value is {0:x}. Elements must be greater than 0x3.", d)); else Console.Write(d + " "); } // Store the exception and continue with the loop. catch (Exception e) { exceptions.Enqueue(e); } }); // Throw the exceptions here after the loop completes. if (exceptions.Count > 0) throw new AggregateException(exceptions); } }

See Also

Step 1: Examining the Configuration Files


.NET Framework 4.5 Other Versions This topic has not yet been rated - Rate this topic Assembly binding behavior can be configured at different levels based on three XML files:

Application configuration file. Publisher policy file. Machine configuration file.

These files follow the same syntax and provide information such as binding redirects, the location of code, and binding modes for particular assemblies. Each configuration file can contain an <assemblyBinding> element that redirects the binding process. The child elements of the <assemblyBinding> element include the <dependentAssembly> element. The children of <dependentAssembly> element include the <assemblyIdentity> element, the <bindingRedirect> element, and the <codeBase> element. Note Configuration information can be found in the three configuration files; not all elements are valid in all configuration files. For example, binding mode and private path information can only be in the application configuration file. For a complete list of the information that is contained in each file, see Configuring Applications. Application Configuration File

First, the common language runtime checks the application configuration file for information that overrides the version information stored in the calling assembly's manifest. The application configuration file can be deployed with an application, but is not required for application execution. Usually the retrieval of this file is almost instantaneous, but in situations where the application base is on a remote computer, such as in an Internet Explorer Web-based scenario, the configuration file must be downloaded. For client executables, the application configuration file resides in the same directory as the application's executable and has the same base name as the executable with a .config extension. For example, the configuration file for C:\Program Files\Myapp\Myapp.exe is C:\Program Files\Myapp\Myapp.exe.config. In a browser-based scenario, the HTML file must use the <link> element to explicitly point to the configuration file. The following code provides a simple example of an application configuration file. This example adds a TextWriterTraceListener to the Listeners collection to enable recording debug information to a file.
<configuration> <system.diagnostics> <trace useGlobalLock="false" autoflush="true" indentsize="0"> <listeners> <add name="myListener" type="System.Diagnostics.TextWriterTraceListener, system version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" initializeData="c:\myListener.log" /> </listeners> </trace> </system.diagnostics> </configuration>

Publisher Policy File Second, the runtime examines the publisher policy file, if one exists. Publisher policy files are distributed by a component publisher as a fix or update to a shared component. These files contain compatibility information issued by the publisher of the shared component that directs an assembly reference to a new version. Unlike application and machine configuration files, publisher policy files are contained in their own assembly that must be installed in the global assembly cache. The following is an example of a Publisher Policy configuration file:
<configuration> <runtime> <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"> <dependentAssembly> <assemblyIdentity name="asm6" publicKeyToken="c0305c36380ba429" /> <bindingRedirect oldVersion="3.0.0.0" newVersion="2.0.0.0"/> </dependentAssembly>

</assemblyBinding> </runtime> </configuration>

To create an assembly, you can use the Al.exe (Assembly Linker) tool with a command such as the following:
Al.exe /link:asm6.exe.config /out:policy.3.0.asm6.dll /keyfile: compatkey.dat /v:3.0.0.0

compatkey.dat is a strong-name key file. This command creates a strong-named assembly you can place in the global assembly cache. Note Publisher policy affects all applications that use a shared component. The publisher policy configuration file overrides version information that comes from the application (that is, from the assembly manifest or from the application configuration file). If there is no statement in the application configuration file to redirect the version specified in the assembly manifest, the publisher policy file overrides the version specified in the assembly manifest. However, if there is a redirecting statement in the application configuration file, publisher policy overrides that version rather than the one specified in the manifest. A publisher policy file is used when a shared component is updated and the new version of the shared component should be picked up by all applications using that component. The settings in the publisher policy file override settings in the application configuration file, unless the application configuration file enforces safe mode. Safe Mode Publisher policy files are usually explicitly installed as part of a service pack or program update. If there is any problem with the upgraded shared component, you can ignore the overrides in the publisher policy file using safe mode. Safe mode is determined by the <publisherPolicy apply="yes|no"/> element, located only in the application configuration file. It specifies whether the publisher policy configuration information should be removed from the binding process. Safe mode can be set for the entire application or for selected assemblies. That is, you can turn off the policy for all assemblies that make up the application, or turn it on for some assemblies but not others. To selectively apply publisher policy to assemblies that make up an application, set <publisherPolicy apply=no/> and specify which assemblies you want to be affected using the <dependentAssembly> element. To apply publisher policy to all assemblies that make up the application, set <publisherPolicy apply=no/> with no dependent assembly elements. For more about configuration, see Configuration Files. Machine Configuration File

Third, the runtime examines the machine configuration file. This file, called Machine.config, resides on the local computer in the Config subdirectory of the root directory where the runtime is installed. This file can be used by administrators to specify assembly binding restrictions that are local to that computer. The settings in the machine configuration file take precedence over all other configuration settings; however, this does not mean that all configuration settings should be put in this file. The version determined by the administrator policy file is final, and cannot be overridden. Overrides specified in the Machine.config file affect all applications. For more information about configuration files, see Configuration Files.

<requiredRuntime> Element
.NET Framework 4.5 Other Versions This topic has not yet been rated - Rate this topic Specifies that the application supports only version 1.0 of the common language runtime. <configuration> Element <startup> Element <requiredRuntime> Element
<requiredRuntime version="runtime version" safemode="true|false"/>

Attributes and Elements The following sections describe attributes, child elements, and parent elements. Attributes Attribute Optional attribute. version A string value that specifies the version of the .NET Framework that this application supports. The string value must match the directory name found under the .NET Framework installation root. The contents of the string value are not parsed. Optional attribute. Specifies whether the runtime startup code searches the registry to determine the runtime version. Description

safemode

safemode Attribute Value Description false The runtime startup code looks in the registry. This is the default value.

true

The runtime startup code does not look in the registry.

Child Elements None. Parent Elements Description The root element in every configuration file used by the common language runtime configuration and .NET Framework applications. startup Contains the <requiredRuntime> element. Remarks Applications built to support only version 1.0 of the runtime must use the <requiredRuntime> element. Applications built using version 1.1 or later of the runtime must use the <supportedRuntime> element. Note If you use the CorBindToRuntimeByCfg function to specify the configuration file, you must use the <requiredRuntime> element for all versions of the runtime. The <supportedRuntime> element is ignored when you use CorBindToRuntimeByCfg. The version attribute string must match the installation folder name for the specified version of the .NET Framework. This string is not interpreted. If the runtime startup code does not find a matching folder, the runtime is not loaded; the startup code shows an error message and quits. Note The startup code for an application that is hosted in Microsoft Internet Explorer ignores the <requiredRuntime> element. Example The following example shows how to specify the runtime version in a configuration file.
<configuration> <startup> <requiredRuntime version="v1.0.3705" safemode="true"/> </startup> </configuration>

Element

Specifying an Assembly's Location


.NET Framework 4.5 Other Versions

0 out of 1 rated this helpful - Rate this topic There are two ways to specify an assembly's location:

Using the <codeBase> element. Using the <probing> element.

You can also use the .NET Framework Configuration Tool (Mscorcfg.msc) to specify assembly locations or specify locations for the common language runtime to probe for assemblies. Using the <codeBase> Element You can use the <codeBase> element only in machine configuration or publisher policy files that also redirect the assembly version. When the runtime determines which assembly version to use, it applies the code base setting from the file that determines the version. If no code base is indicated, the runtime probes for the assembly in the normal way. For details, see How the Runtime Locates Assemblies. The following example shows how to specify an assembly's location.
<configuration> <runtime> <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"> <dependentAssembly> <assemblyIdentity name="myAssembly" publicKeyToken="32ab4ba45e0a69a1" culture="en-us" /> <codeBase version="2.0.0.0" href="http://www.litwareinc.com/myAssembly.dll"/> </dependentAssembly> </assemblyBinding> </runtime> </configuration>

The version attribute is required for all strong-named assemblies but should be omitted for assemblies that are not strong-named. The <codeBase> element requires the href attribute. You cannot specify version ranges in the <codeBase> element. Note If you are supplying a code base hint for an assembly that is not strong-named, the hint must point to the application base or a subdirectory of the application base directory. Using the <probing> Element The runtime locates assemblies that do not have a code base by probing. For more information about probing, see How the Runtime Locates Assemblies.

You can use the <probing> element in the application configuration file to specify subdirectories the runtime should search when locating an assembly. The following example shows how to specify directories the runtime should search.
<configuration> <runtime> <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"> <probing privatePath="bin;bin2\subbin;bin3"/> </assemblyBinding> </runtime> </configuration>

The privatePath attribute contains the directories that the runtime should search for assemblies. If the application is located at C:\Program Files\MyApp, the runtime will look for assemblies that do not specify a code base in C:\Program Files\MyApp\Bin, C:\Program Files\MyApp\Bin2\Subbin, and C:\Program Files\MyApp\Bin3. The directories specified in privatePath must be subdirectories of the application base directory.

<applicationPool> Element (Web Settings)


.NET Framework 4.5 Other Versions 1 out of 2 rated this helpful - Rate this topic Specifies configuration settings that are used by ASP.NET to manage process-wide behavior when an ASP.NET application is running in Integrated mode on IIS 7.0 or a later version. Important This element and the feature it supports only work if your ASP.NET application is hosted on IIS 7.0 or later versions. <configuration> Element <system.web> Element (Web Settings) <applicationPool> Element (Web Settings)
<applicationPool maxConcurrentRequestsPerCPU="5000" maxConcurrentThreadsPerCPU="0" requestQueueLimit="5000" />

Attributes and Elements The following sections describe attributes, child elements, and parent elements. Attributes Description Specifies how many simultaneous requests ASP.NET allows maxConcurrentRequestsPerCPU per CPU. Attribute

Specifies how many simultaneous threads can be running for an application pool for each CPU. This provides an alternative way to control ASP.NET concurrency, because you can limit the number of managed threads that can be used per CPU to maxConcurrentThreadsPerCPU serve requests. By default this setting is 0, which means that ASP.NET does not limit the number of threads that can be created per CPU, although the CLR thread pool also limits the number of threads that can be created. Specifies the maximum number of requests that can be queued for ASP.NET in a single process. When two or more ASP.NET requestQueueLimit applications run in a single application pool, the cumulative set of requests being made to any application in the application pool is subject to this setting. Child Elements None. Parent Elements Element Description <system.web> Contains information about how ASP.NET interacts with a host application. Remarks When you run IIS 7.0 or a later version in Integrated mode, this element combination lets you configure how ASP.NET manages threads and queues requests when the application is hosted in an IIS application pool. If you run IIS 6 or you run IIS 7.0 in Classic mode or in ISAPI mode, these settings are ignored. The applicationPool settings apply to all application pools that run on a particular version of the .NET Framework. The settings are contained in an aspnet.config file. There is a version of this file for versions 2.0 and 4.0 of the .NET Framework. (Versions 3.0 and 3.5 of the .NET Framework share the aspnet.config file with version 2.0.) Important If you run IIS 7.0 on Windows 7, you can configure a separate aspnet.config file for every application pool. This lets you tailor the performance of the threads for each application pool. For the maxConcurrentRequestsPerCPU setting, the default setting of "5000" in the .NET Framework 4 effectively turns off request throttling that is controlled by ASP.NET, unless you actually have 5000 or more requests per CPU. The default setting depends instead on the CLR thread-pool to automatically manage concurrency per CPU. Applications that make extensive use of asynchronous request processing, or that have many long-running requests blocked on network I/O, will benefit from the increased default limit in the .NET Framework 4. Setting maxConcurrentRequestsPerCPU to zero turns off the use of managed threads for processing

ASP.NET requests. When an application runs in an IIS application pool, requests stay on the IIS I/O thread and therefore concurrency is throttled by IIS thread settings. The requestQueueLimit setting works the same way as the requestQueueLimit attribute of the processModel element, which is set in the Web.config files for ASP.NET applications. However, the requestQueueLimit setting in an aspnet.config file overrides the requestQueueLimit setting in a Web.config file. In other words, if both attributes are set (by default, this is true), the requestQueueLimit setting in the aspnet.config file takes precedence. Example The following example shows how to configure ASP.NET process-wide behavior in the aspnet.config file in the following circumstances:

The application is hosted in an IIS 7.0 application pool. IIS 7.0 is running in Integrated mode. The application is using the .NET Framework 3.5 SP1 or a later version.

The values in the example are the default values.


<configuration> <system.web> <applicationPool maxConcurrentRequestsPerCPU="5000" maxConcurrentThreadsPerCPU="0" requestQueueLimit="5000" /> </system.web> </configuration>

Element Information Namespace Schema Name Validation File

<system.web> Element (Web Settings)


.NET Framework 4.5 Other Versions This topic has not yet been rated - Rate this topic Contains information about how the ASP.NET hosting layer manages process-wide behavior. <configuration> Element <system.web> Element (Web Settings)
<system.web> </system.web>

Attributes and Elements

The following sections describe attributes, child elements, and parent elements. Attributes None. Child Elements Description Specifies configuration settings for IIS application pools in an aspnet.config <applicationPool> file. Parent Elements Description Specifies the root element in every configuration file that is used by the <configuration> common language runtime and .NET Framework applications. Remarks The system.web element and its child applicationPool element were added to the .NET Framework as of .NET Framework 3.5 SP1. When you run IIS 7.0 or later versions in Integrated mode, this element combination lets you configure how ASP.NET manages threads and how it queues requests when ASP.NET is hosted in an IIS application pool. If you run IIS 7.0 or later versions in Classic or ISAPI mode, these settings are ignored. Example The following example shows how to configure ASP.NET process-wide behavior in the aspnet.config file when ASP.NET is hosted in an IIS application pool. The example assumes that IIS is running in Integrated mode and that the application is using the .NET Framework 3.5 SP1 or a later version. This behavior does not occur in versions of the .NET Framework earlier than the .NET Framework 3.5 SP1. The values in the example are the default values.
<configuration> <system.web> <applicationPool maxConcurrentRequestsPerCPU="5000" maxConcurrentThreadsPerCPU="0" requestQueueLimit="5000" /> </system.web> </configuration>

Element

Element

Element Information Namespace Schema Name Validation File Can be Empty

<codeBase> Element
.NET Framework 4.5 Other Versions 1 out of 2 rated this helpful - Rate this topic Specifies where the common language runtime can find an assembly. <configuration> Element <runtime> Element <assemblyBinding> Element for <runtime> <dependentAssembly> Element <codeBase> Element
<codeBase version="Assembly version" href="URL of assembly"/>

Attributes and Elements The following sections describe attributes, child elements, and parent elements. Attributes Attribute Required attribute. href Specifies the URL where the runtime can find the specified version of the assembly. Required attribute. version Specifies the version of the assembly the codebase applies to. The format of an assembly version number is major.minor.build.revision. Description

version Attribute Value Description Valid values for each part of the version number are 0 to 65535. Not applicable. Child Elements None. Parent Elements Element Description

Defines a collection of build providers used to compile custom resource files. You can have any number of build providers. compilation Configures all the compilation settings that ASP.NET uses. The root element in every configuration file used by the common language configuration runtime and .NET Framework applications. System.web Specifies the root element for the ASP.NET configuration section. Remarks buildproviders For the runtime to use the <codeBase> setting in a machine configuration file or publisher policy file, the file must also redirect the assembly version. Application configuration files can have a codebase setting without redirecting the assembly version. After determining which assembly version to use, the runtime applies the codebase setting from the file that determines the version. If no codebase is indicated, the runtime probes for the assembly in the usual way. If the assembly has a strong name, the codebase setting can be anywhere on the local intranet or the Internet. If the assembly is a private assembly, the codebase setting must be a path relative to the application's directory. For assemblies without a strong name, version is ignored and the loader uses the first appearance of <codebase> inside <dependentAssembly>. If there is an entry in the application configuration file that redirects binding to another assembly, the redirection will take precedence even if the assembly version doesnt match the binding request. Example The following example shows how to specify where the runtime can find an assembly.
<configuration> <runtime> <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"> <dependentAssembly> <assemblyIdentity name="myAssembly" publicKeyToken="32ab4ba45e0a69a1" culture="neutral" /> <codeBase version="2.0.0.0" href="http://www.litwareinc.com/myAssembly.dll"/> </dependentAssembly> </assemblyBinding> </runtime> </configuration>

<assemblyBinding> Element for <configuration>


.NET Framework 4.5 Other Versions 0 out of 1 rated this helpful - Rate this topic

Specifies assembly binding policy at the configuration level. <configuration> Element <assemblyBinding> Element for <configuration>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"> </assemblyBinding>

Attributes and Elements The following sections describe attributes, child elements, and parent elements. Attributes Attribute Required attribute. xmlns Specifies the XML namespace required for assembly binding. Use the string "urn:schemas-microsoft-com:asm.v1" as the value. Description

Child Elements Element Description <linkedConfiguration> Element Specifies a configuration file to include. Parent Elements Element <configuration> Element Remarks Description The root element in every configuration file used by the common language runtime and .NET Framework applications.

The <linkedConfiguration> Element simplifies the management of component assemblies by allowing application configuration files to include assembly configuration files in well-known locations, rather than duplicating assembly configuration settings. Note The <linkedConfiguration> element is not supported for applications with Windows side-by-side manifests.

Runtime Settings Schema


.NET Framework 4.5 Other Versions This topic has not yet been rated - Rate this topic

Runtime settings specify how the common language runtime handles garbage collection and the version of an assembly to use in configuration files. <configuration> <runtime> <alwaysFlowImpersonationPolicy> <appDomainManagerAssembly> <appDomainManagerType> <appDomainResourceMonitoring> <assemblyBinding> Element for <runtime> <dependentAssembly> <assemblyIdentity> <bindingRedirect> <codeBase> <probing> <publisherPolicy> <qualifyAssembly> <bypassTrustedAppStrongNames> <CompatSortNLSVersion> <developmentMode> <disableCachingBindingFailures> <disableCommitThreadStack> <disableFusionUpdatesFromADManager> <enforceFIPSPolicy> <etwEnable>

<forcePerformanceCounterUniqueSharedMemoryReads> <gcAllowVeryLargeObjects> <gcConcurrent> <GCCpuGroup> <gcServer> <generatePublisherEvidence> <legacyCorruptedStateExceptionsPolicy> <legacyImpersonationPolicy> <loadfromRemoteSources> <NetFx40_LegacySecurityPolicy> <NetFx40_PInvokeStackResilience> <NetFx45_CultureAwareComparerGetHashCode_LongStrings> <PreferComInsteadOfManagedRemoting> <relativeBindForResources> <shadowCopyVerifyByTimeStamp> <relativeBindForResources> <supportPortability> <system.runtime.caching> <memoryCache> <namedCaches> <add> <clear> <remove>

<Thread_UseAllCpuGroups> <ThrowUnobservedTaskExceptions> <TimeSpan_LegacyFormatMode> <UseRandomizedStringHashAlgorithm> <UseSmallInternalThreadStacks> Element <add> Description Adds a named cache to the namedCaches collection for a memory cache. Specifies that the Windows identity always flows across asynchronous points, regardless of how impersonation was performed. Specifies the assembly that provides the application domain manager for the default application domain in the process. Specifies the type that serves as the application domain manager for the default application domain. Instructs the runtime to collect statistics on all application domains in the process for the life of the process. Contains information about assembly version redirection and the locations of assemblies. Contains identifying information about an assembly. Redirects one assembly version to another. Specifies whether strong name verification for trusted assemblies should be bypassed. Clears the namedCaches collection for a memory cache.

<alwaysFlowImpersonationPolicy>

<appDomainManagerAssembly>

<appDomainManagerType>

<appDomainResourceMonitoring>

<assemblyBinding> Element for <runtime> <assemblyIdentity> <bindingRedirect> <bypassTrustedAppStrongNames> <clear>

<codeBase>

<CompatSortNLSVersion>

<dependentAssembly>

<developmentMode>

<disableCachingBindingFailures>

<disableCommitThreadStack>

<disableFusionUpdatesFromADManager>

<enforceFIPSPolicy>

<etwEnable>

<forcePerformanceCounterUniqueSharedMemoryReads>

Specifies where the runtime can find an assembly. Specifies that the runtime should use legacy sorting behavior when performing string comparisons Encapsulates binding policy and assembly location for each assembly. Specifies whether the runtime searches for assemblies in directories specified by the DEVPATH environment variable. Specifies whether the caching of binding failures, which is the default behavior in the .NET Framework 2.0, is disabled. Specifies whether the full thread stack is committed when a thread starts. Specifies whether the default behavior, which is to allow the runtime host to override configuration settings for an application domain, is disabled. Specifies whether to enforce a computer configuration requirement that cryptographic algorithms must comply with the Federal Information Processing Standards (FIPS). Specifies whether to enable event tracing for Windows (ETW) for common language runtime events. Specifies whether PerfCounter.dll uses the CategoryOptions registry setting in a .NET Framework version 1.1 application to determine whether to load performance counter data from category-specific shared

<gcAllowVeryLargeObjects>

<gcConcurrent>

<GCCpuGroup>

<gcServer>

<generatePublisherEvidence>

<legacyCorruptedStateExceptionsPolicy>

<legacyImpersonationPolicy>

<loadfromRemoteSources>

<memoryCache>

<namedCaches>

<NetFx40_LegacySecurityPolicy>

<NetFx40_PInvokeStackResilience>

memory or global memory. On 64-bit platforms, enables arrays that are greater than 2 gigabytes (GB) in total size. Specifies whether the runtime runs garbage collection concurrently. Specifies whether garbage collection supports multiple CPU groups. Specifies whether the common language runtime runs server garbage collection. Specifies whether the runtime uses code access security (CAS) publisher policy. Specifies whether the runtime allows managed code to catch access violations and other corrupted state exceptions. Specifies that the Windows identity does not flow across asynchronous points, regardless of the flow settings for the execution context on the current thread. Specifies whether assemblies from remote sources are loaded as full trust. Defines an element that is used to configure a cache that is based on the MemoryCache class. Contains a collection of configuration settings for the namedCache instance. Specifies whether the runtime uses legacy code access security (CAS) policy. Specifies whether the runtime automatically fixes incorrect platform invoke declarations at run time, at the cost of slower transitions between managed

and unmanaged code. Specifies whether the runtime uses a fixed amount of memory <NetFx45_CultureAwareComparerGetHashCode_LongStrings> to calculate hash codes for the StringComparer.GetHashCode method. Specifies that the runtime will use COM interop instead of <PreferComInsteadOfManagedRemoting> remoting across application domain boundaries. Specifies subdirectories that the <probing> runtime searches when loading assemblies. Specifies whether the runtime <publisherPolicy> applies publisher policy. Specifies the full name of the assembly that should be <qualifyAssembly> dynamically loaded when a partial name is used. Optimizes the probe for satellite <relativeBindForResources> assemblies. Removes a named cache entry <remove> from the namedCaches collection for a memory cache. Contains information about <runtime> assembly binding and the behavior of garbage collection. Specifies whether shadow copying uses the default startup behavior introduced in the <shadowCopyTimeStampVerification> .NET Framework 4, or reverts to the startup behavior of earlier versions of the .NET Framework. Specifies that an application can reference the same assembly in two different implementations of the .NET <supportPortability> Framework, by disabling the default behavior that treats the assemblies as equivalent for application portability purposes. <system.runtime.caching> Provides configuration

<Thread_UseAllCpuGroups>

<ThrowUnobservedTaskExceptions>

<TimeSpan_LegacyFormatMode>

<UseRandomizedStringHashAlgorithm>

<UseSmallInternalThreadStacks>

information for the default inmemory object cache. Specifies whether the runtime distributes managed threads across all CPU groups. Specifies whether unhandled task exceptions should terminate a running process. Specifies whether the runtime uses legacy formatting for TimeSpan values. Specifies whether the runtime calculates hash codes for strings on a per application domain basis. Requests that the runtime use explicit stack sizes when it creates certain threads that it uses internally, instead of the default stack size.

See Also

<configuration> Element
.NET Framework 4.5 Other Versions 2 out of 5 rated this helpful - Rate this topic The root element in every configuration file used by the common language runtime and .NET Framework applications. <configuration>
<configuration> <!-- configuration settings --> </configuration>

Child Elements Element <assemblyBinding> Element for <configuration> Startup Settings Schema Runtime Settings Schema Remoting Settings Schema

Description Specifies assembly binding policy at the configuration level. All elements in the startup settings schema. All elements in the runtime settings schema. All elements in the remoting settings schema.

Network Settings Schema Cryptography Settings Schema Configuration Sections Schema Trace and Debug Settings Schema ASP.NET Settings Schema

All elements in the network settings schema. All elements in the crypto settings schema. All elements in the configuration section settings schema. All elements in the trace and debug settings schema. All elements in the ASP.NET configuration schema, which includes elements for configuring ASP.NET Web sites and applications. Used in Web.config files.

XML Web Services Settings All elements in the Web services settings schema. Schema All elements in the Web settings schema, which includes elements Web Settings Schema for configuring how ASP.NET works with a host application such as IIS. Used in aspnet.config files.

Web Services Settings Schema


.NET Framework 4 Other Versions This topic has not yet been rated - Rate this topic This topic is specific to a legacy technology. XML Web services and XML Web service clients should now be created using Windows Communication Foundation . The Web services settings schema defines configuration file elements that control the behavior of ASP.NET Web services and their clients. The parent element is <webServices>. By default, the <webServices> element and its descendants are applied to any Web service or proxy class to which the configuration applies. The configuration is applied according to the application type, as follows:

ASP.NET Web application (service or client): Refer to ASP.NET Configuration File Hierarchy and Inheritance concerning the standard rules for configuration inheritance, scoping, and precedence within an ASP.NET Web application. The <webServices> element typically is placed in a Web.config file. Stand-alone .NET Framework application (client only): Refer to Application Configuration Files. The <webServices> element typically is placed in the application configuration file.

The <webServices> element and its descendants are applied to the following kinds of classes:

A Web service class that derives from WebService.

A client proxy class that derives indirectly from WebClientProtocol.

A <webServices> element can be applied to both a Web service and a client where a Web application contains both entities. <configuration> <system.web> <webServices> <protocols> <add> <remove> <clear> <serviceDescriptionFormatExtensionTypes> <add> <remove> <clear> <soapExtensionTypes> <add> <remove> <clear> <soapExtensionImporterTypes> <add> <remove> <clear> <soapExtensionReflectorTypes> <add> <remove> <clear> <wsdlHelpGenerator> Element <add> for <protocols> Description Adds a specified protocol that an ASP.NET Web service can use to receive request data sent from a client and to return response data. Adds a specified service description format extension (SDFE) class that defines how to extend the service descriptions (WSDL documents) generated for Web services. Adds a specified SOAP extension class that provides extended processing of SOAP messages on the Web service or client. Adds a specified SOAP extension importer class, which extends the client proxy generation process for use with a service description format extension (SDFE).

<add> for <serviceDescriptionFormatExtensionTypes>

<add> for <soapExtensionTypes>

<add> for <soapExtensionImporterTypes>

Adds a specified SOAP extension reflector class, which extends the service description (WSDL <add> for <soapExtensionReflectorTypes> document) generation process for use with a service description format extension (SDFE). Removes all references to items appropriate to <clear> the parent tag. Specifies the protocols that an ASP.NET Web service can use to receive request data sent from a client and return response data. A protocol can <protocols> be used to associate request data with a method and its parameters and to associate response data with the method and its return value. Removes a specified protocol for handling <remove> for <protocols> request and response data from within the scope of the configuration file. Removes a specified service description format <remove> for extension (SDFE) class from within the scope of <serviceDescriptionFormatExtensionTypes> the configuration file. Removes a specified SOAP extension class from <remove> for <soapExtensionTypes> within the scope of the configuration file. Removes a specified SOAP extension importer <remove> for <soapExtensionImporterTypes> class from within the scope of the configuration file. Removes a specified SOAP extension reflector <remove> for class from within the scope of the configuration <soapExtensionReflectorTypes> file. Specifies the service description format extension (SDFE) classes used to extend the WSDL <serviceDescriptionFormatExtensionTypes> documents generated for Web services. SDFE classes provide a means of describing SOAP extensions. Specifies SOAP extension importer classes, which extend the client proxy generation process. <soapExtensionImporterTypes> For use with service description format extensions (SDFEs). Specifies SOAP extension reflector classes, which extend the service description (WSDL <soapExtensionReflectorTypes> document) generation process. For use with service description format extensions (SDFEs). Specifies the SOAP extensions used to inspect or modify the SOAP message during processing on <soapExtensionTypes> the Web service or client. SOAP extensions augment the functionality of Web services. <webServices> Controls the settings of Web services deployed

<wsdlHelpGenerator>

using ASP.NET and of Web service clients running on the .NET Framework. Specifies the Web service Help page (an .aspx file) that is displayed to a browser when the browser navigates directly to an ASMX Web services page.

Assemblies in the Common Language Runtime


.NET Framework 4.5 Other Versions 6 out of 8 rated this helpful - Rate this topic Assemblies are the building blocks of .NET Framework applications; they form the fundamental unit of deployment, version control, reuse, activation scoping, and security permissions. An assembly is a collection of types and resources that are built to work together and form a logical unit of functionality. An assembly provides the common language runtime with the information it needs to be aware of type implementations. To the runtime, a type does not exist outside the context of an assembly. An assembly performs the following functions:

It contains code that the common language runtime executes. Microsoft intermediate language (MSIL) code in a portable executable (PE) file will not be executed if it does not have an associated assembly manifest. Note that each assembly can have only one entry point (that is, DllMain, WinMain, or Main). It forms a security boundary. An assembly is the unit at which permissions are requested and granted. For more information about security boundaries as they apply to assemblies, see Assembly Security Considerations. It forms a type boundary. Every type's identity includes the name of the assembly in which it resides. A type called MyType that is loaded in the scope of one assembly is not the same as a type called MyType that is loaded in the scope of another assembly. It forms a reference scope boundary. The assembly's manifest contains assembly metadata that is used for resolving types and satisfying resource requests. It specifies the types and resources that are exposed outside the assembly. The manifest also enumerates other assemblies on which it depends. It forms a version boundary. The assembly is the smallest versionable unit in the common language runtime; all types and resources in the same assembly are versioned as a unit. The assembly's manifest describes the version dependencies you specify for any dependent assemblies. For more information about versioning, see Assembly Versioning. It forms a deployment unit. When an application starts, only the assemblies that the application initially calls must be present. Other assemblies, such as localization resources or assemblies containing utility classes, can be retrieved on demand. This allows applications to be kept simple and thin when first downloaded. For more information about deploying assemblies, see Deploying Applications.

It is the unit at which side-by-side execution is supported. For more information about running multiple versions of an assembly, see Assemblies and Side-by-Side Execution.

Assemblies can be static or dynamic. Static assemblies can include .NET Framework types (interfaces and classes), as well as resources for the assembly (bitmaps, JPEG files, resource files, and so on). Static assemblies are stored on disk in portable executable (PE) files. You can also use the .NET Framework to create dynamic assemblies, which are run directly from memory and are not saved to disk before execution. You can save dynamic assemblies to disk after they have executed. There are several ways to create assemblies. You can use development tools, such as Visual Studio 2005, that you have used in the past to create .dll or .exe files. You can use tools provided in the Windows Software Development Kit (SDK) to create assemblies with modules created in other development environments. You can also use common language runtime APIs, such as Reflection.Emit, to create dynamic assemblies. Related Topics Title Assembly Benefits Assembly Contents Assembly Manifest Global Assembly Cache Strong-Named Assemblies Assembly Security Considerations Assembly Versioning

Description Describes how assemblies help solve versioning problems and DLL conflicts. Describes the elements that make up an assembly. Describes the data in the assembly manifest, and how it is stored in assemblies. Describes the global assembly cache and how it is used with assemblies. Describes the characteristics of strong-named assemblies. Discusses how security works with assemblies.

Provides an overview of the .NET Framework versioning policy. Assembly Placement Discusses where to locate assemblies. Assemblies and Side-by-Side Provides an overview of using multiple versions of the runtime Execution or of an assembly simultaneously. Programming with Assemblies Describes how to create, sign, and set attributes on assemblies. Emitting Dynamic Methods and Describes how to create dynamic assemblies. Assemblies How the Runtime Locates Describes how the .NET Framework resolves assembly Assemblies references at run time. Reference

Assembly Manifest

.NET Framework 4.5 Other Versions

1 out of 3 rated this helpful - Rate this topic Every assembly, whether static or dynamic, contains a collection of data that describes how the elements in the assembly relate to each other. The assembly manifest contains this assembly metadata. An assembly manifest contains all the metadata needed to specify the assembly's version requirements and security identity, and all metadata needed to define the scope of the assembly and resolve references to resources and classes. The assembly manifest can be stored in either a PE file (an .exe or .dll) with Microsoft intermediate language (MSIL) code or in a standalone PE file that contains only assembly manifest information. The following illustration shows the different ways the manifest can be stored. Types of assemblies

For an assembly with one associated file, the manifest is incorporated into the PE file to form a single-file assembly. You can create a multifile assembly with a standalone manifest file or with the manifest incorporated into one of the PE files in the assembly. Each assembly's manifest performs the following functions:

Enumerates the files that make up the assembly. Governs how references to the assembly's types and resources map to the files that contain their declarations and implementations. Enumerates other assemblies on which the assembly depends. Provides a level of indirection between consumers of the assembly and the assembly's implementation details. Renders the assembly self-describing.

Assembly Manifest Contents

The following table shows the information contained in the assembly manifest. The first four itemsthe assembly name, version number, culture, and strong name informationmake up the assembly's identity. Information Assembly name Description A text string specifying the assembly's name. A major and minor version number, and a revision and build number. The Version number common language runtime uses these numbers to enforce version policy. Information on the culture or language the assembly supports. This information should be used only to designate an assembly as a satellite Culture assembly containing culture- or language-specific information. (An assembly with culture information is automatically assumed to be a satellite assembly.) Strong name The public key from the publisher if the assembly has been given a strong information name. A hash of each file contained in the assembly and a file name. Note that all List of all files in files that make up the assembly must be in the same directory as the file the assembly containing the assembly manifest. Information used by the runtime to map a type reference to the file that Type reference contains its declaration and implementation. This is used for types that are information exported from the assembly. A list of other assemblies that are statically referenced by the assembly. Each Information on reference includes the dependent assembly's name, assembly metadata referenced (version, culture, operating system, and so on), and public key, if the assemblies assembly is strong named. You can add or change some information in the assembly manifest by using assembly attributes in your code. You can change version information and informational attributes, including Trademark, Copyright, Product, Company, and Informational Version. For a complete list of assembly attributes, see Setting Assembly Attributes. See Also }); wi.ko.printPageUsage = ko.computed(function() { return wi.ko.numberOfWebsitePages() + "/" + wi.ko.numberOfAllowedPages().toString(); }); return wi; }); </script> <script> define('napsoc', ['modules/util/util.persistence'], function (PersistenceModel) { var napsocData = PersistenceModel.load({"Name":"Goblueaz","Address":"4218 E montgomery rd Cave Creek AZ 85331 us","Phone":null,"Email":"Kdaly480@gmail.com","FacebookUrl":"","TwitterUsername":""}, 'napsoc');

napsocData.themeNapsoc = PersistenceModel.load({"Name":"Site Name","Address":"777 E WebsiteBuilder St, World Wide, WB 12345","Phone":"(111) 5555555","Email":"email@builderamazing.com","FacebookUrl":"https://www.facebook.com/seeam azingplaces","TwitterUsername":"goamazingplaces"}); return napsocData; }); </script> <script> require(["modules/gomez/gomez"], function (gomez) { gomez.init("designer"); }); </script> <script> require(["jq!starfield/jquery.mod", "modules/wsb/wsb"], function($, wsb) { $(function () { wsb.configModule({ $container: $("body").children(".wsb").first() }); wsb.initModule(); }); }); </script> </head> <body> <div class="wsb"> <div class="wsb-loading"> <img src="//img3.wsimg.com/wst/v7/WSB7_J_20130808_0907_Blogging_58/images/progress.gif" style="height:1.2em;" /> Loading... </div> </div> <!-- Fastball Traffic Logging --> <img src="//img.godaddy.com/image.aspx?sitename=app7.websitetonight.com&server=P3PWWSBA PP09&page=/WSB7_J_20130808_0907_Blogging_58/designer&referrer=https%3a%2f%2fapp7 .websitetonight.com%2fcontrolpanel&shopper=64984740&privatelabelid=1&isc=&ci=&status= 200&querystring=" style="border: none;" width="0" height="0" alt="" /> <!-- Fastball Traffic Logging End --> <script type="text/javascript"> var _gaDataLayer = _gaDataLayer || []; _gaDataLayer.push({ 'shopperId': '64984740' }); _gaDataLayer.push({ 'privateLabelId': '1' }); _gaDataLayer.push({ 'server': 'P3PWWSBAPP09' }); var _gaq = _gaq || []; _gaq.push(['_setDomainName', 'websitetonight.com']);

</script> <!-- Google Tag Manager --> <noscript> <iframe src="//www.googletagmanager.com/ns.html?id=GTM-SXRF" height="0" width="0" style="display:none;visibility:hidden"></iframe> </noscript> <script> (function (w, d, s, l, i) { w[l] = w[l] || []; w[l].push({ 'gtm.start': new Date().getTime(), event: 'gtm.js' }); var f = d.getElementsByTagName(s)[0], j = d.createElement(s), dl = l != 'dataLayer' ? '&l=' + l : ''; j.async = true; j.src = '//www.googletagmanager.com/gtm.js?id=' + i + dl; f.parentNode.insertBefore(j, f); })(window, document, 'script', '_gaDataLayer', 'GTM-SXRF'); </script> <!-- End Google Tag Manager --> <div id="sessionTimeout" class="clearfix"></div> <script> require(["modules/session/sessionTimeout"], function (session) { $(function () { session.start(180 - 2, "https://app7.websitetonight.com/home/keepalive", "https://login.websitetonight.com/"); }); }); </script> <div id="sessionTimeout"></div> <script> require(["modules/session/sessionCheck"], function (sessionCheck) { sessionCheck.init(); }); </script> <script type="text/html" id="template-session-check"> <div class="wsb-session-alert"> <p>Ahem. It looks like youve logged in to your Website Builder in another browser or window.</p> <p>Were refreshing this session to sync with that one.</p> </div> </script> <script> require(["modules/session/sso"], function (sso) {

$(function () { sso.keepAlive("https://idp.godaddy.com/keepalive.aspx"); }); }); </script> <script type="text/html" id="template-addthis-growl-title"> AddThis Widget Removed </script> <script type="text/html" id="template-addthis-growl-message"> You can always change this later in &quot;Settings&quot; </script> <script type="text/html" id="template-addthis-growl-error-title"> Yikes! We hit a snag... </script> <script type="text/html" id="template-addthis-growl-error-message"> Please try again or <a class='wsb-support-link' href='/help/support' target='_blank'> contact customer support</a>. </script> <div id="addthis-context-html" style="display: none;"> <h3 class="sf-dialog-title2" style="cursor: text !important;">Help us help you get found!</h3> <div class="sf-dialog-content2"> <p>Pump up your site traffic. How? By letting visitors share your site on social networks.</p> <a class="btn btn-success" style="margin-right: 20px;" href="#" data-aid="addthis-ok" databind="click: closeContext">OK</a><a class="sf-dialog-link" href="#" data-aid="addthisnothanks" data-bind="click: disable">No thanks (remove it)</a> <p style="font-size: 12px; color: #797979; padding-top: 20px;">You can always change this later in &quot;Settings&quot;</p> </div> </div> <div id="addthis-overlay" style="position: fixed; top: 20%; left: 48px; height:242px; width: 1px; background-color: transparent; display: none;"></div> <script> require(["modules/social/addthis/addthissmartlayer"], function (addthissmartlayer) { addthissmartlayer.init({ 'share': { 'mobile': false } }); }); </script></body> </html>

Publishing a Web Site Based on an ASP.NET Starter Kit


Date Submitted: 7-25-2013 ASP.NET starter kits can be downloaded from the ASP.NET website.

The following instructions use the ASP Time Tracker starter kit as an example. However, you can use this upload procedure for any starter kit that uses a 2005 SQL database (running from a local MDF file or a standalone server). The directions assume the following:

You have downloaded an ASP.NET starter kit and developed a web application locally. The database uses a local MDF file (starter kit default setting). The Database Publishing Wizard client is installed on your local machine. You have at least one Microsoft 2005 SQL Server database setup on your hosting account. Your database has remote access enabled. For more information, see Connecting Remotely to Shared Hosting Databases.

To Publish Your Database Web Application to the Hosting Server: 1. Create a Connection to your database from Visual Web Developer. 1. In Visual Web Developer, open the Database Explorer tab. 2. Open a connection to your local SQL Server. 1. Right-click Data Connections and select add Connection. 2. If the Change Data Source dialog comes up, choose Microsoft SQL Server. Leave the default setting for Data Provider. 3. Press OK. 4. On the Add Connection Dialog, enter your database's host name. For more information, see Locating Your Database's Host Name. 5. Select Attach a database file. 6. Click Browse. 7. On the file dialog, locate your MDF and press Open. 8. Enter a logical file name. This should be easily associated with your project. 9. Click OK. 2. Right-click the entry for your website Database. Select Publish to Provider. This will launch the Database Publishing Wizard. 3. Follow the instructions for Setting up a SQL Server Database on Your Hosting Account. 4. Modify the default connection strings section of your web.config file. 5. Add the following Time Tracker connection string entry below to your web.config file, making the same substitutions as in the previous step: <add name="aspnet_staterKits_TimeTracker" connectionString=" Server=whsql-v04.prod.mesa1.secureserver.net; Database=DB_675; User ID=user_id; Password=password; Trusted_Connection=False" providerName="System.Data.SqlClient" /> NOTE: The misspelling of "starter" in the value "aspnet_staterKits_TimeTracker" originates from the Time Tracker application itself.

6. If your existing website resides in your hosting account root directory, add the following line of code to the Time Tracker web.config file, between the <system.web> tags: <pages styleSheetTheme=""/> 7. Under the Tools section of the Hosting Control Panel, click the IIS Settings icon. 8. Click Create Directory. Enter the name of the directory in which your Time Tracker application will reside and, then select Anonymous Access and Set Application Root permissions. 9. Click Continue. 10. Upload the contents of your application to the directory you specified in step 8. For additional information about the Database Publishing Service and the Database Publishing Wizard, see the following articles:

What are the connection strings for my application's database?


Date Submitted: 2-28-2013 The following list contains connection strings for many popular program databases. If your program is not listed, contact the program's manufacturer. NOTE:You will have to obtain these files referenced below by FTPing into your hosting account and into the application's directories. For more information on this, see your application's manufacturer's website. To find your hostname, see What do I use for a host name when creating a database? 4Images Edit the config.php file. You will need to update the following line with the name of the new database server. $db_host = "youroldhostname"; Aardvark Topsites Edit the settings_sql.php file. You will need to update the following line with the name of the new database server. $CONF['sql_host'] = 'youroldhostname'; Advanced Guestbook

Edit the admin/config.inc.php file. You will need to update the following line with the name of the new database server. $GB_DB["host"] = "youroldhostname"; Advanced Poll Edit the db/include/config.inc.php file. You will need to update the following line with the name of the new database server. $POLLDB["host"] = "youroldhostname"; anyInventory Edit the globals.php file. You will need to update the following line with the name of the new database server. $db_host = "youroldhostname"; BidWare Edit the configuration/configure.inc.php file. You will need to update the following line with the name of the new database server. $bidwareTsohbD = 'youroldhostname'; BlogEngine.NET Edit the web.config file. You will need to update the following line with the name of the new database server. <add name="BlogEngine" connectionString="Data Source=youroldhostname;User ID=DBUser;Password=DBPassword;persist security info=False;initial catalog=DBName;" providerName="System.Data.SqlClient"/> Brim Edit the framework/configuration/databaseConfiguration.php file. You will need to update the following line with the name of the new database server. $host = 'youroldhostname'; Community Server Edit the connectionStrings.config file. You will need to update the following line with the name of the new database server.

<add name="SiteSqlServer" connectionString="server=youroldservername;uid=DBUser;pwd='DBPassword';database=DBNa me"/> Coppermine Edit the include/config.inc.php file. You will need to update the following line with the name of the new database server. $CONFIG['dbserver'] = 'youroldhostname; DotNetNuke Edit the web.config file. You will need to update the following line with the name of the new database server. connectionString="Server=youroldhostname;Database=DBName;uid=DBUser;pwd=DBPass;" dotProject Edit the includes/config.php file. You will need to update the following line with the name of the new database server. $dPconfig['dbhost'] = 'youroldhostname'; connectionString="Server=youroldhostname;Database=DBName;uid=DBUser;pwd=DBPass;" Drupal To update Drupal connection strings, follow the instructions listed in INSTALL.txt. Gallery Edit the config.php file. You will need to update the following line with the name of the new database server. $storeConfig['hostname'] = 'youroldhostname; Geeklog Edit the db-config.php file. You will need to update the following line with the name of the new database server. $_DB_host = 'youroldhostname'; Joomla

Edit the configuration.php file. You will need to update the following line with the name of the new database server. var $host = 'youroldhostname'; Lifetype Edit the config/config.properties.php file. You will need to update the following line with the name of the new database server. $config['db_host'] = 'youroldhostname'; MODx Edit the includes/config.inc.php file. You will need to update the following line with the name of the new database server. $database_server = 'youroldhostname'; Mambo Edit the configuration.php file. You will need to update the following line with the name of the new database server. $mosConfig_host = 'youroldhostname'; Mantis Edit the config_inc.php file. You will need to update the following line with the name of the new database server. $g_hostname = "youroldhostname"; MediaWiki Edit the LocalSettings.php and config/LocalSettings.php files. You will need to update the following line with the name of the new database server.$wgDBserver = "youroldhostname"; Moodle Edit the config.php file. You will need to update the following line with the name of the new database server. $CFG->dbhost = 'youroldhostname'; Noahs Classifieds

Edit the app/config.php file. You will need to update the following line with the name of the new database server. $hostName="youroldhostname"; Nucleus Edit the config.php file. You will need to update the following line with the name of the new database server. $MYSQL_HOST = 'youroldhostname'; OSCommerce Edit the includes/configure.php and admin/includes/configure.php files. You will need to update the following line with the name of the new database server. define('DB_SERVER', 'youroldhostname'); OpenDB Edit the include/local.config.php file. You will need to update the following line with the name of the new database server. 'host'=>'youroldhostname', //OpenDb database host OpenX Edit the var/yoursitename.com.conf.php file. You will need to update the following line with the name of the new database server. host="youroldhostname" OrangeHRM Edit the lib/confs/Conf.php file. You will need to update the following line with the name of the new database server. $this->dbhost = 'youroldhostname'; paFileDB Edit the includes/config.php file. You will need to update the following line with the name of the new database server. $dbServer = "youroldhostname";

PHCDownload Edit the include/config.ini.php file. You will need to update the following line with the name of the new database server. $config['db_server'] = "youroldservername"; PHPOpenChat Edit the config.inc.php file. You will need to update the following line with the name of the new database server. define('DATABASE_HOST', 'youroldhostname'); PHProjekt Edit the config.inc.php file. You will need to update the following line with the name of the new database server. define('PHPR_DB_HOST', 'youroldhostname'); PhpBB Edit the config.php file. You will need to update the following line with the name of the new database server. $dbhost = 'youroldhostname; phpCollab Edit the includes/settings.php file. You will need to update the following line with the name of the new database server. define('MYSERVER', 'youroldhostname'); phpMyFAQ Edit the inc/data.php file. You will need to update the following line with the name of the new database server. $DB["server"] = 'youroldhostname'; phpmyvisits Edit the config/config.php file. You will need to update the following line with the name of the new database server.

'db_host' => 'youroldhostname', Pinnacle Cart Edit the content/engine/engine_config.php file. You will need to update the following line with the name of the new database server. define('DB_HOST', 'youroldhostname'); PostNuke Edit the config.php file. You will need to update the following line with the name of the new database server. $pnconfig['dbhost'] = 'youroldhostname'; reBlog Edit the config.php file. You will need to update the following line with the name of the new database server. define('REF_DB_HOST', "youroldhostname"); Serendipity Edit the serendipity_config_local.inc.php file. You will need to update the following line with the name of the new database server. $serendipity['dbHost'] = 'youroldhostname'; SilverStripe Edit the tutorial/_config.php file. You will need to update the following line with the name of the new database server. "server" => "youroldhostname", Simple Machine Forum Edit the Settings.php file. You will need to update the following line with the name of the new database server. $db_server = 'youroldhostname'; Vanilla Forum

Edit the conf/database.php file. You will need to update the following line with the name of the new database server. $Configuration['DATABASE_HOST'] = 'youroldhostname; WebCalendar Edit the includes/settings.php file. You will need to update the following line with the name of the new database server. db_host: youroldhostname WordPress Edit the wp-config.php file. You will need to update the following line with the name of the new database server. define('DB_HOST', 'youroldhostname'); Xoops Edit the mainfile.php file. You will need to update the following line with the name of the new database server. define( 'XOOPS_DB_HOST', 'youroldhostname' ); YetAnotherForum Edit the yafnet.config file. You will need to update the following line with the name of the new database server. <connstr>user id=DBUser;pwd=DBPassword;data source=youroldhostname;initial catalog=DBName;timeout=90</connstr> Zen Cart Edit the includes/configure.php and admin/includes/configure.php files. You will need to update the following line with the name of the new database server. define('DB_SERVER', 'youroldhostname);

Modifying or Adding Custom MIME Types to Windows Hosting Accounts

Date Submitted: 6-30-2011 Using a Windows hosting account running IIS 7, you can modify or add MIME types. This lets you specify how Web browsers handle file extensions. Your hosting account already handles a number of different MIME types. For more information, see What MIME types does my Windows hosting account support by default?. To modify or add custom MIME types, you must create or edit your account's web.config file. For more information about web.config files, see ASP.NET's Web.Config Basics. To Modify Existing MIME Types Create or edit a web.config file in your account's root directory to include the following: <configuration> <system.webServer> <staticContent> <remove fileExtension=".EXTENSION" /> <mimeMap fileExtension=".EXTENSION" mimeType="TYPE/SUBTYPE" /> </staticContent> </system.webServer> </configuration> Enter your own values for EXTENSION, TYPE, and SUBTYPE, where:
EXTENSION is the file extension you want to serve to the browser TYPE is the MIME type you want to use, such as application, image, SUBTYPE is the MIME subtype you want to use

or video

For example, you could use this code in your web.config file, if you want to add MP4 files to your website: <configuration> <system.webServer> <staticContent> <remove fileExtension=".mp4" /> <mimeMap fileExtension=".mp4" mimeType="video/mp4" /> </staticContent> </system.webServer> </configuration> To Add Custom MIME Types Create or edit a web.config file in your account's root directory to include the following:

<configuration> <system.webServer> <staticContent> <mimeMap fileExtension=".EXTENSION" mimeType="TYPE/SUBTYPE" /> </staticContent> </system.webServer> </configuration> Enter your own values for EXTENSION, TYPE, and SUBTYPE, where:
EXTENSION is the file extension you want to serve to the browser TYPE is the MIME type you want to use, such as application, image, SUBTYPE is the MIME subtype you want to use

or video

Publishing Your FrontPage 2003 Website Using FTP


Date Submitted: 2-22-2012

If you built your website using Microsoft FrontPage 2003, we recommend publishing your website using File Transfer Protocol (FTP) instead of FrontPage Server Extensions. Microsoft discontinued FrontPage Extension support in 2004 and no longer provides security updates or patches. NOTE: Your website will still work without FrontPage Server Extensions, and you can continue to use and manage your site using FrontPage. However, some features of your website will not work, such as contact forms.
To Publish Your FrontPage 2003 Website Using FTP 1. Launch FrontPage. 2. From the File menu, select Publish Site.

3. Complete the following fields, and then click OK: o Select FTP. o Remote Web site location Enter your domain name or hosting account's IP address after ftp://. o FTP directory Type / to publish to your hosting account's primary domain name, or the path on your hosting account to the domain name you want to use. o Select Use Passive FTP

4. In the Publish all changed pages section, select Local to remote, and then click Publish Web site.

Creating an ASP.NET 2.0 Personal Web Site


Date Submitted: 10-26-2009

Visual Web Developer 2008 Express Edition includes a Personal website Starter Kit. This starter kit provides you with a basic home page, a page for your resume, another to place a collection of your favorite links, and another page that enables you to publish your photos. For more information about the ASP.NET 2.0 Personal website, see the Introduction to the Personal website Starter Kit on MSDN.
To Create an ASP.NET 2.0 Personal website 1. 2. 3. 4. 5. 6. Download and install the Visual Web Developer 2008 Express Edition. Next, you need to enable ASP.NET 2.0 on your Windows hosting account. Setup the ASP.NET 2.0 schema for your SQL Server database. Add the "personal-add.sql" schema for your website to your SQL server database. Modify the connection strings section of your web.config file. Upload your website.

7. Connecting to a SQL Server Database Using ASP.NET 3.5


8. Date Submitted: 7-25-2013

9. Before you upload your ASP.NET 3.5 application onto your hosting server, you need to modify the connection strings section of your web.config file. 10. NOTE: You may want to back up the web.config file on your local computer or simply comment out your current connection strings before you make any changes. This way, you can easily return to developing your application on you local computer.

11. This is an example of the connection strings section that will connect an ASP.NET 3.5 application to one of our SQL Servers:
12. <connectionStrings> <add name="Personal" connectionString=" Server=whsql-v04.prod.mesa1.secureserver.net; Database=DB_675; User ID=user_id; Password=password; Trusted_Connection=False" providerName="System.Data.SqlClient" /> <remove name="LocalSqlServer"/><add name="LocalSqlServer" connectionString=" Server=whsql-v04.prod.mesa1.secureserver.net; Database=DB_675; User ID=user_id; Password=password; Trusted_Connection=False" providerName="System.Data.SqlClient" /> </connectionStrings>

13. NOTE: You can find your server name, database name, user ID, and password in the SQL Server section of your Hosting Control Panel. These connection string values map to host name, database name, user name, and password, respectively. The user name and password values are those specified during SQL database (not hosting account) creation.

15.

Is Parent Path Enabled on Shared ASP Hosting?

16. Date Submitted: 11-14-2011

17. Yes, we have enabled parent paths on your Windows shared hosting account. 18. Parent Pathing allows you to access resources from a file-relative approach. You can "address up" a directory level and access those resources.

19.

What ASP.NET runtime version should I choose?

20. Date Submitted: 8-5-2010

21. The ASP.NET runtime you choose for your hosting account should match the runtime version of the .NET applications you plan to install. Both IIS 7 and IIS 6 are compatible with runtime versions 1.1, 2.0, 3.0, and 3.5. ASP.NET v4.0 is only compatible with IIS 7.

Do your hosting accounts support MVC3 applications?


Date Submitted: 4-29-2013

Our Web Hosting accounts support MVC3 applications by default, but our Shared Hosting accounts do not. For more information, see What type of hosting account do I have? However, you can deploy ASP.NET MVC3 applications to Windows Shared Hosting accounts by copying certain assemblies to the bin directory. If you want to use an ASP.NET MVC 3 RC2 application with our Windows Hosting accounts, you must use IIS 7, runtime version 4.0 with integrated pipeline mode, and then upload the required assembly dependencies.

To Use MVC3 Applications with Windows Shared Hosting 1. Make sure your account uses IIS 7. For more information, see Customizing IIS Settings on Your Windows Hosting Account. 2. Follow the instructions in Changing Pipeline Mode on Your Windows IIS 7 Hosting Account. Select Integrated Pipeline Mode. 3. In your Project References section, set Copy Local to True for the following assemblies: o System.Web.Abstractions o System.Web.Helpers o System.Web.Routing o System.Web.Mvc o System.Web.WebPages 4. Add the following assemblies to your project, and then set Copy Local to True: o Microsoft.Web.Infrastructure o System.Web.Razor o System.Web.WebPages.Deployment o System.Web.WebPages.Razor 5. Publish your application.

Changing Pipeline Mode on Your Windows IIS 7 Hosting Account


Date Submitted: 7-25-2013

Windows hosting accounts running IIS 7 offer two pipeline modes: classic and integrated. Your pipeline mode can be changed anytime through the Hosting Control Panel. For information on pipeline modes, see What is pipeline mode?. For information on migration issues, see Migration Issues with IIS 7's Integrated Pipeline Mode.
To Change Pipeline Mode 1. 2. 3. 4. 5. 6. 7. Log in to your Account Manager. Click Web Hosting. Next to the hosting account you want to use, click Launch. In the Tools section of the Hosting Control Panel, click IIS Management. Click the Pipeline icon. In the Advanced Features section, select the appropriate pipeline mode. Click OK.

S-ar putea să vă placă și