Issue Description
You can get this Exception:
HttpException (0x80004005): Validation of viewstate
MAC failed. If this application is hosted by a Web
Farm or cluster, ensure that configuration
specifies the same validationKey and validation
algorithm. AutoGenerate cannot be used in a cluster.
when the following preconditions are true:
1. You aren't using a web farm.
2. It appears when using built-in databound controls such as GridView, DetailsView or FormView which utilize “DataKeyNames”.
3. It appears if you have a large page which loads slowly for any reason.
If following preconditions are true and you click a postbacking control/link and the page hasn't loaded completely in client browser, you might get the "Validation of ViewState MAC failed" exception.
When this happens, if you just try setting the page property "EnableViewStateMac" to false, it does not solve the problem, it just changes the error message in same navigation behavior:
The state information is invalid for this page and might be corrupted.
Other exceptions that seem to be the same problem look like:
Exception: System.Web.HttpUnhandledException
Message: Exception of type 'System.Web.HttpUnhandledException' was thrown.
Source: System.Web
at System.Web.UI.Page.HandleError(Exception e)
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint,
Boolean includeStagesAfterAsyncPoint)
at System.Web.UI.Page.ProcessRequest(Boolean includeStagesBeforeAsyncPoint,
Boolean includeStagesAfterAsyncPoint)
at System.Web.UI.Page.ProcessRequest()
at System.Web.UI.Page.ProcessRequestWithNoAssert(HttpContext context)
at System.Web.UI.Page.ProcessRequest(HttpContext context)
at ASP.test_aspx.ProcessRequest(HttpContext context)
at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExec
utionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean&
completedSynchronously)
Nested Exception
Exception: System.ArgumentException
Message: Invalid postback or callback argument. Event validation is enabled using in configuration or <%@ Page
EnableEventValidation="true" %> in a page. For security purposes, this feature
verifies that arguments to postback or callback events originate from the server control that originally rendered them. If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation.
Source: System.Web
at System.Web.UI.ClientScriptManager.ValidateEvent(String uniqueId, String
argument)
at System.Web.UI.Control.ValidateEvent(String uniqueID, String eventArgument)
at System.Web.UI.WebControls.TextBox.LoadPostData(String postDataKey,
NameValueCollection postCollection)
at System.Web.UI.WebControls.TextBox.System.Web.UI.IPostBackDataHandler.LoadPostData(St
ring postDataKey, NameValueCollection postCollection)
at System.Web.UI.Page.ProcessPostData(NameValueCollection postData, Boolean
fBeforeLoad)
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint,
Boolean includeStagesAfterAsyncPoint) and
Content-Length:1232
Content-Type:application/x-www-form-urlencoded
Accept:*/*
Accept-Encoding:gzip,deflate
Accept-Language:en-us
Cookie:ASP.NET_SessionId=skk4vriy1lzghm55bicesz45;
Host:
User-Agent:T-Mobile Dash Mozilla/4.0 (compatible; MSIE 4.01; Windows CE;
Smartphone; 320x240) UA-OS:Windows CE (Smartphone) - Version 5.1
UA-color:color16
UA-pixels:320x240
x-wap-profile:""
UA-Voice:TRUE
UA-CPU:x86
X-Forwarded-For:
Thread: 964
Date: 2007-10-25 13:47:03,925
NDC: (null)
Exception: System.Web.HttpException
Message: Validation of viewstate MAC failed. If this application is hosted by a Web
Farm or cluster, ensure that configuration specifies the same validationKey and validationalgorithm. AutoGenerate cannot be used in a cluster.
Source: System.Web
at System.Web.UI.ViewStateException.ThrowError(Exception inner, String
persistedState, String errorPageMessage, Boolean macValidationError)
at System.Web.UI.ObjectStateFormatter.Deserialize(String inputString)
at
System.Web.UI.ObjectStateFormatter.System.Web.UI.IStateFormatter.Deserialize(String
serializedState)
at System.Web.UI.Util.DeserializeWithAssert(IStateFormatter formatter, String
serializedState)
at System.Web.UI.HiddenFieldPageStatePersister.Load()
at System.Web.UI.Page.LoadPageStateFromPersistenceMedium()
at System.Web.UI.Page.LoadAllState()
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint,
Boolean includeStagesAfterAsyncPoint)
at System.Web.UI.Page.ProcessRequest(Boolean includeStagesBeforeAsyncPoint,
Boolean includeStagesAfterAsyncPoint)
at System.Web.UI.Page.ProcessRequest()
at System.Web.UI.Page.ProcessRequestWithNoAssert(HttpContext context)
at System.Web.UI.Page.ProcessRequest(HttpContext context)at ASP.test_aspx.ProcessRequest(HttpContext context)
at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExec
utionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean&
completedSynchronously)
Nested Exception
Exception: System.Web.UI.ViewStateException
Message: Invalid viewstate.
Client IP:
Port: 61362
User-Agent: T-Mobile Dash Mozilla/4.0 (compatible; MSIE 4.01;
Windows CE; Smartphone; 320x240)
ViewState:
/wEPDwUJMjUyNTI1NDMyD2QWAmYPZBYCAgEPZBYEAlAPD2QWAh4Kb25rZXlwcmVzcwUqcmV0dXJuIGNsaWNr
QnV0dG9uKGV2ZW50LCdjdGwwMF9pYlNlYXJjaCcpZAJWD2QWBAIBD2QWBAIDDw9kFgIfAAUxcmV0dXJuIGNs
aWNrQnV0dG9uKGV2ZW50LCdjdGwwMF9jcDFfRmxhc2hCdXR0b24nKWQCBg8UKwACDxYCHghJbWFnZVVybAUj
fi9faG9tZV9hZF91bml0cy9ob21lX2FkdW5pdHMxMS5qcGdkDxQrAAMWCB4LQ29vcmRpbmF0ZXMFFzAsMCwy
NTUsMCwyMjQsMTEwLDAsMTEwHgtOYXZpZ2F0ZVVybAUGfi9uZmwvHg1BbHRlcm5hdGVUZXh0BSNUaGUgcnVz
aCB0byBGYXRoZWFkIGZvb3RiYWxsIGlzIG9uIR4GVGFyZ2V0ZRYIHwIFGzQ5OCwwLDQ1OCwxMTAsMjI0LDEx
MCwyNTUsMB8DBRB+L2hlcm9lcy9iYXRtYW4vHwQFOVRoZSBEYXJrIEtuaWdodCBpcyBoZXJlLi4uYW5kIGhl
J3MgYnJvdWdodCBzb21lIGZyaWVuZCdzIR8FZRYIHwIFGzcwOCwxMTAsNzM5LDAsNDk4LDAsNDU4LDExMB8D
BQZ+L21sYi8fBAUhTUxCIGhpdHMgYSBob21lIHJ1biB3aXRoIEZhdGhlYWQhHwVlFCsBAwICAgICAmQCAw8P
FgIeB1Zpc2libGVoZBYCAgEPZBYCZg8PZBYCHwAFMnJldHVybiBjbGlja0J1dHRvbihldmVudCwnY3RsMDBf
Y3AxX1N0YXRpY0J1dHRvbicpZBgBBR5f...
Nested Exception
Exception: System.Web.HttpException
Message: Unable to validate data.
Source: System.Web
at System.Web.Configuration.MachineKeySection.GetDecodedData(Byte[] buf, Byte[]
modifier, Int32 start, Int32 length, Int32& dataLength)
at System.Web.UI.ObjectStateFormatter.Deserialize(String inputString)
Root Cause
This exception appears because Controls using DataKeyNames require Viewstate to be encrypted. When Viewstate is encrypted (Default mode, Auto, is to encrypt if controls require that, otherwise not), Page adds field just before closing of the int EndForm = html.IndexOf(">", FormStart) + 1;
if (EndForm >= 0)
html = html.Insert(EndForm, ViewStateInput);
}
}
writer.Write(html);
}Update
Another solution based on #3 above, special thanks to Alex for posting this in the comments below. He wrote a small class called BasePage that fixes the issues, so you just have to extend your page from BasePage instead of Page:
public class BasePage : Page{ private static string[] aspNetFormElements = new string[] { "__EVENTTARGET", "__EVENTARGUMENT", "__VIEWSTATE", "__EVENTVALIDATION", "__VIEWSTATEENCRYPTED", }; protected override void Render(HtmlTextWriter writer) { StringWriter stringWriter = new StringWriter(); HtmlTextWriter htmlWriter = new HtmlTextWriter(stringWriter); base.Render(htmlWriter); string html = stringWriter.ToString(); int formStart = html.IndexOf("
Wednesday, November 10, 2010
Wednesday, September 1, 2010
OOPS Concepts
OOPS Concepts
OOPS Concepts:
Key Concepts of Object Oriented Programming:
(1) Abstraction: is the ability to generalize an object as a data type that has a specific set of characteristics and is able to perform a set of actions.
Object-oriented languages provide abstraction via classes. Classes define the properties and methods of an object type.
Classes are blueprints for Object.
Objects are instance of classes.
Early binding means that our code directly interacts with the object, by directly calling its methods. Since the compiler knows the object's data type ahead of time, it can directly compile code to invoke the methods on the object. Early binding also allows the IDE to use IntelliSense to aid our development efforts; it allows the compiler to ensure that we are referencing methods that do exist and that we are providing the proper parameter values.
Late binding means that our code interacts with an object dynamically at run-time. This provides a great deal of flexibility since our code literally doesn't care what type of object it is interacting with as long as the object supports the methods we want to call. Because the type of the object isn't known by the IDE or compiler, neither IntelliSense nor compile-time syntax checking is possible but we get unprecedented flexibility in exchange.
(2) Encapsulation:Here objects can hide its internal data from direct access by external objects.It can be done by using 'private' or 'protected' keywords while declaration instead of public.
Encapsulation, sometimes called information hiding, is the ability to hide the internals of an object from its users and to provide an interface to only those members that you want the client to be able to directly manipulate.
Encapsulation provides the boundary between a class's external interface-that is, the public members visible to the class's users-and its internal implementation details. The advantage of encapsulation for the class developer is that he can expose the members of a class that will remain static, or unchanged, while hiding the more dynamic and volatile class internals.
(3) Polymorphism: Polymorphism is reflected in the ability to write one routine that can operate on objects from more than one class-treating different objects from different classes in exactly the same way. For instance, if both Customer and Vendor objects have a Name property, and we can write a routine that calls the Name property regardless of whether we're using a Customer or Vendor object, then we have polymorphism.
A vehicle is a good example of polymorphism. A vehicle interface would only have those properties and methods that all vehicles have, a few of which might include paint color, number of doors, accelerator, and ignition. These properties and methods would apply to all types of vehicles including cars, trucks, and semi-trucks.
Polymorphism will not implement code behind the vehicle's properties and methods. Instead, polymorphism is the implementation of an interface. If the car, truck, and semitruck all implement the same vehicle interface, then the client code for all three classes can be exactly the same.
C# gives us polymorphism through inheritance. C# provides a keyword virtual that is used in the definition of a method to support polymorphism.
Child class are now free to provide their own implementation of this virtual method, that is called overriding. The following points are important regarding virtual keyword:-
If the method is not virtual, the compiler simply uses the reference type to invoke the appropriate method.
If the method is virtual, the compiler will generate code to checkup the reference type at runtime it is actually denoting to, then the appropriate method is called from the class of the reference type.
When a virtual method is called, runtime check (late method binding) is made to identify the object and appropriate method is invoked, all this is done at runtime.
In case of non-virtual methods, this information is available at compile time, so no runtime check to identify the object is made, so slightly efficient in the way non-virtual methods are called. But the behavior of virtual method is useful in many ways; the functionality they provide is fair enough to bear this slight loss of performance.
(4) Inheritance: is the idea that one class, called a subclass, can be based on another class, called a base class. Inheritance provides a mechanism for creating hierarchies of objects. Inheritance is the ability to apply another class's interface and code to your own class.
Normal base classes may be instantiated themselves, or inherited. Derived classes can inherit base class members marked with protected or greater access. The derived class is specialized to provide more functionality, in addition to what its base class provides. Inheriting base class members in derived class is not mandatory.
base -> Access the members of the base class.
this -> Refer to the current object for which a method is called.
The base keyword is used to access members of the base class from within a derived class:
Call a method on the base class that has been overridden by another method. Specify which base-class constructor should be
called when creating instances of the derived class. A base class access is permitted only in a constructor, an instance
method, or an instance property accessor.
- A static member cannot be marked as override, virtual, or abstract.
- You can't call static methods of base class from derived class using base keyword.
Interface: An interface defines a contract. A class or struct that implements an interface must adhere to its contract.
Use an interface:
- When creating a standalone project which can be changed at will, use an interface in preference to an abstract class because, it offers more design flexibility.
- Use interfaces to introduce polymorphic behavior without subclassing and to model multiple inheritance—allowing a specific type to support numerous behaviors.
- Use an interface to design a polymorphic hierarchy for value types.
- Use an interface when an immutable contract is really intended.
- A well-designed interface defines a very specific range of functionality. Split up interfaces that contain unrelated functionality.
Abstract Class:Abstract classes are a special type of base classes. In addition to normal class members, they have abstract class members. These Abstract class members are methods and properties that are declared without an implementation. All classes derived directly from abstract classes must implement all of these abstract methods and properties.
Abstract classes can never be instantiated. This would be illogical, because of the members without implementations.So what good is a class that can't be instantiated? Lots! Abstract classes sit toward the top of a class hierarchy. They establish structure and meaning to code. They make frameworks easier to build. This is possible because abstract classes have information and behavior common to all derived classes in a framework.
Use an abstract class:
- When creating a class library which will be widely distributed or reused—especially to clients, use an abstract class in preference to an interface; because, it simplifies versioning.
- Use an abstract class to define a common base class for a family of types.
- Use an abstract class to provide default behavior.
- Subclass only a base class in a hierarchy to which the class logically belongs.
Difference between Interface and Abstract Class
- Interfaces are closely related to abstract classes that have all members abstract.
- For an abstract class, at least one method of the class must be an abstract method that means it may have concrete methods.
- For an interface, all the methods must be abstract
- Class that implements an interface much provide concrete implementation of all the methods definition in an interface or else must be declare an abstract class.
- In C#, multiple inheritance is possible only through implementation of multiple interfaces. Abstract class can only be derived once.
- An interface defines a contract and can only contains four entities viz methods, properties, events and indexes. An interface thus cannot contain constants, fields, operators, constructors, destructors, static constructors, or types.
- an interface cannot contain static members of any kind. The modifiers abstract, public, protected, internal, private, virtual, override is disallowed, as they make no sense in this context.
- Class members that implement the interface members must be publicly accessible.
OOPS Concepts:
Key Concepts of Object Oriented Programming:
(1) Abstraction: is the ability to generalize an object as a data type that has a specific set of characteristics and is able to perform a set of actions.
Object-oriented languages provide abstraction via classes. Classes define the properties and methods of an object type.
Classes are blueprints for Object.
Objects are instance of classes.
Early binding means that our code directly interacts with the object, by directly calling its methods. Since the compiler knows the object's data type ahead of time, it can directly compile code to invoke the methods on the object. Early binding also allows the IDE to use IntelliSense to aid our development efforts; it allows the compiler to ensure that we are referencing methods that do exist and that we are providing the proper parameter values.
Late binding means that our code interacts with an object dynamically at run-time. This provides a great deal of flexibility since our code literally doesn't care what type of object it is interacting with as long as the object supports the methods we want to call. Because the type of the object isn't known by the IDE or compiler, neither IntelliSense nor compile-time syntax checking is possible but we get unprecedented flexibility in exchange.
(2) Encapsulation:Here objects can hide its internal data from direct access by external objects.It can be done by using 'private' or 'protected' keywords while declaration instead of public.
Encapsulation, sometimes called information hiding, is the ability to hide the internals of an object from its users and to provide an interface to only those members that you want the client to be able to directly manipulate.
Encapsulation provides the boundary between a class's external interface-that is, the public members visible to the class's users-and its internal implementation details. The advantage of encapsulation for the class developer is that he can expose the members of a class that will remain static, or unchanged, while hiding the more dynamic and volatile class internals.
(3) Polymorphism: Polymorphism is reflected in the ability to write one routine that can operate on objects from more than one class-treating different objects from different classes in exactly the same way. For instance, if both Customer and Vendor objects have a Name property, and we can write a routine that calls the Name property regardless of whether we're using a Customer or Vendor object, then we have polymorphism.
A vehicle is a good example of polymorphism. A vehicle interface would only have those properties and methods that all vehicles have, a few of which might include paint color, number of doors, accelerator, and ignition. These properties and methods would apply to all types of vehicles including cars, trucks, and semi-trucks.
Polymorphism will not implement code behind the vehicle's properties and methods. Instead, polymorphism is the implementation of an interface. If the car, truck, and semitruck all implement the same vehicle interface, then the client code for all three classes can be exactly the same.
C# gives us polymorphism through inheritance. C# provides a keyword virtual that is used in the definition of a method to support polymorphism.
Child class are now free to provide their own implementation of this virtual method, that is called overriding. The following points are important regarding virtual keyword:-
If the method is not virtual, the compiler simply uses the reference type to invoke the appropriate method.
If the method is virtual, the compiler will generate code to checkup the reference type at runtime it is actually denoting to, then the appropriate method is called from the class of the reference type.
When a virtual method is called, runtime check (late method binding) is made to identify the object and appropriate method is invoked, all this is done at runtime.
In case of non-virtual methods, this information is available at compile time, so no runtime check to identify the object is made, so slightly efficient in the way non-virtual methods are called. But the behavior of virtual method is useful in many ways; the functionality they provide is fair enough to bear this slight loss of performance.
(4) Inheritance: is the idea that one class, called a subclass, can be based on another class, called a base class. Inheritance provides a mechanism for creating hierarchies of objects. Inheritance is the ability to apply another class's interface and code to your own class.
Normal base classes may be instantiated themselves, or inherited. Derived classes can inherit base class members marked with protected or greater access. The derived class is specialized to provide more functionality, in addition to what its base class provides. Inheriting base class members in derived class is not mandatory.
base -> Access the members of the base class.
this -> Refer to the current object for which a method is called.
The base keyword is used to access members of the base class from within a derived class:
Call a method on the base class that has been overridden by another method. Specify which base-class constructor should be
called when creating instances of the derived class. A base class access is permitted only in a constructor, an instance
method, or an instance property accessor.
- A static member cannot be marked as override, virtual, or abstract.
- You can't call static methods of base class from derived class using base keyword.
Interface: An interface defines a contract. A class or struct that implements an interface must adhere to its contract.
Use an interface:
- When creating a standalone project which can be changed at will, use an interface in preference to an abstract class because, it offers more design flexibility.
- Use interfaces to introduce polymorphic behavior without subclassing and to model multiple inheritance—allowing a specific type to support numerous behaviors.
- Use an interface to design a polymorphic hierarchy for value types.
- Use an interface when an immutable contract is really intended.
- A well-designed interface defines a very specific range of functionality. Split up interfaces that contain unrelated functionality.
Abstract Class:Abstract classes are a special type of base classes. In addition to normal class members, they have abstract class members. These Abstract class members are methods and properties that are declared without an implementation. All classes derived directly from abstract classes must implement all of these abstract methods and properties.
Abstract classes can never be instantiated. This would be illogical, because of the members without implementations.So what good is a class that can't be instantiated? Lots! Abstract classes sit toward the top of a class hierarchy. They establish structure and meaning to code. They make frameworks easier to build. This is possible because abstract classes have information and behavior common to all derived classes in a framework.
Use an abstract class:
- When creating a class library which will be widely distributed or reused—especially to clients, use an abstract class in preference to an interface; because, it simplifies versioning.
- Use an abstract class to define a common base class for a family of types.
- Use an abstract class to provide default behavior.
- Subclass only a base class in a hierarchy to which the class logically belongs.
Difference between Interface and Abstract Class
- Interfaces are closely related to abstract classes that have all members abstract.
- For an abstract class, at least one method of the class must be an abstract method that means it may have concrete methods.
- For an interface, all the methods must be abstract
- Class that implements an interface much provide concrete implementation of all the methods definition in an interface or else must be declare an abstract class.
- In C#, multiple inheritance is possible only through implementation of multiple interfaces. Abstract class can only be derived once.
- An interface defines a contract and can only contains four entities viz methods, properties, events and indexes. An interface thus cannot contain constants, fields, operators, constructors, destructors, static constructors, or types.
- an interface cannot contain static members of any kind. The modifiers abstract, public, protected, internal, private, virtual, override is disallowed, as they make no sense in this context.
- Class members that implement the interface members must be publicly accessible.
Tuesday, June 15, 2010
Uninstalling an installer from add or remove programs
Hi Friends,
some times we do not see the prompt for un installing the installer from the Add/Remove Programs so in that case we do not know the solution to un install the program .use the below tool for un installing any kind of program from registry
http://support.microsoft.com/kb/290301
some times we do not see the prompt for un installing the installer from the Add/Remove Programs so in that case we do not know the solution to un install the program .use the below tool for un installing any kind of program from registry
http://support.microsoft.com/kb/290301
Friday, April 9, 2010
Connection String examples in vb.net and C#.net
http://www.dofactory.com/Connect/Connect.aspx#_self11
Thursday, April 8, 2010
C# Cross-Thread Operations Cross-Thread Operations
C# Cross-Thread Operations
Cross-Thread Operations
A cross-thread operation in C# is a call that accesses components from a different thread. Starting with .NET Framework 2.0, it is no longer optional to make proper cross-thread operations, it is a requirement. So we are going to learn how to make cross-thread calls between controls.
For example, if you try to call a Form function from a seperate thread, you will get an error message similar to:
Cross-thread operation not valid: Control 'Form1' accessed from a thread other than the thread it was created on.
Delegates
The answer is simply to use delegates to invoke methods that use cross-thread operations. Delegates are an elegant way to call methods that are from other threads.
Methods
For our example, we need two general methods: one to keep the loop running, and one to perform the single cross-thread operation. The whole point of even using seperate a Thread is have a thread specialized in updating part of the application without disturbing the rest.
The example, which you can download at the bottom of the page, will alternate the colors of a Panel to create a sort of blinker. By using a Thread, the Panel can be constantly updated without locking up the rest of the user interface.
InvokeRequired
The key for cross-thread calls is in the InvokeRequired property. When cross-threading will be required, the property will be true. You can then use delegates to invoke the method properly:
if (this.InvokeRequired)
{
BlinkDelegate del = new BlinkDelegate(Blink); //delegate
object[] parameters = { secondsInterval }; //parameters
this.Invoke(del, parameters); //call
}
else
{
//What you want done goes here
}
Notice that the C# function is simply calling itself if invoke is required.
Cross-Thread Operations
A cross-thread operation in C# is a call that accesses components from a different thread. Starting with .NET Framework 2.0, it is no longer optional to make proper cross-thread operations, it is a requirement. So we are going to learn how to make cross-thread calls between controls.
For example, if you try to call a Form function from a seperate thread, you will get an error message similar to:
Cross-thread operation not valid: Control 'Form1' accessed from a thread other than the thread it was created on.
Delegates
The answer is simply to use delegates to invoke methods that use cross-thread operations. Delegates are an elegant way to call methods that are from other threads.
Methods
For our example, we need two general methods: one to keep the loop running, and one to perform the single cross-thread operation. The whole point of even using seperate a Thread is have a thread specialized in updating part of the application without disturbing the rest.
The example, which you can download at the bottom of the page, will alternate the colors of a Panel to create a sort of blinker. By using a Thread, the Panel can be constantly updated without locking up the rest of the user interface.
InvokeRequired
The key for cross-thread calls is in the InvokeRequired property. When cross-threading will be required, the property will be true. You can then use delegates to invoke the method properly:
if (this.InvokeRequired)
{
BlinkDelegate del = new BlinkDelegate(Blink); //delegate
object[] parameters = { secondsInterval }; //parameters
this.Invoke(del, parameters); //call
}
else
{
//What you want done goes here
}
Notice that the C# function is simply calling itself if invoke is required.
Cross-thread operation not valid: Control 'progressBar1' accessed from a thread other than the thread it was created on
Cross-thread operation not valid: Control 'progressBar1' accessed from a thread other than the thread it was created on PDF Print E-mail
Written by Shabdar
Tuesday, 25 November 2008 12:28
You will get following error when you try to update a windows form control from a separate thread.
"Cross-thread operation not valid: Control 'progressBar1' accessed from a thread other than the thread it was created on."
This article guides you on how to overcome this problem.
Problem
To reproduce this error, insert a progress bar control (progressbar1) on your form and insert a button(btnStart).
private void btnStart_Click(object sender, EventArgs e)
{
progressBar1.Minimum = 0;
progressBar1.Maximum = 100;
System.Threading.Thread t1 = new System.Threading.Thread(startProgress);
t1.Start();
}
void startProgress()
{
for (int i = 0; i {
progressBar1.Value = i; //You will get error at this line
System.Threading.Thread.Sleep(100);
}
}
window.google_render_ad();
Solution
private void btnStart_Click(object sender, EventArgs e)
{
progressBar1.Minimum = 0;
progressBar1.Maximum = 100;
System.Threading.Thread t1 = new System.Threading.Thread(startProgress);
t1.Start();
}
void startProgress()
{
for (int i = 0; i {
SetControlPropertyValue(progressBar1, "value", i); //This is a thread safe method
System.Threading.Thread.Sleep(100);
}
}
delegate void SetControlValueCallback(Control oControl, string propName, object propValue);
private void SetControlPropertyValue(Control oControl, string propName, object propValue)
{
if (oControl.InvokeRequired)
{
SetControlValueCallback d = new SetControlValueCallback(SetControlPropertyValue);
oControl.Invoke(d, new object[] { oControl, propName, propValue });
}
else
{
Type t = oControl.GetType();
PropertyInfo[] props = t.GetProperties();
foreach (PropertyInfo p in props)
{
if (p.Name.ToUpper() == propName.ToUpper())
{
p.SetValue(oControl, propValue, null);
}
}
}
}
You can apply same solution to any windows control. All you have to do is, copy SetControlValueCallback delegate and SetControlPropertyValue function from above code. For example if you want to set property of a label, use SetControlPropertyValue function.
SetControlPropertyValue(Label1, "Text", i.ToString());
Make sure you supply property value in correct type. In above example Text is a string property. This is why I am converting variable i to string.
Written by Shabdar
Tuesday, 25 November 2008 12:28
You will get following error when you try to update a windows form control from a separate thread.
"Cross-thread operation not valid: Control 'progressBar1' accessed from a thread other than the thread it was created on."
This article guides you on how to overcome this problem.
Problem
To reproduce this error, insert a progress bar control (progressbar1) on your form and insert a button(btnStart).
private void btnStart_Click(object sender, EventArgs e)
{
progressBar1.Minimum = 0;
progressBar1.Maximum = 100;
System.Threading.Thread t1 = new System.Threading.Thread(startProgress);
t1.Start();
}
void startProgress()
{
for (int i = 0; i {
progressBar1.Value = i; //You will get error at this line
System.Threading.Thread.Sleep(100);
}
}
window.google_render_ad();
Solution
private void btnStart_Click(object sender, EventArgs e)
{
progressBar1.Minimum = 0;
progressBar1.Maximum = 100;
System.Threading.Thread t1 = new System.Threading.Thread(startProgress);
t1.Start();
}
void startProgress()
{
for (int i = 0; i {
SetControlPropertyValue(progressBar1, "value", i); //This is a thread safe method
System.Threading.Thread.Sleep(100);
}
}
delegate void SetControlValueCallback(Control oControl, string propName, object propValue);
private void SetControlPropertyValue(Control oControl, string propName, object propValue)
{
if (oControl.InvokeRequired)
{
SetControlValueCallback d = new SetControlValueCallback(SetControlPropertyValue);
oControl.Invoke(d, new object[] { oControl, propName, propValue });
}
else
{
Type t = oControl.GetType();
PropertyInfo[] props = t.GetProperties();
foreach (PropertyInfo p in props)
{
if (p.Name.ToUpper() == propName.ToUpper())
{
p.SetValue(oControl, propValue, null);
}
}
}
}
You can apply same solution to any windows control. All you have to do is, copy SetControlValueCallback delegate and SetControlPropertyValue function from above code. For example if you want to set property of a label, use SetControlPropertyValue function.
SetControlPropertyValue(Label1, "Text", i.ToString());
Make sure you supply property value in correct type. In above example Text is a string property. This is why I am converting variable i to string.
Thursday, March 25, 2010
adding the styles to the renderd data as excel in the browser page using style sheet properties
Private Function AddExcelStyling() As String
Dim sb As StringBuilder = New StringBuilder
sb.Append(("" & vbLf + "" & vbLf))))
sb.Append("" & vbLf)
sb.Append("
'sb.Append("18 ")
'sb.Append("0 ")
'sb.Append("")
'sb.Append("")
'sb.Append("3 ")
'sb.Append(" ")
'sb.Append("")
'sb.Append("1 ")
'sb.Append(" ")
'sb.Append("")
'sb.Append("2 ")
'sb.Append(" ")
'sb.Append("")
'sb.Append("0 ")
'sb.Append(" ")
'sb.Append(" ")
'sb.Append("50 ")
'sb.Append("25 ")
''
'sb.Append("1 ")
'sb.Append("1 ")
sb.Append("" & vbLf)
sb.Append(" " & vbLf)
sb.Append("12 " & vbLf)
sb.Append("80 ")
sb.Append("1 ")
sb.Append("999 ")
sb.Append("20 " & vbLf)
sb.Append("20 " & vbLf)
sb.Append(" " & vbLf)
sb.Append(" " & vbLf)
sb.Append(" " & vbLf)
sb.Append("False " & vbLf)
sb.Append("False " & vbLf)
sb.Append("False " & vbLf)
sb.Append("" & vbLf)
sb.Append("" & vbLf)
sb.Append("" & vbLf)
sb.Append("12780 " & vbLf)
sb.Append("19035 " & vbLf)
sb.Append("0 " & vbLf)
sb.Append("15 " & vbLf)
sb.Append("False " & vbLf)
sb.Append("False " & vbLf)
sb.Append("" & vbLf)
sb.Append("" & vbLf)
sb.Append("" & vbLf)
sb.Append("" & vbLf)
Return sb.ToString
End Function
Dim sb As StringBuilder = New StringBuilder
sb.Append(("" & vbLf + "" & vbLf))))
sb.Append("" & vbLf)
sb.Append("
'sb.Append("
'sb.Append("
'sb.Append("
'sb.Append("
'sb.Append("
'sb.Append("
'sb.Append("
'sb.Append("
'sb.Append("
'sb.Append("
'sb.Append("
'sb.Append("
'sb.Append("
'sb.Append("
'sb.Append("
'sb.Append("
'sb.Append("
'sb.Append("
''
'sb.Append("
'sb.Append("
sb.Append("
sb.Append("
sb.Append("
sb.Append("
sb.Append("
sb.Append("
sb.Append("
sb.Append("
sb.Append("
sb.Append("
sb.Append("
sb.Append("
sb.Append("
sb.Append("
sb.Append("" & vbLf)
sb.Append("" & vbLf)
sb.Append("" & vbLf)
sb.Append("
sb.Append("
sb.Append("
sb.Append("
sb.Append("
sb.Append("
sb.Append("" & vbLf)
sb.Append("" & vbLf)
sb.Append("" & vbLf)
sb.Append("" & vbLf)
Return sb.ToString
End Function
Subscribe to:
Posts (Atom)
