7

Story:

Im developing a Chart that is displaying Vacations (Annual vacation ,Used vacation" etc...) the for the selection a year , Business unit , and a Department from a Combo box so far im happy whit the result it is working ... but if switch between this departments after some time doing this i get this strange error ... *

The state information is invalid for this page and might be corrupted.

[No relevant source lines]


so I scrolled little bit down and found this

[ViewStateException: Invalid viewstate. 
  Client IP: ::1
  Port: 27968
  Referer: http://localhost/HolidayTracker/Report/VacationChart.aspx
  Path: /HolidayTracker/Report/VacationChart.aspx
  User-Agent: Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; WOW64; Trident/6.0)
  ViewState: ....

So I checked my view states and I haven't found a error or something else ..

        private HtBusinessUnit selectedBU
    {
        get
        {
            return (HtBusinessUnit)ViewState["selectedBu"];

        }
        set
        {
            ViewState["selectedBu"] = value;
        }
    }
    private HtDepartment selectDep
    {
        get
        {
            return (HtDepartment)ViewState["selectedDep"];
        }
        set
        {
            ViewState["selectedDep"] = value;
        }
    }
    private string selectedYear
    {
        get
        {
            return ViewState["selectedYear"] != null ? ViewState["selectedYear"].ToString() : "";
        }
        set
        {
            ViewState["selectedYear"] = value;
        }
    }

here is the error message

[ArgumentException: Invalid token for impersonation - it cannot be duplicated.]
   System.Security.Principal.WindowsIdentity.CreateFromToken(IntPtr userToken) +3597947
   System.Security.Principal.WindowsIdentity..ctor(SerializationInfo info) +187
   System.Security.Principal.WindowsIdentity..ctor(SerializationInfo info, StreamingContext context) +51

[TargetInvocationException: Exception has been thrown by the target of an invocation.]
   System.RuntimeMethodHandle.SerializationInvoke(IRuntimeMethodInfo method, Object target, SerializationInfo info, StreamingContext& context) +0
   System.Runtime.Serialization.ObjectManager.CompleteISerializableObject(Object obj, SerializationInfo info, StreamingContext context) +298
   System.Runtime.Serialization.ObjectManager.FixupSpecialObject(ObjectHolder holder) +45
   System.Runtime.Serialization.ObjectManager.DoFixups() +230
   System.Runtime.Serialization.Formatters.Binary.ObjectReader.Deserialize(HeaderHandler handler, __BinaryParser serParser, Boolean fCheck, Boolean isCrossAppDomain, IMethodCallMessage methodCallMessage) +137
   System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Deserialize(Stream serializationStream, HeaderHandler handler, Boolean fCheck, Boolean isCrossAppDomain, IMethodCallMessage methodCallMessage) +186
   System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Deserialize(Stream serializationStream) +15
   System.Web.UI.ObjectStateFormatter.DeserializeValue(SerializerBinaryReader reader) +1873
   System.Web.UI.ObjectStateFormatter.DeserializeValue(SerializerBinaryReader reader) +334
   System.Web.UI.ObjectStateFormatter.DeserializeValue(SerializerBinaryReader reader) +420
   System.Web.UI.ObjectStateFormatter.DeserializeValue(SerializerBinaryReader reader) +432
   System.Web.UI.ObjectStateFormatter.DeserializeValue(SerializerBinaryReader reader) +420
   System.Web.UI.ObjectStateFormatter.Deserialize(Stream inputStream) +139

[ArgumentException: The serialized data is invalid.]
   System.Web.UI.ObjectStateFormatter.Deserialize(Stream inputStream) +203
   System.Web.UI.ObjectStateFormatter.Deserialize(String inputString, Purpose purpose) +481
   System.Web.UI.ObjectStateFormatter.System.Web.UI.IStateFormatter2.Deserialize(String serializedState, Purpose purpose) +8
   System.Web.UI.Util.DeserializeWithAssert(IStateFormatter2 formatter, String serializedState, Purpose purpose) +40
   System.Web.UI.HiddenFieldPageStatePersister.Load() +127

[ViewStateException: Invalid viewstate. 
    Client IP: ::1
    Port: 27795
    Referer: http://localhost/HolidayTracker/Report/VacationChart.aspx
    Path: /HolidayTracker/Report/VacationChart.aspx
    User-Agent: Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; WOW64; Trident/6.0)
    ViewState: /wEPDwULLTE2OTYyMjA5MzkPFgQeCnNlbGVjdGVkQnUy1p4BAAEAAAD/////AQAAAAAAAAAMAgAAAElIb2xpZGF5VHJhY2tlckRhdGEsIFZlcnNpb249MS4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1udWxsDAMAAABVU3lzdGVtLkRhdGEuRW50aXR5LCBWZXJzaW9uPTQuMC4wLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49Yjc3YTVjNTYxOTM0ZTA4OQUBAAAAKEhvbGlkYXlUcmFja2VyLkRhdGEuTW9kZWwuSHRCdXNpbmVzc1VuaXQFAAAAD19CdXNpbmVzc1VuaXRJZAVfTmFtZQ9fT3JnYW5pc2F0aW9uSWQbRW50aXR5T2JqZWN0K19yZWxhdGlvbnNoaXBzF0VudGl0eU9iamVjdCtfZW50aXR5S2V5AAEABAQICDNTeXN0ZW0uRGF0YS5PYmplY3RzLkRhdGFDbGFzc2VzLlJlbGF0aW9uc2hpcE1hbmFnZXIDAAAAFVN5c3RlbS5EYXRhLkVudGl0eUtleQMAAAACAAAAFAAAAAYEAAAABUZTLUlTDgAAAAkFAAAACQYAAAAFBQAAADNTeXN0ZW0uRGF0YS5PYmplY3RzLkRhdGFDbGFzc2VzLlJlbGF0aW9uc2hpcE1hbmFnZXICAAAABl9vd25lcg5fcmVsYXRpb25zaGlwcwQDKEhvbGlkYXl...]

[HttpException (0x80004005): The state information is invalid for this page and might be corrupted.]
   System.Web.UI.ViewStateException.ThrowError(Exception inner, String persistedState, String errorPageMessage, Boolean macValidationError) +198
   System.Web.UI.HiddenFieldPageStatePersister.Load() +266
   System.Web.UI.Page.LoadPageStateFromPersistenceMedium() +88
   System.Web.UI.Page.LoadAllState() +36
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +6704
   System.Web.UI.Page.ProcessRequest(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +245
   System.Web.UI.Page.ProcessRequest() +72
   System.Web.UI.Page.ProcessRequestWithNoAssert(HttpContext context) +21
   System.Web.UI.Page.ProcessRequest(HttpContext context) +58
   ASP.report_vacationchart_aspx.ProcessRequest(HttpContext context) in c:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\holidaytracker\ad68c354\56d80455\App_Web_k5s5ajkf.1.cs:0
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +341
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +69

Here is my Global.asax.cs

namespace HolidayTracker {
    public class Global : System.Web.HttpApplication {

        void Application_Start(object sender, EventArgs e) {
            // Code that runs on application startup

        }

        void Application_End(object sender, EventArgs e) {
            //  Code that runs on application shutdown

        }

        void Application_Error(object sender, EventArgs e) {
            // Code that runs when an unhandled error occurs

        }

        void Session_Start(object sender, EventArgs e) {
            // Code that runs when a new session is started
            if (HttpContext.Current.User != null && HttpContext.Current.User is HtUser)
            { 
                HtUser user = (HtUser)HttpContext.Current.User;
                Session["UserId"] = user.UserId;

                Session["User"] = user.LastName+" "+user.FirstName ;


                if (user.HtDepartments.Any() && user.HtDepartments.SingleOrDefault().HtBusinessUnit != null)
                {
                    int BusinessUnitId = user.HtDepartments.First().HtBusinessUnit.BusinessUnitId;
                    Session["BusinessUnnitId"] = BusinessUnitId;
                }


            }
        }

        void Session_End(object sender, EventArgs e) {
            // Code that runs when a session ends. 
            // Note: The Session_End event is raised only when the sessionstate mode
            // is set to InProc in the Web.config file. If session mode is set to StateServer 
            // or SQLServer, the event is not raised.

            //if (Session["UserId"] == null)
            //{
            //    Response.ClearContent();
            //    Response.Write("Not agine");
            //    Response.End();
            //}
            //else
            //{
            //    Response.Write(Session["UserId"].ToString());
            //}
        }

         protected void WindowsAuthentication_OnAuthenticate(Object source, WindowsAuthenticationEventArgs e)
        {
            if (Request.Cookies.Get(Constants.AUTHORIZATION_COOKIE_NAME) != null)
                return;

            String strUserIdentity;
            FormsAuthenticationTicket formsAuthTicket;
            HttpCookie httpCook;
            String strEncryptedTicket;
            AdLookup adLookup = new AdLookup();

            strUserIdentity = e.Identity.Name;

            bool loggedIn = false;
            String email = null;
            String role = null;

            email = strUserIdentity; 
            HtUser userInfo = null;
            if (email != null && email != "")
            {
                userInfo = HtUser.GetByLogin(e.Identity, email);

                if (userInfo != null && userInfo.UserName.Length > 0)
                {
                    loggedIn = true;
                    role = HtUser.GetUserRoleString(userInfo);
                }
                //Checks if user is in domain
                else
                {
                    userInfo = adLookup.GetAdUserByUsername(HtUser.getUserNameFromDomainString(email));
                    if (userInfo != null && userInfo.UserName.Length > 0)
                    {
                        loggedIn = true;
                        role = UserRoles.User;
                    }
                }
            }
            //}

            if (loggedIn)
            {
                formsAuthTicket = new FormsAuthenticationTicket(1, email, DateTime.Now,
                                                                DateTime.Now.AddMinutes(60), false, role);
                strEncryptedTicket = FormsAuthentication.Encrypt(formsAuthTicket);
                httpCook = new HttpCookie(Constants.AUTHORIZATION_COOKIE_NAME, strEncryptedTicket);
                Response.Cookies.Add(httpCook);
                HttpContext.Current.User = userInfo;
            }
            else
            {
                HttpContext.Current.User = null;
            }
        }

    }
}

I you need something more feel free to ask me !!

Thanks for help and fast answer

Mingebag
  • 748
  • 2
  • 20
  • 35
  • Do you dynamically add / remove controls from the control tree when switching between departments? – Josh Darnell Mar 14 '13 at 15:29
  • @jadarnel27 I'm not adding and also not removing controls just filtering my chart –  Mar 14 '13 at 15:51
  • Do you use integrated or classic mode for the application pool? – polybios Mar 19 '13 at 16:25
  • 1
    Make sure your application pool is not recycling. You can also have a machine key in your web.config to make sure that even if it does recycle, the viewstate will remain valid – kaspur Mar 19 '13 at 20:39
  • Please take a look at this: http://stackoverflow.com/questions/8993293/windowsidentity-impersonate-in-asp-net-randomly-invalid-token-for-impersonation – JustAndrei Mar 19 '13 at 21:06
  • @JustAndrei thanks for the link but I don't see solution for my Problem –  Mar 20 '13 at 07:56
  • @polybios where can I check that ? –  Mar 20 '13 at 08:44
  • @kaspur I have tried to use the the machine key no result –  Mar 20 '13 at 08:52
  • This may be a long call: What is the structure of the objects that you add to the viewstate? Does any of the objects (or nested members) contain any references to a WindowsIdentity (or IIdentity) object? – mortb Mar 20 '13 at 12:12
  • @mortb no I don't think so –  Mar 20 '13 at 14:19
  • I've used ViewState decoder (http://ignatu.co.uk/ViewStateDecoder.aspx) in the past to extract the information that is encoded in the viewstate. You can extract the viewstate string from you webpage and run it through viewstate decoder to try to see what it actually contains. – mortb Mar 20 '13 at 15:28
  • @mortb where are is this Base64 string or entire input tag ? in my view state or how can i get it ? –  Mar 20 '13 at 15:39
  • You'd load the page into you browser, right click on the page, select "view source" (internet explorer, it might be another context menu choice if you use another browser) in the context menu. In the html source you'd locate the __viewstate hidden field. The base64 string is the attribute named value. – mortb Mar 20 '13 at 15:55
  • @mortb the value is really giant are an if i past the hole value in the decoder I just get the message Couldn't decode the View State. The error was: 'Invalid character in a Base-64 string.' –  Mar 20 '13 at 16:03
  • 1
    (It's not uncommon that the viestate value gets really large. That's why it may be good to turn off viewstate for controls if not needed) – mortb Mar 20 '13 at 16:22
  • Have you pasted the whole value? You can try the other decoders listed in this http://stackoverflow.com/questions/22814/how-to-decode-viewstate question as well. – mortb Mar 20 '13 at 16:24
  • Have you sifted through the microsoft kb aricle yet? http://support.microsoft.com/kb/555353 – Chains Mar 20 '13 at 19:30
  • send me the code for you controls i want to check it out – Mingebag Mar 21 '13 at 13:31
  • 1
    @Mingebag thx for you offer i will send you my code then plzz delete your email ad –  Mar 21 '13 at 13:31

1 Answers1

0

Oo I see it not something big but I would you highly recommend to replace your view states with just a "normal" solution just use the values from your Rad Combo boxes its way easier but for sure this is not a real solution for you problem cause as I see its really strange I don't see the error here , for me it seems all to me Ok. but if send you your updated code back with some comments .

If you have and problems feel free to ask!¨

PS: If you wind the solution give contact me!!

Mingebag
  • 748
  • 2
  • 20
  • 35
  • seams to work GREAT THANKS FOR YOU HELP !!!!!! JUST WOW for sure i will contact you if I wound the real solution i will send you a mail but so fare your is working fine !! :D –  Mar 21 '13 at 13:40
  • be ware it not a real solution but np ^^ – Mingebag Mar 21 '13 at 13:42