Monday, November 23, 2015

Retrieving the COM class factory for component with CLSID {92459B29-7D3B-4612-86D8-3657ADFE7033} failed due to the following error: 80040154 Class not registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG)).

Issue :
Retrieving the COM class factory for component with CLSID {92459B29-7D3B-4612-86D8-3657ADFE7033} failed due to the following error: 80040154 Class not registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG)).




Solution :


1.Modify your project's platform from 'Any CPU' to 'X86' in Project Properties, Build/Platform's Target in Visual Studio
2.If your Application is a Web-Based Application, try setting IIS to run in 32-bit mode. You can do this by going to IIS Manager, selecting the Application Pool, then choosing "Advanced Settings". The second option from the top is "Enable 32-bit Applications".
3.If your Application is Web-Based, it could be that the com object was not configured to allow launch and access permissions for the aspnet user identity. Under administrative tools > Component services under the tree view, go to Component Services > Computers > My Computer > DCOM Config and find the registered com object. Right click for properties. Under the security tag, customize the Permissions to allow asp.net user

Wednesday, November 10, 2010

Validation of viewstate MAC failed error

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
tag. But this hidden field might not have been rendered to the browser with long-running pages, and if you make a postback before it does, the browser initiates postback without this field (in form post collection). End result is that if this field is omitted on postback, the page doesn't know that Viewstate is encrypted and causes the aforementioned Exception. I.E. page expects to be fully-loaded before you make a postback.

And by the way similar problem is with event validation since __EVENTVALIDATION field is also rendered on the end of the form. This is a security feature that ensures that postback actions only come from events allowed and created by the server to help prevent spoofed postbacks. This feature is implemented by having controls register valid events when they render (as in, during their actual Render() methods). The end result is that at the bottom of your rendered tag, you'll see something like this: . When a postback occurs, ASP.NET uses the values stored in this hidden field to ensure that the button you clicked invokes a valid event. If it's not valid, you get the exception above.

The problem happens specifically when you postback before the EventValidation field has been rendered. If EventValidation is enabled (which it is, by default), but ASP.net doesn't see the hidden field when you postback, you also get the exception. If you submit a form before it has been entirely rendered, then chances are the EventValidation field has not yet been rendered, and thus ASP.NET cannot validate your click.

Workarounds
1. Set enableEventValidation to false and viewStateEncryptionMode to Never as follows:

viewstateencryptionmode="Never">This has the unwanted side-effect of disabling validation and encryption. On some sites, this may be ok to do, but it isn't a best practice, especially in publicly facing sites.



2. Another way around the problem is to mark the form as disabled and then enable it in script once the load is complete:

function enableForm() {
document.getElementById("form").disabled = false;
}

window.onLoad = enableForm();

Or you can disable the individual form elements and enable them once everything is loaded:

function disableElements(elements) {
for (var i = elements.length - 1; i >= 0; i--) {
var elmt = elements[i];

if (!elmt.disabled) {
elmt.disabled = true;
}
else {
elmt._wasDisabled = true;
}
}
}

function disableFormElements() {
disableElements(_form.getElementsByTagName("INPUT"));
disableElements(_form.getElementsByTagName("SELECT"));
disableElements(_form.getElementsByTagName("TEXTAREA"));
disableElements(_form.getElementsByTagName("BUTTON"));
disableElements(_form.getElementsByTagName("A"));
}

function enableElements(elements) {
for (var i = elements.length - 1; i >= 0; i--) {
var elmt = elements[i];
if (!elmt._wasDisabled) {
elmt.disabled = false;
}
else {
elmt._wasDisabled = null;
}
}
}

function enableFormElements() {
enableElements(_form.getElementsByTagName("INPUT"));
enableElements(_form.getElementsByTagName("SELECT"));
enableElements(_form.getElementsByTagName("TEXTAREA"));
enableElements(_form.getElementsByTagName("BUTTON"));
enableElements(_form.getElementsByTagName("A"));
}
Make sure that the variable _form is set to the ASP.net form on the page. Then just call enableFormElements() and disableFormElements().


3. The last way to workaround this problem is to override the Render Event of the page to place the hidden fields for Encrypted Viewstate and Event validation on the top of the form. This will ensure that these things get written out before anything that can submit the form:



protected override void Render(System.Web.UI.HtmlTextWriter writer)
{
System.IO.StringWriter stringWriter = new System.IO.StringWriter();
HtmlTextWriter htmlWriter = new HtmlTextWriter(stringWriter);
base.Render(htmlWriter);
string html = stringWriter.ToString();
string[] aspnet_formelems = new string[5];
aspnet_formelems[0] = "__EVENTTARGET";
aspnet_formelems[1] = "__EVENTARGUMENT";
aspnet_formelems[2] = "__VIEWSTATE";
aspnet_formelems[3] = "__EVENTVALIDATION"; aspnet_formelems[4] = "__VIEWSTATEENCRYPTED";
foreach (string elem in aspnet_formelems)
{
//Response.Write("input type=""hidden"" name=""" & abc.ToString & """")
int StartPoint = html.IndexOf(" elem.ToString() + "\"");
if (StartPoint >= 0)
{
//does __VIEWSTATE exist?
int EndPoint = html.IndexOf("/>", StartPoint) + 2;
string ViewStateInput = html.Substring(StartPoint, EndPoint - StartPoint);
html = html.Remove(StartPoint, EndPoint - StartPoint);
int FormStart = html.IndexOf(" 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("= 0) endForm = html.IndexOf(">", formStart); if (endForm >= 0) { StringBuilder viewStateBuilder = new StringBuilder(); foreach (string element in aspNetFormElements) { int startPoint = html.IndexOf("= 0 && startPoint > endForm) { int endPoint = html.IndexOf("/>", startPoint); if (endPoint >= 0) { endPoint += 2; string viewStateInput = html.Substring(startPoint, endPoint - startPoint); html = html.Remove(startPoint, endPoint - startPoint); viewStateBuilder.Append(viewStateInput).Append("\r\n"); } } } if (viewStateBuilder.Length > 0) { viewStateBuilder.Insert(0, "\r\n"); html = html.Insert(endForm + 1, viewStateBuilder.ToString()); } } writer.Write(html); }}
There are many other workarounds for the above mentioned problem; however no definite solution.

Further Information around this problem
ASP.NET Forum link
Connect Bug

Also, if you use Server.Transfer on your page, you you can also run into this issue. For information on that, take a look at the documentation found here. Specifically:

If you set preserveForm to true and if the enableViewStateMac attribute of the pages configuration element is true, ASP.NET will raise an exception when Transfer is executed because the view state from the page that calls Transfer is not valid on the destination page. One of the preserved form fields on the calling page is the hidden __VIEWSTATE form field, which holds the view state for the page. When enableViewStateMac is true, ASP.NET runs a message authentication check on the view state of the destination page when the page is posted back from the client and the check will fail.

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.

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

Friday, April 9, 2010

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