Posts Tagged C#

The control tree into which viewstate is being loaded must match the control tree that was used to save viewstate during the previous request.

I have got the following error when I was developing a gridview editing on a webpage last week. This is most common issue, even I have faced several times earlier. But I want to keep this solution for beginners!

Here is the full error message:

"Failed to load viewstate.  The control tree into which viewstate is being loaded must match the control tree that was used to save viewstate during the previous request.  For example, when adding controls dynamically, the controls added during a post-back must match the type and position of the controls added during the initial request"

error

My 1st suggestion is just check the cache! Meaning..clear your browser cache and refresh it and see whether it is working? if not continue with one of the following solutions!

1. Enable ViewState is false

Find the control which is giving problem in the page and then disable the ViewState! For me it was a  DropDownList so,

<EditItemTemplate>
<asp:DropDownList ID="DropDownList1" runat="server" EnableViewState="false">
</asp:DropDownList>
</EditItemTemplate>

2. Just place the data binding on the GridView events wherever you use the edit! For and example “RowCancelingEdit”

Protected Sub GridViewRelease_RowCancelingEdit(ByVal sender As Object, ByVal e As GridViewCancelEditEventArgs) Handles GridViewRelease.RowCancelingEdit
GridViewReleaseAnalyst.EditIndex = -1
BindData()
End Sub

That’s all, No more ViewState issue! Happy Programming!!

References:

  1. http://forums.asp.net/t/1368283.aspx/1
Advertisement

, , , , , , ,

1 Comment

An invalid VARIANT was detected during a conversion from an unmanaged VARIANT to a managed object – C#

I have got this exception after I fixed this error, please check this post and read the following…!

Error Message:

“An invalid VARIANT was detected during a conversion from an unmanaged VARIANT to a managed object. Passing invalid VARIANTs to the CLR can cause unexpected exceptions, corruption or data loss.”

Fix:
Just go to the Debug menu in Visual studio and select Exceptions

Click and expand the Manage Debugging Assistants

Find the Invalid Variant node and uncheck the Thrown check box.

Click Ok and run the application, That’s all! Happy Programming..! If you want to read more about this issue, just read this post! 🙂

References:

http://www.dotnetspider.com/forum/299944-System.outofmemoryexception.aspx

http://blogs.msdn.com/b/yangxind/archive/2006/03/21/556837.aspx

, , , , , , , , , ,

2 Comments

The CLR has been unable to transition from COM context 0xXXXXXXX to COM context 0xYYYYYYY for 60 seconds – C#

Few months ago, I was developing a small windows application which gathers data from Active Directory(AD) and dumping into a SQL database table. There were around 18 to 20,000 records involved in the process. After developing and testing components with few data, everything was okay but when I run the application I got following error message:

“The CLR has been unable to transition from COM context 0x2297ce0 to COM context 0x2297f30 for 60 seconds. The thread that owns the destination context/apartment is most likely either doing a non pumping wait or processing a very long running operation without pumping Windows messages. This situation generally has a negative performance impact and may even lead to the application becoming non responsive or memory usage accumulating continually over time. To avoid this problem, all single threaded apartment (STA) threads should use pumping wait primitives (such as CoWaitForMultipleHandles) and routinely pump messages during long running operations.”

I didn’t want to spend too much time with this error and I have found the quick fix from this site, if you want to know more about this please read there. 😉

Here are the steps to fix this error;

Step 1: Go to Debug –> Exceptions  in Visual Studio 2010 (I was using 2010)

Step 2: Click on  Managed Debug Assistants

Step 3:  Un-check the ContextSwitchDeadlock and click OK

That’s all,  the problem was fixed but I have got an other error, please see the same kind of solution here.

References:

http://dotnetdud.blogspot.ca/2009/01/clr-has-been-unable-to-transition-from.html

, , , , , , ,

2 Comments

Installing Visual Studio 2012 RC on Windows 8 Step By Step

I want to create a Metro style application using C# on Windows 8, I have already  installed Windows 8 release preview on my laptop. You can see some screen shots here. Now I need to install the Visual Studio 2012 and I tried to install the express version and I have got this error (version conflict)! The reason is, the latest Visual Studio RTM versions won’t install on Windows 8 Release Preview. So we need to choose the correct version of Visual Studio 2012, So I have chosen the Visual Studio 2012 RC to install on my Windows 8. Okay here are the steps:

Step 1: Download the Visual studio 2012 RC and double click on setup.exe. I have selected Ultimate version.

Step 2: Installation started

Step 3: Setup requires 8.95 GB minimum, click agree and Next

Step 4:  It will ask for optional features to install, I have selected all

Step 5: After clicking Install then a window will be opened. That will show the acquiring and applying process..!

Step 6: Wait for few minutes to complete these processes

Step 7: Yes, setup completed successfully and click the LAUNCH button

Step 8: After few minutes below window will ask you to choose the default environment setting and I have chosen  the general development setting. Click Start Visual Studio button.

Step 9: Visual studio is loading user settings

Step 10:  Yes..Visual Studio is ready to rockz..! Just click the new project and select the language, I have selected C#

Step 11: Choose the Metro Style application and continue your coding..! Okay I will try to post my first Metro Style Application next! 🙂

 

That’s all guys! Happy programming n metro styling..!

References:

http://www.microsoft.com/visualstudio/eng/downloads#vs

http://www.microsoft.com/en-us/download/details.aspx?id=29917

, , , , , , , , ,

3 Comments

Difference between ‘Shadowing’ and ‘Overriding’ (Shadowing vs Overriding) – C#

This is a very quick Tech-Tips..! Actually Shadowing is VB.Net concept, in C# this concept called hiding! We will see this chapter later. 🙂

Shadowing : Creating an entirely new method with the same signature as one in a base class.

Overriding: Redefining an existing method on a base class.

  • Both are used when a derived class inherits from a base class
  • Both redefine one or more of the base class elements in the derived class

If you want to read more regarding this, just follow this MSDN topic.


class A
 {
 public int M1()
 {
 return 1;
 }

 public virtual int M2()
 {
 return 1;
 }
 }

class B : A
 {
 public new int M1()
 {
 return 2;
 }

 public override int M2()
 {
 return 2;
 }
 }

class Program
 {
 static void Main(string[] args)
 {
 B b = new B();
 A a = (A)b;

 Console.WriteLine(a.M1()); //Base Method
 Console.WriteLine(a.M2()); //Override Method
 Console.WriteLine(b.M1());
 Console.WriteLine(b.M2());
 Console.Read();
 }
 }

The output is : 1, 2, 2, 2

, , , , ,

1 Comment

SecurityException was unhandled by user code – VSTA, C#, InfoPath 2007

I got this error, while I was developing a InfoPath form in VSTA (Visual Studio Tools for Applications 2008) . This was my enviornment:

  • Windows 7
  • VSTA 2008
  • InfoPath 2007

Scenario: I was trying to get the user information from Active Directory(AD) and then display in an InfoPath form. Here is the C# code I have written in the VSTA:

public void CTRL1_5_Clicked(object sender, ClickedEventArgs e)
 {
 string strUserName = System.Environment.UserName;

 string xpath2 = "/my:myFields/my:field1";
 XPathNavigator field2 = MainDataSource.CreateNavigator().SelectSingleNode(xpath2, NamespaceManager);
 field2.SetValue(GetOU(strUserName)); //Get Organization Unit(OU) from Acitve Directory(AD)
 }

This is the error message I have got: 😦

Solution: I have fixed this issue in a different situation, just read in my previous post.

Thanks. R./

Happy InfoPathing. 🙂

, , , ,

1 Comment

Difference between ‘ref’ and ‘out’ parameters (ref vs out) – C#

  • Both are treated differently @ runtime but same in the compile time, so can’t be overloaded.
  • Both are passed by references except ‘ref’ requires that the variable to be initialized before passed.

ref:

class Program
 {
 static void M1(out int i)
 {
 i = 1;
 i += 1;
 }

static void Main(string[] args)
 {
 int j; //Not assigned
 M1(out j);
 Console.Write(j);
 Console.Read();
 }
 }
}

The output is : 2

out:

class Program
 {
 static void M1(ref int i)
 {
 i = 1;
 i += 1;
 }

 static void Main(string[] args)
 {
 int j=0; //Assigned
 M1(ref j);
 Console.Write(j);
 Console.Read();
 }
}

The output is same: 2, but we have to assigned the variable before used otherwise we will get an error.

, , , ,

2 Comments

How to get the current user’s OU (Organizational Unit) from AD (Active Directory) – C#

There are so many ways to get the user details form AD (Active directory), but I wanted to get the current user’s OU (Organizational Unit) from Active directory. There is no any direct method to get the OU (Actually I could not find anything on the web, if anyone get an easy way to find-out please let me know). I am currently developing a Custom Search for SharePoint 2007 and according to the OU, I want to display the search results.

Here is the method I have created and most of the comments I have put in the code itself. I used Asp.net and C#.

public string GetOU(string username)
 {
 string result = string.Empty;
 using (HostingEnvironment.Impersonate())
 {
 //Getting the domain
 PrincipalContext yourDomain = new PrincipalContext(ContextType.Domain);

//Finding the user
 UserPrincipal user = UserPrincipal.FindByIdentity(yourDomain, username);

//If the user found
 if (user != null)
 {
 // Getting the DirectoryEntry
 DirectoryEntry directoryEntry = (user.GetUnderlyingObject() as DirectoryEntry);
 //if the directoryEntry is not null
 if (directoryEntry != null)
 {
 //Getting the directoryEntry's path and spliting with the "," character
 string[] directoryEntryPath = directoryEntry.Path.Split(',');
 //Getting the each items of the array and spliting again with the "=" character
 foreach (var splitedPath in directoryEntryPath)
 {
 string[] eleiments = splitedPath.Split('=');
 //If the 1st element of the array is "OU" string then get the 2dn element
 if (eleiments[0].Trim() == "OU")
 {
 result = username + "-" + eleiments[1].Trim();
 break;
 }
 }
 }
 }
 }
 return result;
 }

Please don’t forget to add the following references:

using System.Collections;
using System.DirectoryServices.AccountManagement;
using System.DirectoryServices;
using System.Security.Principal;

If you want to get the current user’s OU then you can call this method in the Page_Load event.

protected void Page_Load(object sender, EventArgs e)
{
string userName = Context.User.Identity.Name;
LabelOU.Text = GetOU(userName);
}

You will get the output like this:

Domain-Name\RajanihanthV
OU-Name
I hope this small C# code will be helping someone! Thanks R./

References:

1. http://stackoverflow.com/questions/637486/how-to-get-the-current-users-active-directory-details-in-c-sharp

2. http://stackoverflow.com/questions/5309988/how-to-get-the-groups-of-a-user-in-active-directory-c-asp-net

, , , , , , , , , , , ,

7 Comments