protected override void OnRequestFinishImpl(TraceData.TraceData traceData) { if (System.Diagnostics.Debugger.IsAttached) { string msg = Convertors.ToXml(traceData); System.Diagnostics.Debug.WriteLine(msg); } }
public void Activate(string name, TraceData traceData = null) { if (!_traceDataRegistry.ContainsKey(name)) throw new PBException("can't activate TraceData, TraceData \"{0}\" dont exist", name); if (traceData == null) traceData = TraceData.CurrentTraceData; _traceDataRegistry[name].ActivateTraceData(traceData); }
public void OnRequestFinish(TraceData.TraceData traceData) { OnRequestFinishImpl(traceData); if (Next != null) { Next.OnRequestFinish(traceData); } }
private void SaveContent(string url, string body) { var documentStore = new DocumentStore { ConnectionStringName = "RAVENHQ_CONNECTION_STRING" }; documentStore.Initialize(); using (IDocumentSession session = documentStore.OpenSession()) { TraceData data = new TraceData(); data.Data = string.Format("{{tracedata:{0} {1} {2}}}", url, Environment.NewLine, body); // Operations against session session.Store(data); // Flush those changes session.SaveChanges(); } }
protected override void OnRequestFinishImpl(TraceData.TraceData traceData) { if (System.Diagnostics.Debugger.IsAttached) { string msg; if (TraceSwitcher.Verbosity == TraceSwitcher.TraceVerbosity.Verbose) msg = String.Format("[{0}/{1}, {2}ms] {3} {4}", traceData.StartTime.ToString("o"), traceData.LocalStartTime.ToString("o"), traceData.TotalTime, traceData.Method, traceData.Url); else msg = String.Format("[{0}, {1}ms] {2} {3}", traceData.StartTime.ToString("o"), traceData.TotalTime, traceData.Method, traceData.Url); System.Diagnostics.Debug.WriteLine(msg); } }
// this method can run on a worker thread! private void BuildNodeCollection(XmlDocument doc) { XmlDataCollection collection = null; if (doc != null) { if (TraceData.IsExtendedTraceEnabled(this, TraceDataLevel.XmlBuildCollection)) { TraceData.Trace(TraceEventType.Warning, TraceData.XmlBuildCollection( TraceData.Identify(this))); } XmlNodeList nodes = GetResultNodeList(doc); //we always create a new DataCollection collection = new XmlDataCollection(this); if (nodes != null) { collection.SynchronizeCollection(nodes); } } if (TraceData.IsExtendedTraceEnabled(this, TraceDataLevel.ProviderQuery)) { TraceData.Trace(TraceEventType.Warning, TraceData.QueryFinished( TraceData.Identify(this), Dispatcher.CheckAccess() ? "synchronous" : "asynchronous", TraceData.Identify(collection), TraceData.IdentifyException(null))); } OnQueryFinished(collection, null, CompletedCallback, doc); }
//------------------------------------------------------ // // Private Methods // //------------------------------------------------------ // Recalculate the node to be used as XPath query context; // only call this when CurrentItem changes and for Attach/Detach DataItem. // If worker was hooked up for notifications, this will UnhookNotifications() // before changing ContextNode, and then optionally HookNotifications() after. private void UpdateContextNode(bool hookNotifications) { UnHookNotifications(); if (DataItem == BindingExpressionBase.DisconnectedItem) { ContextNode = null; return; } if (CollectionView != null) { ContextNode = CollectionView.CurrentItem as XmlNode; if (ContextNode != CollectionView.CurrentItem && TraceData.IsEnabled) { TraceData.Trace(TraceEventType.Error, TraceData.XmlBindingToNonXmlCollection, XPath, ParentBindingExpression, DataItem); } } else { ContextNode = DataItem as XmlNode; if (ContextNode != DataItem && TraceData.IsEnabled) { TraceData.Trace(TraceEventType.Error, TraceData.XmlBindingToNonXml, XPath, ParentBindingExpression, DataItem); } } if (hookNotifications) { HookNotifications(); } }
private void ComputeActionName(TraceData.TraceData traceData) { var evt = traceData.Events.FirstOrDefault(e => AreEqual(e.Category, "System.Web.Http.Action") && AreEqual(e.Operation, "ExecuteAsync") && AreEqual(e.Kind, "Begin")); if (evt == null) return; traceData.ActionName = evt.Message; }
// Token: 0x06001CE1 RID: 7393 RVA: 0x00086E04 File Offset: 0x00085004 private void CreateDocFromInlineXml(XmlReader xmlReader) { if (!this._tryInlineDoc) { this._savedDocument = null; if (this._waitForInlineDoc != null) { this._waitForInlineDoc.Set(); } return; } Exception ex = null; XmlDocument xmlDocument; try { xmlDocument = new XmlDocument(); try { if (TraceData.IsExtendedTraceEnabled(this, TraceDataLevel.Transfer)) { TraceData.Trace(TraceEventType.Warning, TraceData.XmlLoadInline(new object[] { TraceData.Identify(this), base.Dispatcher.CheckAccess() ? "synchronous" : "asynchronous" })); } xmlDocument.Load(xmlReader); } catch (XmlException ex2) { if (TraceData.IsEnabled) { TraceData.Trace(TraceEventType.Error, TraceData.XmlDPInlineDocError, ex2); } ex = ex2; } if (ex == null) { this._savedDocument = (XmlDocument)xmlDocument.Clone(); } } finally { xmlReader.Close(); if (this._waitForInlineDoc != null) { this._waitForInlineDoc.Set(); } } if (TraceData.IsEnabled) { XmlNode documentElement = xmlDocument.DocumentElement; if (documentElement != null && documentElement.NamespaceURI == xmlReader.LookupNamespace(string.Empty)) { TraceData.Trace(TraceEventType.Error, TraceData.XmlNamespaceNotSet); } } if (ex == null) { this.BuildNodeCollection(xmlDocument); return; } if (TraceData.IsExtendedTraceEnabled(this, TraceDataLevel.Attach)) { TraceData.Trace(TraceEventType.Warning, TraceData.QueryFinished(new object[] { TraceData.Identify(this), base.Dispatcher.CheckAccess() ? "synchronous" : "asynchronous", TraceData.Identify(null), TraceData.IdentifyException(ex) })); } this.OnQueryFinished(null, ex, this.CompletedCallback, null); }
object InvokeMethodOnInstance(out Exception e) { object data = null; string error = null; // string that describes known error e = null; Debug.Assert(_objectType != null); object[] parameters = new object[_methodParameters.Count]; _methodParameters.CopyTo(parameters, 0); // PreSharp uses message numbers that the C# compiler doesn't know about. // Disable the C# complaints, per the PreSharp documentation. #pragma warning disable 1634, 1691 // PreSharp complains about catching NullReference (and other) exceptions. // It doesn't recognize that IsCritical[Application]Exception() handles these correctly. #pragma warning disable 56500 try { data = _objectType.InvokeMember(MethodName, s_invokeMethodFlags, null, _objectInstance, parameters, System.Globalization.CultureInfo.InvariantCulture); } catch (ArgumentException ae) { error = "Parameter array contains a string that is a null reference."; e = ae; } catch (MethodAccessException mae) { error = "The specified member is a class initializer."; e = mae; } catch (MissingMethodException mme) { error = "No method was found with matching parameter signature."; e = mme; } catch (TargetException te) { error = "The specified member cannot be invoked on target."; e = te; } catch (AmbiguousMatchException ame) { error = "More than one method matches the binding criteria."; e = ame; } // Catch all exceptions. When there is no app code on the stack, // the exception isn't actionable by the app. // Yet we don't want to crash the app. catch (Exception ex) { if (CriticalExceptions.IsCriticalApplicationException(ex)) { throw; } error = null; // indicate unknown error e = ex; } catch //FXCop Fix: CatchNonClsCompliantExceptionsInGeneralHandlers { error = null; // indicate unknown error e = new InvalidOperationException(SR.Get(SRID.ObjectDataProviderNonCLSExceptionInvoke, MethodName, _objectType.Name)); } #pragma warning restore 56500 #pragma warning restore 1634, 1691 if (e != null || error != null) { // report known errors through TraceData (instead of throwing exceptions) if (TraceData.IsEnabled) { TraceData.Trace(TraceEventType.Error, TraceData.ObjDPInvokeFailed, MethodName, _objectType.Name, error, e); } // in async mode we pass all exceptions to main thread; // in [....] mode we don't handle unknown exceptions. if (!IsAsynchronous && error == null) { throw e; } } return(data); }
// Token: 0x060075FB RID: 30203 RVA: 0x0021A3F0 File Offset: 0x002185F0 internal override object GetObject(DependencyObject d, ObjectRefArgs args) { if (d == null) { throw new ArgumentNullException("d"); } object obj = null; if (args.ResolveNamesInTemplate) { FrameworkElement frameworkElement = d as FrameworkElement; if (frameworkElement != null && frameworkElement.TemplateInternal != null) { obj = Helper.FindNameInTemplate(this._name, d); if (args.IsTracing) { TraceData.Trace(TraceEventType.Warning, TraceData.ElementNameQueryTemplate(new object[] { this._name, TraceData.Identify(d) })); } } if (obj == null) { args.NameResolvedInOuterScope = true; } } FrameworkObject frameworkObject = new FrameworkObject(d); while (obj == null && frameworkObject.DO != null) { DependencyObject dependencyObject; obj = frameworkObject.FindName(this._name, out dependencyObject); if (d == dependencyObject && d is IComponentConnector && d.ReadLocalValue(NavigationService.NavigationServiceProperty) == DependencyProperty.UnsetValue) { DependencyObject dependencyObject2 = LogicalTreeHelper.GetParent(d); if (dependencyObject2 == null) { dependencyObject2 = Helper.FindMentor(d.InheritanceContext); } if (dependencyObject2 != null) { obj = null; frameworkObject.Reset(dependencyObject2); continue; } } if (args.IsTracing) { TraceData.Trace(TraceEventType.Warning, TraceData.ElementNameQuery(new object[] { this._name, TraceData.Identify(frameworkObject.DO) })); } if (obj == null) { args.NameResolvedInOuterScope = true; FrameworkObject frameworkObject2 = new FrameworkObject(dependencyObject); DependencyObject dependencyObject3 = frameworkObject2.TemplatedParent; if (dependencyObject3 == null) { Panel panel = frameworkObject.FrameworkParent.DO as Panel; if (panel != null && panel.IsItemsHost) { dependencyObject3 = panel; } } if (dependencyObject3 == null && dependencyObject == null) { ContentControl contentControl = LogicalTreeHelper.GetParent(frameworkObject.DO) as ContentControl; if (contentControl != null && contentControl.Content == frameworkObject.DO && contentControl.InheritanceBehavior == InheritanceBehavior.Default) { dependencyObject3 = contentControl; } } if (dependencyObject3 == null && dependencyObject == null) { dependencyObject3 = frameworkObject.DO; for (;;) { DependencyObject dependencyObject4 = LogicalTreeHelper.GetParent(dependencyObject3); if (dependencyObject4 == null) { dependencyObject4 = Helper.FindMentor(dependencyObject3.InheritanceContext); } if (dependencyObject4 == null) { break; } dependencyObject3 = dependencyObject4; } ContentPresenter contentPresenter = VisualTreeHelper.IsVisualType(dependencyObject3) ? (VisualTreeHelper.GetParent(dependencyObject3) as ContentPresenter) : null; dependencyObject3 = ((contentPresenter != null && contentPresenter.TemplateInternal.CanBuildVisualTree) ? contentPresenter : null); } frameworkObject.Reset(dependencyObject3); } } if (obj == null) { obj = DependencyProperty.UnsetValue; args.NameResolvedInOuterScope = false; } return(obj); }
public void ProcessorComplete(TraceData td) { if ((Statements.Count == 0) && currentStatement == null) { return; } /* add final sql statement */ Statements.Add(currentStatement); /* Group them all by Where */ var sqlByWhereList = td.SQLByWhere; var byWheres = Statements.Where(p => p.Type != SQLType.INSERT).GroupBy(p => p.WhereClause).Select(g => new SQLByWhere { NumberOfCalls = g.Count(), TotalTime = g.Sum(i => i.Duration), WhereClause = g.Key, HasError = g.Count(p => p.IsError) > 0 ? true : false }); foreach (var byW in byWheres) { sqlByWhereList.Add(byW); } var sqlByFromList = td.SQLByFrom; var byFroms = Statements.Where(p => p.Type == SQLType.SELECT || p.Type == SQLType.DELETE).GroupBy(p => p.FromClause).Select(g => new SQLByFrom { NumberOfCalls = g.Count(), TotalTime = g.Sum(i => i.Duration), FromClause = g.Key, HasError = g.Count(p => p.IsError) > 0 ? true : false }); foreach (var byF in byFroms) { sqlByFromList.Add(byF); } td.Statistics.Add(new StatisticItem() { Category = "SQL Statements", Label = "Total Count", Value = Statements.Count.ToString() }); SQLStatement longest = Statements.OrderBy(s => s.Duration).Reverse().First(); td.Statistics.Add(new StatisticItem() { Category = "SQL Statements", Label = "Longest Execution", Value = longest.Duration.ToString(), Tag = longest }); SQLStatement mostFetches = Statements.OrderBy(s => s.FetchCount).Reverse().First(); td.Statistics.Add(new StatisticItem() { Category = "SQL Statements", Label = "Most Fetches", Value = mostFetches.FetchCount.ToString(), Tag = mostFetches }); td.Statistics.Add(new StatisticItem() { Category = "SQL Statements", Label = "Total SQL Time", Value = Statements.Sum(s => s.Duration).ToString() }); td.Statistics.Add(new StatisticItem() { Category = "SQL Statements", Label = "Total SELECT Time", Value = Statements.Where(s => s.Type == SQLType.SELECT).Sum(s => s.Duration).ToString() }); td.Statistics.Add(new StatisticItem() { Category = "SQL Statements", Label = "Total UPDATE Time", Value = Statements.Where(s => s.Type == SQLType.UPDATE).Sum(s => s.Duration).ToString() }); td.Statistics.Add(new StatisticItem() { Category = "SQL Statements", Label = "Total INSERT Time", Value = Statements.Where(s => s.Type == SQLType.INSERT).Sum(s => s.Duration).ToString() }); td.Statistics.Add(new StatisticItem() { Category = "SQL Statements", Label = "Total DELETE Time", Value = Statements.Where(s => s.Type == SQLType.DELETE).Sum(s => s.Duration).ToString() }); }
//------------------------------------------------------ // // Private API // //------------------------------------------------------ private object ConvertHelper(object o, Type destinationType, DependencyObject targetElement, CultureInfo culture, bool isForward) { object value = DependencyProperty.UnsetValue; bool needAssignment = (isForward ? !_shouldConvertTo : !_shouldConvertFrom); NotSupportedException savedEx = null; if (!needAssignment) { value = TryParse(o, destinationType, culture); if (value == DependencyProperty.UnsetValue) { ValueConverterContext ctx = Engine.ValueConverterContext; // The fixed VCContext object is usually available for re-use. // In the rare cases when a second conversion is requested while // a previous conversion is still in progress, we allocate a temporary // context object to handle the re-entrant request. if (ctx.IsInUse) { ctx = new ValueConverterContext(); } try { ctx.SetTargetElement(targetElement); if (isForward) { value = _typeConverter.ConvertTo(ctx, culture, o, destinationType); } else { value = _typeConverter.ConvertFrom(ctx, culture, o); } } catch (NotSupportedException ex) { needAssignment = true; savedEx = ex; } finally { ctx.SetTargetElement(null); } } } if (needAssignment && ((o != null && destinationType.IsAssignableFrom(o.GetType())) || (o == null && !destinationType.IsValueType))) { value = o; needAssignment = false; } if (TraceData.IsEnabled) { if ((culture != null) && (savedEx != null)) { TraceData.Trace(TraceEventType.Error, TraceData.DefaultValueConverterFailedForCulture( AvTrace.ToStringHelper(o), AvTrace.TypeName(o), destinationType.ToString(), culture), savedEx); } else if (needAssignment) { TraceData.Trace(TraceEventType.Error, TraceData.DefaultValueConverterFailed( AvTrace.ToStringHelper(o), AvTrace.TypeName(o), destinationType.ToString()), savedEx); } } if (needAssignment && savedEx != null) { throw savedEx; } return(value); }
private void PublishRaceTrace(TraceData traceData) { _raceTraceSubject.OnNext(traceData); }
protected override void Write(TraceClass info) { TraceData.Enqueue(info); }
private static String GetMarkdown(AppTracer app, AppMinuteStat st, Boolean includeTitle) { var sb = new StringBuilder(); if (includeTitle) { sb.AppendLine($"### [{app}]系统告警"); } sb.AppendLine($">**总数:**<font color=\"info\">{st.Errors}</font>"); var url = Setting.Current.WebUrl; var appUrl = ""; var traceUrl = ""; if (!url.IsNullOrEmpty()) { appUrl = url.EnsureEnd("/") + "Monitors/appMinuteStat?appId=" + st.AppId + "&minError=1"; traceUrl = url.EnsureEnd("/") + "Monitors/traceMinuteStat?appId=" + st.AppId + "&minError=1"; } // 找找具体接口错误 var names = new List <String>(); var sts = TraceMinuteStat.FindAllByAppIdAndTime(st.AppId, st.StatTime).OrderByDescending(e => e.Errors).ToList(); foreach (var item in sts) { if (item.Errors > 0) { sb.AppendLine($">**错误:**<font color=\"info\">{item.StatTime.ToFullString()} 埋点[{item.Name}]共报错[{item.Errors:n0}]次</font>[更多]({traceUrl}&name={HttpUtility.UrlEncode(item.Name)})"); // 相同接口的错误,不要报多次 if (!names.Contains(item.Name)) { var ds = TraceData.Search(st.AppId, item.Name, "minute", item.StatTime, 20); if (ds.Count > 0) { var sms = SampleData.FindAllByDataIds(ds.Select(e => e.Id).ToArray()).Where(e => !e.Error.IsNullOrEmpty()).ToList(); if (sms.Count > 0) { var msg = sms[0].Error?.Trim(); if (!msg.IsNullOrEmpty()) { // 错误内容取第一行,详情看更多 var p = msg.IndexOfAny(new[] { '\r', '\n' }); if (p > 0) { msg = msg.Substring(0, p); } sb.AppendLine($">**错误内容:**{msg}"); names.Add(item.Name); } } } } } } var str = sb.ToString(); if (str.Length > 1600) { str = str.Substring(0, 1600); } // 构造网址 if (!appUrl.IsNullOrEmpty()) { str += Environment.NewLine + $"[更多信息]({appUrl})"; } return(str); }
public void DesactivateTraceData() { _traceData = null; }
public void ActivateTraceData(TraceData traceData) { _traceData = traceData; }
protected abstract void OnRequestFinishImpl(TraceData.TraceData traceData);
private void ComputeControllerName(TraceData.TraceData traceData) { var evt = traceData.Events.FirstOrDefault(e => AreEqual(e.Category, "System.Web.Http.Controllers") && AreEqual(e.Operation, "Create") && AreEqual(e.Kind, "End")); if (evt == null) return; traceData.ControllerName = evt.Message; }
private void ComputeTotalTime(TraceData.TraceData traceData) { traceData.EndTime = _time.UtcNow; TimeSpan ts = traceData.EndTime.GetValueOrDefault() - traceData.StartTime; traceData.TotalTime = ts.TotalMilliseconds; }
public void PushState(int[] s_t) { if (m_traceData.Count > 0 && s_t.Length != m_traceData[0].S_t.Length) { m_traceData.Clear(); } while (m_traceData.Count >= m_learning.TraceLength) { m_traceData.RemoveAt(m_traceData.Count - 1); } int[] inserted = s_t.Clone() as int[]; TraceData tmp = new TraceData(inserted, 0); m_traceData.Insert(0, tmp); }
public override Color GetColor(Raytracer raytracer, Ray ray, RaycastHit hit, TraceData traceData) { Vector2 texCoord; Vector3 surfaceNormal; Vector3 tangent, binormal; bool texCoordAndTangentRequired = NormalMap != null || DiffuseTexture != null || SpecularMap != null || ReflectionMap != null; texCoordAndTangentRequired = true; // DEBUG if (texCoordAndTangentRequired) { Vector3 localNormal; Vector3 localTangent; ColliderUtils.GetTexCoordAndTangent( hit, out texCoord, out localNormal, out localTangent ); tangent = hit.collider.transform.TransformDirection(localTangent); surfaceNormal = hit.collider.transform.TransformDirection(localNormal); binormal = Vector3.Cross(tangent, surfaceNormal); #region Debug Visualisation #if DEBUG_SHOW_TEX_COORDS return(new Color(texCoord.x, texCoord.y, 0, 1)); #endif #if DEBUG_SHOW_BARYCENTRIC_COORDS Vector3 dbgBc = hit.barycentricCoordinate; return(new Color(dbgBc.x, dbgBc.y, dbgBc.z, 1)); #endif #if DEBUG_SHOW_NORMALS Vector3 dbgLocalNormal = localNormal; //dbgLocalNormal = new Vector3 ( // Mathf.Abs ( dbgLocalNormal.x ), // Mathf.Abs ( dbgLocalNormal.y ), // Mathf.Abs ( dbgLocalNormal.z ) //); dbgLocalNormal = (dbgLocalNormal + Vector3.one) * 0.5f; return(new Color(dbgLocalNormal.x, dbgLocalNormal.y, dbgLocalNormal.z, 1)); #endif #if DEBUG_SHOW_TANGENTS Vector3 dbgLocalTangent = localTangent; if (false) { dbgLocalTangent = new Vector3( Mathf.Abs(dbgLocalTangent.x), Mathf.Abs(dbgLocalTangent.y), Mathf.Abs(dbgLocalTangent.z) ); } else if (false) { dbgLocalTangent = new Vector3( Mathf.Abs(dbgLocalTangent.x > 0 ? dbgLocalTangent.x : 0), Mathf.Abs(dbgLocalTangent.y > 0 ? dbgLocalTangent.y : 0), Mathf.Abs(dbgLocalTangent.z > 0 ? dbgLocalTangent.z : 0) ); } else { dbgLocalTangent = (dbgLocalTangent + Vector3.one) * 0.5f; } return(new Color(dbgLocalTangent.x, dbgLocalTangent.y, dbgLocalTangent.z, 1)); #endif #if DEBUG_SHOW_BINORMALS Vector3 localBinormal = Vector3.Cross(localTangent, localNormal); Vector3 dbgBinormal = localBinormal; dbgBinormal = new Vector3( Mathf.Abs(dbgBinormal.x), Mathf.Abs(dbgBinormal.y), Mathf.Abs(dbgBinormal.z) ); return(new Color(dbgBinormal.x, dbgBinormal.y, dbgBinormal.z, 1)); #endif #endregion Debug Visualisation } else { texCoord = Vector2.zero; surfaceNormal = hit.normal; tangent = Vector3.zero; binormal = Vector3.zero; } bool entering = Vector3.Dot(hit.normal, ray.direction) <= 0; surfaceNormal = entering ? surfaceNormal : -surfaceNormal; /* TODO: revise where "entering" calculated upon hit.normal should be replaced * with "entering" calculated upon surfaceNormal transformed with TBN. */ if (NormalMap != null && NormalMapInfluence > 0) { var normalMapRt = TextureCache.FromUnityTexture(NormalMap); Color normalMapColor = normalMapRt.GetFilteredPixel(texCoord.x, texCoord.y); Vector3 texNormal = new Vector3(normalMapColor.r, normalMapColor.g, normalMapColor.b); texNormal = 2 * texNormal - Vector3.one; texNormal.Normalize(); Vector3 texNormalWorld = Raytracer.TransformTbn(texNormal, tangent, binormal, surfaceNormal); float normalMapInfluence = Mathf.Clamp01(NormalMapInfluence); surfaceNormal = Vector3.Lerp(surfaceNormal, texNormalWorld, normalMapInfluence).normalized; #if DEBUG_SHOW_SURFACE_NORMALS Vector3 dbgSurfaceNormal = surfaceNormal; //dbgSurfaceNormal = new Vector3 ( // Mathf.Abs ( dbgSurfaceNormal.x ), // Mathf.Abs ( dbgSurfaceNormal.y ), // Mathf.Abs ( dbgSurfaceNormal.z ) //); dbgSurfaceNormal = (dbgSurfaceNormal + Vector3.one) * 0.5f; return(new Color(dbgSurfaceNormal.x, dbgSurfaceNormal.y, dbgSurfaceNormal.z, 1)); #endif } float specularIntensity = SpecularComponent; if (SpecularMap != null && SpecularMapInfluence > 0 && specularIntensity > 0) { var specularMapRt = TextureCache.FromUnityTexture(SpecularMap); Color specularMapColor = specularMapRt.GetFilteredPixel(texCoord.x, texCoord.y); specularIntensity *= specularMapColor.grayscale * specularMapColor.a; float specularMapInfluence = Mathf.Clamp01(SpecularMapInfluence); specularIntensity = Mathf.Lerp(SpecularComponent, specularIntensity, specularMapInfluence); } Color totalColor = Color.black; Color diffuseLightSumColor = raytracer.OverrideAmbientLight ? raytracer.AmbientLight : RenderSettings.ambientLight; diffuseLightSumColor *= DiffuseComponent; Color specularLightSumColor = Color.black; var lights = Light.GetLights(LightType.Point, 0); foreach (var light in lights) { Vector3 vToLight = light.transform.position - hit.point; float lightVolumeRadius = light.range * 0.00625f; // Empirical coefficient. float distance = vToLight.magnitude - lightVolumeRadius; if (distance < 0) { distance = 0; } else if (distance >= light.range) { continue; } Vector3 dirToLight = vToLight.normalized; float attenuation; attenuation = 1 - distance / light.range; attenuation = attenuation * attenuation; float lightIntensity = light.intensity * LightIntensityFactor; if (DiffuseComponent > 0) { float diffuseIntensity = Vector3.Dot(dirToLight, surfaceNormal); if (diffuseIntensity > 0) { diffuseIntensity = Mathf.Pow(diffuseIntensity, DiffuseExponent); Color diffuseLightColor = light.color * attenuation * diffuseIntensity * lightIntensity; diffuseLightSumColor += diffuseLightColor; } } if (specularIntensity > 0) { Vector3 reflectionDir = Vector3.Reflect(-dirToLight, surfaceNormal); Vector3 vToView = raytracer.Camera.transform.position - hit.point; Vector3 dirToView = vToView.normalized; float specularity = Vector3.Dot(reflectionDir, dirToView); if (specularity > 0) { specularity = Mathf.Pow(specularity, SpecularPower); Color specularLightColor = light.color * attenuation * specularity * lightIntensity; specularLightSumColor += specularLightColor; } } } Color diffuseColor; if (DiffuseTexture != null) { var diffuseTextureRt = TextureCache.FromUnityTexture(DiffuseTexture); // TODO: calculate miplevel, get the color according to its value. Color texColor = diffuseTextureRt.GetFilteredPixel(texCoord.x, texCoord.y); if (texColor.a < 1 && DiffuseColorIsBackground) { diffuseColor = Color.Lerp(this.DiffuseColor, texColor, texColor.a); } else { diffuseColor = Color.Lerp(Color.black, texColor, texColor.a); } diffuseColor.a = texColor.a; } else { diffuseColor = this.DiffuseColor; } totalColor = diffuseLightSumColor * diffuseColor * DiffuseComponent + specularLightSumColor * specularIntensity; if (raytracer.MustInterrupt(totalColor, traceData)) { return(totalColor); } bool willReflect; float reflectionIntensity; if (entering) { willReflect = ReflectionComponent > 0 && traceData.NumReflections < raytracer.MaxReflections; reflectionIntensity = ReflectionComponent; } else { willReflect = InnerReflectionComponent > 0 && traceData.NumInnerReflections < raytracer.MaxInnerReflections; reflectionIntensity = InnerReflectionComponent; } if (willReflect && ReflectionMap != null && ReflectionMapInfluence > 0) { var reflectionMapRt = TextureCache.FromUnityTexture(ReflectionMap); Color reflectionMapColor = reflectionMapRt.GetFilteredPixel(texCoord.x, texCoord.y); float reflectionMapIntensity = reflectionMapColor.grayscale * reflectionMapColor.a; float reflectionMapInfluence = Mathf.Clamp01(ReflectionMapInfluence); reflectionIntensity = Mathf.Lerp(reflectionIntensity, reflectionMapIntensity * reflectionIntensity, reflectionMapInfluence); willReflect = reflectionIntensity > 0; } float refractionIntensity = RefractionComponent; if (RefractWhereTranslucent) { refractionIntensity *= 1 - diffuseColor.a * DiffuseComponent; } bool willRefract = refractionIntensity > 0 && traceData.NumRefractions < raytracer.MaxRefractions; bool forkingRequired = willReflect && willRefract; TraceData tdForRefraction; if (forkingRequired) { tdForRefraction = traceData.Fork(); } else { tdForRefraction = traceData; } if (willReflect) { if (entering) { traceData.NumReflections++; traceData.Counters.Reflections++; } else { traceData.NumInnerReflections++; traceData.Counters.InnerReflections++; } Vector3 reflectionDir = Vector3.Reflect(ray.direction, surfaceNormal); Vector3 pushedOutPoint = hit.point + reflectionDir * Raytracer.PushOutMagnitude; Color reflectionColor = raytracer.Trace(new Ray(pushedOutPoint, reflectionDir), traceData); totalColor += reflectionColor * reflectionIntensity; if (raytracer.MustInterrupt(totalColor, traceData)) { return(totalColor); } } if (willRefract) { tdForRefraction.NumRefractions++; tdForRefraction.Counters.Refractions++; CoefficientOut = RefractionIndex; CoefficientIn = 1 / RefractionIndex; if (CoefficientOut > 1) { CriticalOutAngleCos = Mathf.Sqrt(1 - CoefficientIn * CoefficientIn); CriticalInAngleCos = 0; } else { CriticalOutAngleCos = 0; CriticalInAngleCos = Mathf.Sqrt(1 - CoefficientOut * CoefficientOut); } float criticalAngleCos = entering ? CriticalInAngleCos : CriticalOutAngleCos; Vector3 refractionDir; float nDotRay = Vector3.Dot(surfaceNormal, ray.direction); if (Mathf.Abs(nDotRay) >= criticalAngleCos) { if (entering) { tdForRefraction.PenetrationStack.Push(hit); } else { tdForRefraction.PenetrationStack.Pop(); } float k = entering ? CoefficientIn : CoefficientOut; refractionDir = Raytracer.Refract(ray.direction, surfaceNormal, nDotRay, k); refractionDir.Normalize(); } else // Total internal reflection. { refractionDir = Vector3.Reflect(ray.direction, surfaceNormal); } Vector3 pushedOutPoint = hit.point + refractionDir * Raytracer.PushOutMagnitude; Color refractionColor = raytracer.Trace(new Ray(pushedOutPoint, refractionDir), tdForRefraction); if (ColorAberration != 0 && entering) { //float rDotRay = Vector3.Dot ( refractionDir, ray.direction ); refractionColor = HsvColor.ChangeHue(refractionColor, (1 + nDotRay) * ColorAberration); } totalColor += refractionColor * refractionIntensity; if (raytracer.MustInterrupt(totalColor, tdForRefraction)) { return(totalColor); } } return(totalColor); }
private void ProcessData(AppTracer app, TraceModel model, String ip, ISpanBuilder[] builders) { // 排除项 var excludes = app.Excludes.Split(",", ";") ?? new String[0]; var now = DateTime.Now; var traces = new List <TraceData>(); var samples = new List <SampleData>(); foreach (var item in builders) { // 剔除指定项 if (item.Name.IsNullOrEmpty()) { continue; } if (excludes != null && excludes.Any(e => e.IsMatch(item.Name))) { continue; } if (item.Name.EndsWithIgnoreCase("/Trace/Report")) { continue; } // 拒收超长项 if (item.Name.Length > TraceData._.Name.Length) { continue; } var td = TraceData.Create(item); td.AppId = app.ID; td.ClientId = model.ClientId ?? ip; td.CreateIP = ip; td.CreateTime = now; traces.Add(td); samples.AddRange(SampleData.Create(td, item.Samples, true)); samples.AddRange(SampleData.Create(td, item.ErrorSamples, false)); } traces.Insert(true); samples.Insert(true); // 更新统计 _stat.Add(traces); _appStat.Add(now.Date); if (now.Hour == 0 && now.Minute <= 10) { _appStat.Add(now.Date.AddDays(-1)); } if (!ip.IsNullOrEmpty() && ip.Length >= 3) { // 应用节点数 var nodes = app.Nodes?.Split(",").ToList() ?? new List <String>(); if (!nodes.Contains(ip)) { // 如果超过一定时间没有更新,则刷新它 if (_cache.Add("appNodes:" + app.ID, 1, 3600)) { nodes.Clear(); } nodes.Insert(0, ip); if (nodes.Count > 32) { nodes = nodes.Take(32).ToList(); } // 排序,避免Nodes字段频繁更新 app.Nodes = nodes.OrderBy(e => e).Join(); app.SaveAsync(); } } }
// Token: 0x06001C23 RID: 7203 RVA: 0x00083FF4 File Offset: 0x000821F4 private void AttachToContext(bool lastChance) { DependencyObject targetElement = base.TargetElement; if (targetElement == null) { return; } bool flag = TraceData.IsExtendedTraceEnabled(this, TraceDataLevel.Attach); this._converter = this.ParentMultiBinding.Converter; if (this._converter == null && string.IsNullOrEmpty(base.EffectiveStringFormat)) { TraceData.Trace(TraceEventType.Error, TraceData.MultiBindingHasNoConverter, this.ParentMultiBinding); } if (flag) { TraceData.Trace(TraceEventType.Warning, TraceData.AttachToContext(new object[] { TraceData.Identify(this), lastChance ? " (last chance)" : string.Empty })); } base.TransferIsDeferred = true; bool flag2 = true; int count = this.MutableBindingExpressions.Count; for (int i = 0; i < count; i++) { if (this.MutableBindingExpressions[i].StatusInternal == BindingStatusInternal.Unattached) { flag2 = false; } } if (!flag2 && !lastChance) { if (flag) { TraceData.Trace(TraceEventType.Warning, TraceData.ChildNotAttached(new object[] { TraceData.Identify(this) })); } return; } if (base.UsesLanguage) { WeakDependencySource[] commonSources = new WeakDependencySource[] { new WeakDependencySource(base.TargetElement, FrameworkElement.LanguageProperty) }; WeakDependencySource[] newSources = BindingExpressionBase.CombineSources(-1, this.MutableBindingExpressions, this.MutableBindingExpressions.Count, null, commonSources); base.ChangeSources(newSources); } bool flag3 = base.IsOneWayToSource; object newValue; if (base.ShouldUpdateWithCurrentValue(targetElement, out newValue)) { flag3 = true; base.ChangeValue(newValue, false); base.NeedsUpdate = true; } base.SetStatus(BindingStatusInternal.Active); if (!flag3) { this.UpdateTarget(false); return; } base.UpdateValue(); }
public void ProcessorInit(TraceData data) { Statements = data.SQLStatements; Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-US"); }
// Token: 0x06001C2E RID: 7214 RVA: 0x000844B0 File Offset: 0x000826B0 private bool ConvertProposedValueImpl(object value, out object result) { DependencyObject targetElement = base.TargetElement; if (targetElement == null) { result = DependencyProperty.UnsetValue; return(false); } result = this.GetValuesForChildBindings(value); if (base.IsDetached) { return(false); } if (result == DependencyProperty.UnsetValue) { base.SetStatus(BindingStatusInternal.UpdateSourceError); return(false); } object[] array = (object[])result; if (array == null) { if (TraceData.IsEnabled) { TraceData.Trace(TraceEventType.Error, TraceData.BadMultiConverterForUpdate(new object[] { this.Converter.GetType().Name, AvTrace.ToStringHelper(value), AvTrace.TypeName(value) }), this); } result = DependencyProperty.UnsetValue; return(false); } if (TraceData.IsExtendedTraceEnabled(this, TraceDataLevel.Transfer)) { for (int i = 0; i < array.Length; i++) { TraceData.Trace(TraceEventType.Warning, TraceData.UserConvertBackMulti(new object[] { TraceData.Identify(this), i, TraceData.Identify(array[i]) })); } } int num = this.MutableBindingExpressions.Count; if (array.Length != num && TraceData.IsEnabled) { TraceData.Trace(TraceEventType.Information, TraceData.MultiValueConverterMismatch, new object[] { this.Converter.GetType().Name, num, array.Length, TraceData.DescribeTarget(targetElement, base.TargetProperty) }); } if (array.Length < num) { num = array.Length; } bool result2 = true; for (int j = 0; j < num; j++) { value = array[j]; if (value != Binding.DoNothing && value != DependencyProperty.UnsetValue) { BindingExpressionBase bindingExpressionBase = this.MutableBindingExpressions[j]; bindingExpressionBase.SetValue(targetElement, base.TargetProperty, value); value = bindingExpressionBase.GetRawProposedValue(); if (!bindingExpressionBase.Validate(value, ValidationStep.RawProposedValue)) { value = DependencyProperty.UnsetValue; } value = bindingExpressionBase.ConvertProposedValue(value); } else if (value == DependencyProperty.UnsetValue && TraceData.IsEnabled) { TraceData.Trace(TraceEventType.Information, TraceData.UnsetValueInMultiBindingExpressionUpdate(new object[] { this.Converter.GetType().Name, AvTrace.ToStringHelper(value), j, this._tempTypes[j] }), this); } if (value == DependencyProperty.UnsetValue) { result2 = false; } array[j] = value; } Array.Clear(this._tempTypes, 0, this._tempTypes.Length); result = array; return(result2); }
public void ProcessorInit(TraceData data) { ctx = new ExecutionContext("App Engine Trace"); _data = data; }
// Token: 0x06001C41 RID: 7233 RVA: 0x00084DEC File Offset: 0x00082FEC private void TransferValue() { base.IsInTransfer = true; base.NeedsDataTransfer = false; DependencyObject targetElement = base.TargetElement; if (targetElement != null) { bool flag = TraceData.IsExtendedTraceEnabled(this, TraceDataLevel.Transfer); object obj = DependencyProperty.UnsetValue; object obj2 = this._tempValues; CultureInfo culture = base.GetCulture(); int count = this.MutableBindingExpressions.Count; for (int i = 0; i < count; i++) { this._tempValues[i] = this.MutableBindingExpressions[i].GetValue(targetElement, base.TargetProperty); if (flag) { TraceData.Trace(TraceEventType.Warning, TraceData.GetRawValueMulti(new object[] { TraceData.Identify(this), i, TraceData.Identify(this._tempValues[i]) })); } } if (this.Converter != null) { obj2 = this.Converter.Convert(this._tempValues, base.TargetProperty.PropertyType, this.ParentMultiBinding.ConverterParameter, culture); if (base.IsDetached) { return; } if (flag) { TraceData.Trace(TraceEventType.Warning, TraceData.UserConverter(new object[] { TraceData.Identify(this), TraceData.Identify(obj2) })); } } else if (base.EffectiveStringFormat != null) { for (int j = 0; j < this._tempValues.Length; j++) { if (this._tempValues[j] == DependencyProperty.UnsetValue) { obj2 = DependencyProperty.UnsetValue; break; } } } else { if (TraceData.IsEnabled) { TraceData.Trace(TraceEventType.Error, TraceData.MultiValueConverterMissingForTransfer, this); goto IL_371; } goto IL_371; } if (base.EffectiveStringFormat == null || obj2 == Binding.DoNothing || obj2 == DependencyProperty.UnsetValue) { obj = obj2; } else { try { if (obj2 == this._tempValues) { obj = string.Format(culture, base.EffectiveStringFormat, this._tempValues); } else { obj = string.Format(culture, base.EffectiveStringFormat, new object[] { obj2 }); } if (flag) { TraceData.Trace(TraceEventType.Warning, TraceData.FormattedValue(new object[] { TraceData.Identify(this), TraceData.Identify(obj) })); } } catch (FormatException) { obj = DependencyProperty.UnsetValue; if (flag) { TraceData.Trace(TraceEventType.Warning, TraceData.FormattingFailed(new object[] { TraceData.Identify(this), base.EffectiveStringFormat })); } } } Array.Clear(this._tempValues, 0, this._tempValues.Length); if (obj != Binding.DoNothing) { if (base.EffectiveTargetNullValue != DependencyProperty.UnsetValue && BindingExpressionBase.IsNullValue(obj)) { obj = base.EffectiveTargetNullValue; if (flag) { TraceData.Trace(TraceEventType.Warning, TraceData.NullConverter(new object[] { TraceData.Identify(this), TraceData.Identify(obj) })); } } if (obj != DependencyProperty.UnsetValue && !base.TargetProperty.IsValidValue(obj)) { if (TraceData.IsEnabled) { TraceData.Trace(base.TraceLevel, TraceData.BadValueAtTransfer, obj, this); } if (flag) { TraceData.Trace(TraceEventType.Warning, TraceData.BadValueAtTransferExtended(new object[] { TraceData.Identify(this), TraceData.Identify(obj) })); } obj = DependencyProperty.UnsetValue; } if (obj == DependencyProperty.UnsetValue) { obj = base.UseFallbackValue(); if (flag) { TraceData.Trace(TraceEventType.Warning, TraceData.UseFallback(new object[] { TraceData.Identify(this), TraceData.Identify(obj) })); } } if (flag) { TraceData.Trace(TraceEventType.Warning, TraceData.TransferValue(new object[] { TraceData.Identify(this), TraceData.Identify(obj) })); } bool flag2 = !base.IsInUpdate || !ItemsControl.EqualsEx(obj, base.Value); if (flag2) { base.ChangeValue(obj, true); base.Invalidate(false); Validation.ClearInvalid(this); } base.Clean(); if (flag2) { this.OnTargetUpdated(); } } } IL_371: base.IsInTransfer = false; }
object CreateObjectInstance(out Exception e) { object instance = null; string error = null; // string that describes known error e = null; // PreSharp uses message numbers that the C# compiler doesn't know about. // Disable the C# complaints, per the PreSharp documentation. #pragma warning disable 1634, 1691 // PreSharp complains about catching NullReference (and other) exceptions. // It doesn't recognize that IsCritical[Application]Exception() handles these correctly. #pragma warning disable 56500 Debug.Assert(_objectType != null); try { object[] parameters = new object[_constructorParameters.Count]; _constructorParameters.CopyTo(parameters, 0); instance = Activator.CreateInstance(_objectType, 0, null, parameters, System.Globalization.CultureInfo.InvariantCulture); OnPropertyChanged(s_instance); } catch (ArgumentException ae) { // this may fire when trying to create Context Affinity objects error = "Cannot create Context Affinity object."; e = ae; } catch (System.Runtime.InteropServices.COMException ce) { // this may fire due to marshalling issues error = "Marshaling issue detected."; e = ce; } catch (System.MissingMethodException mme) { // this may be due to setting parameters to a non parameter // only class contructor error = "Wrong parameters for constructor."; e = mme; } // Catch all exceptions. When there is no app code on the stack, // the exception isn't actionable by the app. // Yet we don't want to crash the app. catch (Exception ex) { if (CriticalExceptions.IsCriticalApplicationException(ex)) { throw; } error = null; // indicate unknown error e = ex; } catch // non CLS compliant exception { error = null; // indicate unknown error e = new InvalidOperationException(SR.Get(SRID.ObjectDataProviderNonCLSException, _objectType.Name)); } #pragma warning restore 56500 #pragma warning restore 1634, 1691 if (e != null || error != null) { // report known errors through TraceData (instead of throwing exceptions) if (TraceData.IsEnabled) { TraceData.Trace(TraceEventType.Error, TraceData.ObjDPCreateFailed, _objectType.Name, error, e); } // in async mode we pass all exceptions to main thread; // in [....] mode we don't handle unknown exceptions. if (!IsAsynchronous && error == null) { throw e; } } return(instance); }
void ProcessXmlNodeChanged(EventArgs args) { // By the time this worker is notified, its binding's TargetElement may already be gone. // We should first check TargetElement to see if this worker still matters. (Fix 1494812) DependencyObject target = ParentBindingExpression.TargetElement; if (target == null) { return; } if (IgnoreSourcePropertyChange) { return; } if (DataItem == BindingExpressionBase.DisconnectedItem) { return; } // There should never be a change notification when there's no ContextNode. // If this Assert ever hits, something is wrong with the logic or ordering of // UpdateContextNode(), HookNotifications() and UnHookNotifications(). Debug.Assert(ContextNode != null); // ignore changes that cannot possibly affect the value of this XPath if (!IsChangeRelevant(args)) { return; } if (XPath.Length == 0) { // DataItem is being used directly; no need to check queries at all. _hostWorker.OnXmlValueChanged(); } else if (QueriedCollection == null) { // If there was no previous QueryCollection, it's probably because // the previous xpath query failed. Try again now. _hostWorker.UseNewXmlItem(this.RawValue()); } else { // We have a previous query result; run a new query for comparison: XmlNodeList nodes = SelectNodes(); if (nodes == null) { // Node change has caused the new query to fail. QueriedCollection = null; _hostWorker.UseNewXmlItem(DependencyProperty.UnsetValue); } else if (_collectionMode) { if (TraceData.IsExtendedTraceEnabled(ParentBindingExpression, TraceDataLevel.GetValue)) { TraceData.Trace(TraceEventType.Warning, TraceData.XmlSynchronizeCollection( TraceData.Identify(ParentBindingExpression), IdentifyNodeList(nodes))); } // Any xml change action, doesn't matter if it's an insert, // remove, or change, can result in any number of changes // to the content of the queried collection, so we have to // update the old collection with the new results. QueriedCollection.SynchronizeCollection(nodes); } // PERF: it is possible to add one more optimization "mode" here for singleMode. else if (QueriedCollection.CollectionHasChanged(nodes)) { // RawValue itself has changed, and we don't know // if the hostWorker is consuming information on the // collection itself or on its CurrentItem, so we just reset. _hostWorker.UseNewXmlItem(BuildQueriedCollection(nodes)); } else { // RawValue itself hasn't changed, but its children's content may have. _hostWorker.OnXmlValueChanged(); } } GC.KeepAlive(target); // keep target alive during process xml change (bug 1494812) }
} // It is here to allow enable/disable component. public abstract Color GetColor(Raytracer raytracer, Ray ray, RaycastHit hit, TraceData traceData);
// Token: 0x06001CE3 RID: 7395 RVA: 0x00086FA8 File Offset: 0x000851A8 private void CreateDocFromExternalSource(WebRequest request) { bool flag = TraceData.IsExtendedTraceEnabled(this, TraceDataLevel.Transfer); XmlDocument xmlDocument = new XmlDocument(); Exception ex = null; try { if (flag) { TraceData.Trace(TraceEventType.Warning, TraceData.XmlLoadSource(new object[] { TraceData.Identify(this), base.Dispatcher.CheckAccess() ? "synchronous" : "asynchronous", TraceData.Identify(request.RequestUri.ToString()) })); } WebResponse response = WpfWebRequestHelper.GetResponse(request); if (response == null) { throw new InvalidOperationException(SR.Get("GetResponseFailed")); } Stream responseStream = response.GetResponseStream(); if (flag) { TraceData.Trace(TraceEventType.Warning, TraceData.XmlLoadDoc(new object[] { TraceData.Identify(this) })); } xmlDocument.Load(responseStream); responseStream.Close(); } catch (Exception ex2) { if (CriticalExceptions.IsCriticalException(ex2)) { throw; } ex = ex2; if (TraceData.IsEnabled) { TraceData.Trace(TraceEventType.Error, TraceData.XmlDPAsyncDocError, this.Source, ex); } } catch { throw; } if (ex != null) { if (TraceData.IsExtendedTraceEnabled(this, TraceDataLevel.Attach)) { TraceData.Trace(TraceEventType.Warning, TraceData.QueryFinished(new object[] { TraceData.Identify(this), base.Dispatcher.CheckAccess() ? "synchronous" : "asynchronous", TraceData.Identify(null), TraceData.IdentifyException(ex) })); } this.OnQueryFinished(null, ex, this.CompletedCallback, null); return; } this.BuildNodeCollection(xmlDocument); }
//------------------------------------------------------ // // Public Methods // //------------------------------------------------------ /// <summary> Returns the referenced object. </summary> /// <param name="d">Element defining context for the reference. </param> /// <param name="args">See ObjectRefArgs </param> internal override object GetObject(DependencyObject d, ObjectRefArgs args) { if (d == null) { throw new ArgumentNullException("d"); } object o = null; if (args.ResolveNamesInTemplate) { // look in container's template (if any) first FrameworkElement fe = d as FrameworkElement; if (fe != null && fe.TemplateInternal != null) { o = Helper.FindNameInTemplate(_name, d); if (args.IsTracing) { TraceData.Trace(TraceEventType.Warning, TraceData.ElementNameQueryTemplate( _name, TraceData.Identify(d))); } } if (o == null) { args.NameResolvedInOuterScope = true; } } FrameworkObject fo = new FrameworkObject(d); while (o == null && fo.DO != null) { DependencyObject scopeOwner; o = fo.FindName(_name, out scopeOwner); // if the original element is a scope owner, supports IComponentConnector, // and has a parent, don't use the result of FindName. The // element is probably an instance of a Xaml-subclassed control; // we want to resolve the name starting in the next outer scope. // (bug 1669408) // Also, if the element's NavigationService property is locally // set, the element is the root of a navigation and should use the // inner scope (bug 1765041) if (d == scopeOwner && d is IComponentConnector && d.ReadLocalValue(System.Windows.Navigation.NavigationService.NavigationServiceProperty) == DependencyProperty.UnsetValue) { DependencyObject parent = LogicalTreeHelper.GetParent(d); if (parent == null) { parent = Helper.FindMentor(d.InheritanceContext); } if (parent != null) { o = null; fo.Reset(parent); continue; } } if (args.IsTracing) { TraceData.Trace(TraceEventType.Warning, TraceData.ElementNameQuery( _name, TraceData.Identify(fo.DO))); } if (o == null) { args.NameResolvedInOuterScope = true; // move to the next outer namescope. // First try TemplatedParent of the scope owner. FrameworkObject foScopeOwner = new FrameworkObject(scopeOwner); DependencyObject dd = foScopeOwner.TemplatedParent; // if that doesn't work, we could be at the top of // generated content for an ItemsControl. If so, use // the (visual) parent - a panel. if (dd == null) { Panel panel = fo.FrameworkParent.DO as Panel; if (panel != null && panel.IsItemsHost) { dd = panel; } } // if the logical parent is a ContentControl whose content // points right back, move to the ContentControl. This is the // m---- equivalent of having the ContentControl as the TemplatedParent. // (The InheritanceBehavior clause prevents this for cases where the // parent ContentControl imposes a barrier, e.g. Frame) if (dd == null && scopeOwner == null) { ContentControl cc = LogicalTreeHelper.GetParent(fo.DO) as ContentControl; if (cc != null && cc.Content == fo.DO && cc.InheritanceBehavior == InheritanceBehavior.Default) { dd = cc; } } // next, see if we're in a logical tree attached directly // to a ContentPresenter. This is the m---- equivalent of // having the ContentPresenter as the TemplatedParent. if (dd == null && scopeOwner == null) { // go to the top of the logical subtree DependencyObject parent; for (dd = fo.DO;;) { parent = LogicalTreeHelper.GetParent(dd); if (parent == null) { parent = Helper.FindMentor(dd.InheritanceContext); } if (parent == null) { break; } dd = parent; } // if it's attached to a ContentPresenter, move to the CP ContentPresenter cp = VisualTreeHelper.IsVisualType(dd) ? VisualTreeHelper.GetParent(dd) as ContentPresenter : null; dd = (cp != null && cp.TemplateInternal.CanBuildVisualTree) ? cp : null; } fo.Reset(dd); } } if (o == null) { o = DependencyProperty.UnsetValue; args.NameResolvedInOuterScope = false; } return(o); }
public void WriteFormattedLine(TraceData traceData, string message, params object[] args) { message = this.FormatMessage(traceData.StashEntries, message, args); this.WriteLine(message); }
private void ComputeSummaryData(TraceData.TraceData traceData) { ComputeTotalTime(traceData); ComputeControllerName(traceData); ComputeActionName(traceData); }
private static Nullable <TraceData> ParseTraceData(XElement traceEvent) { var traceData = new TraceData(); traceData.Original = traceEvent; var system = traceEvent.GetElementByName("System"); traceData.TimeCreated = DateTime.Parse(system.GetElementByName("TimeCreated").AttributeAnyNS("SystemTime").Value); traceData.Computer = system.GetElementByName("Computer").Value; traceData.ActivityID = Guid.Parse(system.GetElementByName("Correlation").AttributeAnyNS("ActivityID").Value); var dataItem = traceEvent.GetElementByName("ApplicationData").GetElementByName("TraceData")?.GetElementByName("DataItem"); if (dataItem != null) { var messageLog = dataItem.GetElementByName("MessageLogTraceRecord"); if (messageLog == null) { var traceRecord = dataItem.GetElementByName("TraceRecord"); if (traceRecord == null) { traceData.MessageType = "String"; traceData.Content = dataItem; } else { traceData.Action = traceRecord.AttributeAnyNS("Severity").Value; traceData.MessageType = "Trace"; traceData.Content = traceRecord; } return(traceData); } else { traceData.Source = messageLog.AttributeAnyNS("Source")?.Value; traceData.MessageType = messageLog.AttributeAnyNS("Type")?.Value; if (traceData.MessageType == null && traceData.Source == "Malformed") { traceData.Content = messageLog; return(traceData); } else if (!skipMessageTypes.Contains(traceData.MessageType)) { var soapEnvelope = messageLog.GetElementByName("Envelope", true); if (soapEnvelope == null) { traceData.Content = messageLog; } else { var header = soapEnvelope.GetElementByName("Header", true); traceData.Action = messageLog.GetElementByName("Addressing")?.GetElementByName("Action").Value ?? header?.GetElementByName("Action", true)?.Value; traceData.Address = header?.GetElementByName("To", true)?.Value; var body = soapEnvelope.GetElementByName("Body", true); if (body != null && body.HasElements) { traceData.Content = body.Elements().FirstOrDefault(); } } if (traceData.Action == null || !skipActions.Any(traceData.Action.StartsWith)) { return(traceData); } } } } return(null); }
private void PostToTrace(Machine machine, Product product, Datas datas) { if (!Config.POSTData.ToTrace) { return; } machine.AddPostTotal(); string dataJson = ""; try { TraceData traceData = new TraceData { ListData = new Dictionary <string, List <string> >(), FuncData = new Dictionary <string, Func <JToken, string> > { { "unit_serial_number", (d) => { var b = Config.POSTData.SnType?.ToLower() == "fg"?datas.FGCode: datas.SN; return(b.Length > 17 ? b.Substring(0, 17) : b); } } }, DicData = new Dictionary <string, string> { { "fg", datas.FGCode }, { "fg_sn", Config.POSTData.SnType?.ToLower() == "fg"?datas.FGCode: datas.SN }, { "uut_start", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") }, { "uut_stop", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") }, { "software_version", Version } }, ResultsData = GetTraceResults(datas) }; dataJson = traceDataHelper.GetJson(traceData); } catch (Exception ex) { LogRead.Log.Error($"解码数据失败:{datas.FGCode}\r\n" + ex.Message); LogError.Log.Fatal("Trace 解码数据失败:" + ex.StackTrace); product.AddNgMsg("解码数据失败!"); product.PostTraceSuccess = false; return; } //Process Control Result result = Config.POSTData.ProcessControl ? TracePost.ProcessControl(Config.POSTData.ProcessControlUrl, datas.SN, dataJson) : TracePost.PostTrace(Config.POSTData.TeaceUrl, dataJson); foreach (var one in result.Elapseds) { SaveRequestTime(one.Key, one.Value); } if (result.Success) { LogRead.Log.Info($"上抛Trace 成功 {datas.FGCode}"); datas.TracePost = true; datas.TracePostInformation = ""; product.PostTraceSuccess = true; machine.AddCount(0, 1, 0); } else { LogRead.Log.Info($"上抛Trace 失败 {datas.FGCode}"); product.AddNgMsg(result.Message); datas.TracePost = false; datas.TracePostInformation = string.Join("\r\n", result.Message); product.PostTraceSuccess = false; } //更新数据库 new DbContext().DatasDb.Update(datas); }
// this method can run on a worker thread! private void CreateDocFromInlineXml(XmlReader xmlReader) { // Maybe things have changed and we don't want to use inline doc anymore if (!_tryInlineDoc) { _savedDocument = null; if (_waitForInlineDoc != null) { _waitForInlineDoc.Set(); } return; } XmlDocument doc; Exception ex = null; try { doc = new XmlDocument(); try { if (TraceData.IsExtendedTraceEnabled(this, TraceDataLevel.XmlProvider)) { TraceData.Trace(TraceEventType.Warning, TraceData.XmlLoadInline( TraceData.Identify(this), Dispatcher.CheckAccess() ? "synchronous" : "asynchronous")); } // Load the inline doc from the reader doc.Load(xmlReader); } catch (XmlException xmle) { if (TraceData.IsEnabled) { TraceData.Trace(TraceEventType.Error, TraceData.XmlDPInlineDocError, xmle); } ex = xmle; } if (ex == null) { // Save a copy of the inline document to be used in future // queries, and by serialization. _savedDocument = (XmlDocument)doc.Clone(); } } finally { xmlReader.Close(); // Whether or not parsing was successful, unblock the serializer thread. // If serializer had to wait for the inline doc, it's available now. // If there was an error, null will be returned for DocumentForSerialization. if (_waitForInlineDoc != null) { _waitForInlineDoc.Set(); } } // warn the user if the default xmlns wasn't set explicitly ( if (TraceData.IsEnabled) { XmlNode root = doc.DocumentElement; if (root != null && root.NamespaceURI == xmlReader.LookupNamespace(String.Empty)) { TraceData.Trace(TraceEventType.Error, TraceData.XmlNamespaceNotSet); } } if (ex == null) { // Load succeeded. Create the node collection. (This calls // OnQueryFinished to reset the Document and Data properties). BuildNodeCollection(doc); } else { if (TraceData.IsExtendedTraceEnabled(this, TraceDataLevel.ProviderQuery)) { TraceData.Trace(TraceEventType.Warning, TraceData.QueryFinished( TraceData.Identify(this), Dispatcher.CheckAccess() ? "synchronous" : "asynchronous", TraceData.Identify(null), TraceData.IdentifyException(ex))); } // Load failed. Report the error, and reset // Data and Document properties to null. OnQueryFinished(null, ex, CompletedCallback, null); } }
//------------------------------------------------------ // // Private Method // //------------------------------------------------------ private object GetPreviousData(DependencyObject d) { // move up to the next containing DataContext scope for (; d != null; d = FrameworkElement.GetFrameworkParent(d)) { if (BindingExpression.HasLocalDataContext(d)) { // special case: if the element is a ContentPresenter // whose templated parent is a ContentControl or // HeaderedItemsControl, and both have the same // DataContext, we'll use the parent instead of the // ContentPresenter. In this case, the DataContext // of the CP is set by various forwarding rules, and // shouldn't count as a new scope. // Similarly, do the same for a FE whose parent // is a GridViewRowPresenter; this enables Previous bindings // inside ListView. FrameworkElement parent, child; ContentPresenter cp; if ((cp = d as ContentPresenter) != null) { child = cp; parent = cp.TemplatedParent as FrameworkElement; if (!(parent is ContentControl || parent is HeaderedItemsControl)) { parent = cp.Parent as System.Windows.Controls.Primitives.GridViewRowPresenterBase; } } else { child = d as FrameworkElement; parent = ((child != null) ? child.Parent : null) as System.Windows.Controls.Primitives.GridViewRowPresenterBase; } if (child != null && parent != null && Object.Equals(child.DataContext, parent.DataContext)) { d = parent; if (!BindingExpression.HasLocalDataContext(parent)) { continue; } } break; } } if (d == null) { return(DependencyProperty.UnsetValue); // we fell off the tree } // this only makes sense within generated content. If this // is the case, then d is now the wrapper element, its visual // parent is the layout element, and the layout's ItemsOwner // is the govening ItemsControl. Visual v = d as Visual; DependencyObject layout = (v != null) ? VisualTreeHelper.GetParent(v) : null; ItemsControl ic = ItemsControl.GetItemsOwner(layout); if (ic == null) { if (TraceData.IsEnabled) { TraceData.Trace(TraceEventType.Error, TraceData.RefPreviousNotInContext); } return(null); } // now look up the wrapper's previous sibling within the // layout's children collection Visual v2 = layout as Visual; int count = (v2 != null) ? v2.InternalVisualChildrenCount : 0; int j = -1; Visual prevChild = null; //child at j-1th index if (count != 0) { j = IndexOf(v2, v, out prevChild); } if (j > 0) { d = prevChild; } else { d = null; if ((j < 0) && TraceData.IsEnabled) { TraceData.Trace(TraceEventType.Error, TraceData.RefNoWrapperInChildren); } } return(d); }
public string Format(TraceData traceData) { string s; s = traceData.Level + traceData.Text + NextFormatting.Format(traceData); return s; }
// this method can run on a worker thread! private void CreateDocFromExternalSource(WebRequest request) { bool isExtendedTraceEnabled = TraceData.IsExtendedTraceEnabled(this, TraceDataLevel.XmlProvider); XmlDocument doc = new XmlDocument(); Exception ex = null; // request the content from the URI try { if (isExtendedTraceEnabled) { TraceData.Trace(TraceEventType.Warning, TraceData.XmlLoadSource( TraceData.Identify(this), Dispatcher.CheckAccess() ? "synchronous" : "asynchronous", TraceData.Identify(request.RequestUri.ToString()))); } WebResponse response = WpfWebRequestHelper.GetResponse(request); if (response == null) { throw new InvalidOperationException(SR.Get(SRID.GetResponseFailed)); } // Get Stream and content type from WebResponse. Stream stream = response.GetResponseStream(); if (isExtendedTraceEnabled) { TraceData.Trace(TraceEventType.Warning, TraceData.XmlLoadDoc( TraceData.Identify(this))); } // load the XML from the stream doc.Load(stream); stream.Close(); } catch (Exception e) { if (CriticalExceptions.IsCriticalException(e)) { throw; } ex = e; if (TraceData.IsEnabled) { TraceData.Trace(TraceEventType.Error, TraceData.XmlDPAsyncDocError, Source, ex); } } //FXCop Fix: CatchNonClsCompliantExceptionsInGeneralHandlers catch { throw; } if (ex != null) { if (TraceData.IsExtendedTraceEnabled(this, TraceDataLevel.ProviderQuery)) { TraceData.Trace(TraceEventType.Warning, TraceData.QueryFinished( TraceData.Identify(this), Dispatcher.CheckAccess() ? "synchronous" : "asynchronous", TraceData.Identify(null), TraceData.IdentifyException(ex))); } // we're done if we got an error up to this point // both .Data and .Document properties will be reset to null OnQueryFinished(null, ex, CompletedCallback, null); return; // have an error, no processing of DOM } BuildNodeCollection(doc); // above method also calls OnQueryFinished to push new property values }
// Token: 0x06007607 RID: 30215 RVA: 0x0021A86C File Offset: 0x00218A6C private object GetPreviousData(DependencyObject d) { while (d != null) { if (BindingExpression.HasLocalDataContext(d)) { ContentPresenter contentPresenter; FrameworkElement frameworkElement; FrameworkElement frameworkElement2; if ((contentPresenter = (d as ContentPresenter)) != null) { frameworkElement = contentPresenter; frameworkElement2 = (contentPresenter.TemplatedParent as FrameworkElement); if (!(frameworkElement2 is ContentControl) && !(frameworkElement2 is HeaderedItemsControl)) { frameworkElement2 = (contentPresenter.Parent as GridViewRowPresenterBase); } } else { frameworkElement = (d as FrameworkElement); frameworkElement2 = (((frameworkElement != null) ? frameworkElement.Parent : null) as GridViewRowPresenterBase); } if (frameworkElement == null || frameworkElement2 == null || !ItemsControl.EqualsEx(frameworkElement.DataContext, frameworkElement2.DataContext)) { break; } d = frameworkElement2; if (BindingExpression.HasLocalDataContext(frameworkElement2)) { break; } } d = FrameworkElement.GetFrameworkParent(d); } if (d == null) { return(DependencyProperty.UnsetValue); } Visual visual = d as Visual; DependencyObject dependencyObject = (visual != null) ? VisualTreeHelper.GetParent(visual) : null; if (ItemsControl.GetItemsOwner(dependencyObject) == null) { if (TraceData.IsEnabled) { TraceData.Trace(TraceEventType.Error, TraceData.RefPreviousNotInContext); } return(null); } Visual visual2 = dependencyObject as Visual; int num = (visual2 != null) ? visual2.InternalVisualChildrenCount : 0; int num2 = -1; Visual visual3 = null; if (num != 0) { num2 = this.IndexOf(visual2, visual, out visual3); } if (num2 > 0) { d = visual3; } else { d = null; if (num2 < 0 && TraceData.IsEnabled) { TraceData.Trace(TraceEventType.Error, TraceData.RefNoWrapperInChildren); } } return(d); }