public TransactionTraceWireModel GetTransactionTrace(ImmutableTransaction immutableTransaction, IEnumerable <ImmutableSegmentTreeNode> segmentTrees, TransactionMetricName transactionMetricName, IAttributeValueCollection attribValues)
        {
            segmentTrees = segmentTrees.ToList();

            if (!segmentTrees.Any())
            {
                throw new ArgumentException("There must be at least one segment to create a trace");
            }

            var filteredAttributes = new AttributeValueCollection(attribValues, AttributeDestinations.TransactionTrace);

            // See spec for details on these fields: https://source.datanerd.us/agents/agent-specs/blob/master/Transaction-Trace-LEGACY.md
            var    startTime = immutableTransaction.StartTime;
            var    duration  = immutableTransaction.ResponseTimeOrDuration;
            string uri       = null;

            if (_attribDefs.RequestUri.IsAvailableForAny(AttributeDestinations.TransactionTrace))
            {
                uri = immutableTransaction.TransactionMetadata.Uri?.TrimAfterAChar(StringSeparators.QuestionMarkChar) ?? "/Unknown";
            }

            var guid          = immutableTransaction.Guid;
            var xraySessionId = null as ulong?; // The .NET agent does not support xray sessions

            var isSynthetics         = immutableTransaction.TransactionMetadata.IsSynthetics;
            var syntheticsResourceId = immutableTransaction.TransactionMetadata.SyntheticsResourceId;
            var rootSegment          = GetRootSegment(segmentTrees, immutableTransaction);


            var traceData = new TransactionTraceData(startTime, rootSegment, attribValues);

            var trace = new TransactionTraceWireModel(startTime, duration, transactionMetricName.PrefixedName, uri, traceData, guid, xraySessionId, syntheticsResourceId, isSynthetics);

            return(trace);
        }
示例#2
0
        public void Index_AddCollectionWithTenObjects_LastOjbectSameObjectAsLastIndex()
        {
            var list       = A.CollectionOfFake <object>(10);
            var collection = new AttributeValueCollection(list);

            Assert.AreSame(list.Last(), collection[9]);
        }
        /// <summary>
        /// Unmarshals and deallocates an array of OPCHDA_ATTRIBUTE structures.
        /// </summary>
        internal static AttributeValueCollection[] GetAttributeValueCollections(ref IntPtr pInput, int count, bool deallocate)
        {
            AttributeValueCollection[] output = null;

            if (pInput != IntPtr.Zero && count > 0)
            {
                output = new AttributeValueCollection[count];

                IntPtr pos = pInput;

                for (int ii = 0; ii < count; ii++)
                {
                    output[ii] = GetAttributeValueCollection(pos, deallocate);
                    pos        = (IntPtr)(pos.ToInt64() + Marshal.SizeOf(typeof(OpcRcw.Hda.OPCHDA_ATTRIBUTE)));
                }

                if (deallocate)
                {
                    Marshal.FreeCoTaskMem(pInput);
                    pInput = IntPtr.Zero;
                }
            }

            return(output);
        }
        /// <summary>
        /// Generates the JavaScript for a JSON object.
        /// </summary>
        /// <param name="optionValues"></param>
        /// <returns>
        /// JS code with the JSON object.
        /// </returns>
        public static string GenerateJson(AttributeValueCollection optionValues)
        {
            StringBuilder sb = new StringBuilder();

            sb.Append("{");

            bool firstItem = true;
            foreach (KeyValuePair<string, Value> option in optionValues)
            {
                string jsValue = null;

                // Do not test for IsNullOrEmpty. For example, appenders="" is legitimate (use 0 appenders)
                if (option.Value.Text != null)
                {
                    jsValue = option.Value.ValueInfo.ToJavaScript(option.Value.Text);
                }
                else if (option.Value.TextCollection != null)
                {
                    jsValue = "[" + String.Join(",", option.Value.TextCollection.Select(t => option.Value.ValueInfo.ToJavaScript(t))) + "]";
                }
                else
                {
                    continue;
                }

                sb.AppendFormat("{0}\"{1}\": {2}", firstItem ? "" : ", ", option.Key, jsValue);
                firstItem = false;
            }

            sb.Append("}");

            return sb.ToString();
        }
        private BrowserMonitoringConfigurationData GetBrowserConfigurationData(IInternalTransaction transaction, TransactionMetricName transactionMetricName, string licenseKey)
        {
            var configuration = _configurationService.Configuration;

            var beacon = configuration.BrowserMonitoringBeaconAddress;

            if (beacon == null)
            {
                throw new NullReferenceException(nameof(beacon));
            }

            var errorBeacon = configuration.BrowserMonitoringErrorBeaconAddress;

            if (errorBeacon == null)
            {
                throw new NullReferenceException(nameof(errorBeacon));
            }

            var browserMonitoringKey = configuration.BrowserMonitoringKey;

            if (browserMonitoringKey == null)
            {
                throw new NullReferenceException(nameof(browserMonitoringKey));
            }

            var applicationId = configuration.BrowserMonitoringApplicationId;

            if (applicationId == null)
            {
                throw new NullReferenceException(nameof(applicationId));
            }

            var jsAgentPayloadFile = configuration.BrowserMonitoringJavaScriptAgentFile;

            if (jsAgentPayloadFile == null)
            {
                throw new NullReferenceException(nameof(jsAgentPayloadFile));
            }

            var obfuscatedTransactionName = Strings.ObfuscateStringWithKey(transactionMetricName.PrefixedName, licenseKey);
            var queueTime       = transaction.TransactionMetadata.QueueTime ?? _zeroTimespan;
            var applicationTime = transaction.GetDurationUntilNow();

            var attributes = new AttributeValueCollection(AttributeDestinations.JavaScriptAgent);

            _transactionAttributeMaker.SetUserAndAgentAttributes(attributes, transaction.TransactionMetadata);

            // for now, treat tripId as an agent attribute when passing to browser.  Eventually this will be an intrinsic but need changes to browser code first.
            // if CrossApplicationReferrerTripId is null then this transaction started the first external request, so use its guid
            _attribDefSvc.AttributeDefs.BrowserTripId.TrySetValue(attributes, transaction.TransactionMetadata.CrossApplicationReferrerTripId ?? transaction.Guid);

            //This will resolve any Lazy values and remove null values from the collection.
            //Browser monitoring should not render JSON for attributes if there are none
            attributes.MakeImmutable();

            var obfuscatedFormattedAttributes = GetObfuscatedFormattedAttributes(attributes, licenseKey);
            var sslForHttp = configuration.BrowserMonitoringUseSsl;

            return(new BrowserMonitoringConfigurationData(licenseKey, beacon, errorBeacon, browserMonitoringKey, applicationId, obfuscatedTransactionName, queueTime, applicationTime, jsAgentPayloadFile, obfuscatedFormattedAttributes, sslForHttp));
        }
示例#6
0
        public void Count_AddCollectionWithTenObjects_ReturnsTen()
        {
            var list       = A.CollectionOfFake <object>(10);
            var collection = new AttributeValueCollection(list);

            Assert.AreEqual(10, collection.Count);
        }
示例#7
0
        public void Index_AddCollectionWithOneObject_SameObjectFromIndex()
        {
            var list       = A.CollectionOfFake <object>(1);
            var collection = new AttributeValueCollection(list);

            Assert.AreSame(list.First(), collection[0]);
        }
        public void Transform(ErrorData errorData, float priority)
        {
            if (!_configurationService.Configuration.ErrorCollectorEnabled)
            {
                return;
            }

            var attribValues = new AttributeValueCollection(AttributeDestinations.ErrorEvent, AttributeDestinations.ErrorTrace);

            if (errorData.CustomAttributes != null && _configurationService.Configuration.CaptureCustomParameters)
            {
                foreach (var customAttrib in errorData.CustomAttributes)
                {
                    _attribDefs.GetCustomAttributeForError(customAttrib.Key).TrySetValue(attribValues, customAttrib.Value);
                }
            }

            // For Custom Errors (occurring outside a transaction), UI Error Analytics page co-opts the
            // 'transactionName' attribute to find the corresponding Error Trace (matching it to 'Path')
            // so it can display the stack trace.
            _attribDefs.TransactionNameForError.TrySetValue(attribValues, errorData.Path);

            //We have to do the filtering here b/c these methods further update
            var errorTrace = _errorTraceMaker.GetErrorTrace(new AttributeValueCollection(attribValues, AttributeDestinations.ErrorTrace), errorData);
            var errorEvent = _errorEventMaker.GetErrorEvent(errorData, new AttributeValueCollection(attribValues, AttributeDestinations.ErrorEvent), priority);

            _errorTraceAggregator.Collect(errorTrace);
            _errorEventAggregator.Collect(errorEvent);
        }
示例#9
0
 public void OnReadAttributeComplete(int dwTransactionID, int hrStatus, int hClient, int dwNumItems, OPCHDA_ATTRIBUTE[] pAttributeValues, int[] phrErrors)
 {
     try
     {
         lock (this)
         {
             Request request = (Request)this.m_requests[dwTransactionID];
             if (request != null)
             {
                 ItemAttributeCollection results = new ItemAttributeCollection {
                     ServerHandle = hClient
                 };
                 AttributeValueCollection[] valuesArray = new AttributeValueCollection[pAttributeValues.Length];
                 for (int i = 0; i < pAttributeValues.Length; i++)
                 {
                     valuesArray[i]          = OpcCom.Hda.Interop.GetAttributeValueCollection(pAttributeValues[i], false);
                     valuesArray[i].ResultID = OpcCom.Interop.GetResultID(phrErrors[i]);
                     results.Add(valuesArray[i]);
                 }
                 if (request.InvokeCallback(results))
                 {
                     this.m_requests.Remove(request.RequestID);
                 }
             }
         }
     }
     catch (Exception exception)
     {
         this.HandleException(dwTransactionID, exception);
     }
 }
示例#10
0
        public void GetSpanEvent_DoesNotIncludesErrorAttributes_WhenThereIsAnError_IfErrorCollectionIsDisabled()
        {
            // ARRANGE
            _localConfig.errorCollector.enabled = false;
            PublishConfig();
            var testError = new ErrorData("error message", "ErrorType", "stack trace", DateTime.UtcNow, null, false);
            var segments  = new List <Segment>()
            {
                _baseGenericSegment.CreateSimilar(TimeSpan.FromMilliseconds(1), TimeSpan.FromMilliseconds(5), new List <KeyValuePair <string, object> >())
            };

            segments[0].ErrorData = testError;
            var immutableTransaction  = BuildTestTransaction(segments, sampled: true, hasIncomingPayload: true);
            var transactionMetricName = _transactionMetricNameMaker.GetTransactionMetricName(immutableTransaction.TransactionName);
            var metricStatsCollection = new TransactionMetricStatsCollection(transactionMetricName);
            var transactionAttributes = _transactionAttribMaker.GetAttributes(immutableTransaction, transactionMetricName, TimeSpan.FromSeconds(1), immutableTransaction.Duration, metricStatsCollection);

            // ACT
            var spanEvents           = _spanEventMaker.GetSpanEvents(immutableTransaction, TransactionName, transactionAttributes).ToList();
            var spanEvent            = spanEvents[1];
            var rootSpanEvent        = spanEvents[0];
            var errorEventAttributes = new AttributeValueCollection(transactionAttributes, AttributeDestinations.ErrorEvent);

            // ASSERT
            NrAssert.Multiple(
                () => CollectionAssert.DoesNotContain(errorEventAttributes.GetAttributeValuesDic(AttributeClassification.Intrinsics).Keys, "spanId"),
                () => CollectionAssert.DoesNotContain(spanEvent.AgentAttributes().Keys, "error.class"),
                () => CollectionAssert.DoesNotContain(rootSpanEvent.AgentAttributes().Keys, "error.class")
                );
        }
        public void GetTransactionTrace_AppendsNodeToFauxTopLevelSegmentChildren()
        {
            var          transactionStartTime        = DateTime.Now;
            var          segmentStartTime            = transactionStartTime.AddSeconds(1);
            var          expectedStartTimeDifference = TimeSpan.FromSeconds(1);
            var          segmentDuration             = TimeSpan.FromSeconds(10);
            var          expectedEndTimeDifference   = expectedStartTimeDifference + segmentDuration;
            const string expectedName       = "some segment name";
            var          expectedParameters = new Dictionary <string, object> {
                { "foo", "bar" }
            };
            var expectedClassName     = "foo";
            var expectedMethodName    = "bar";
            var methodCallData        = new MethodCallData(expectedClassName, expectedMethodName, 1);
            var transaction           = BuildTestTransaction(startTime: transactionStartTime);
            var segments              = new[] { BuildNode(transaction, startTime: segmentStartTime, duration: segmentDuration, name: expectedName, parameters: expectedParameters, methodCallData: methodCallData) };
            var transactionMetricName = new TransactionMetricName("WebTransaction", "TrxName");
            var attributes            = new AttributeValueCollection(AttributeDestinations.TransactionTrace);

            var trace        = _transactionTraceMaker.GetTransactionTrace(transaction, segments, transactionMetricName, attributes);
            var realSegments = trace.TransactionTraceData.RootSegment.Children.First().Children;
            var firstSegment = realSegments.First();

            NrAssert.Multiple(
                () => Assert.AreEqual(expectedStartTimeDifference, firstSegment.TimeBetweenTransactionStartAndSegmentStart),
                () => Assert.AreEqual(expectedEndTimeDifference, firstSegment.TimeBetweenTransactionStartAndSegmentEnd),
                () => Assert.AreEqual(expectedName, firstSegment.Name),
                () => Assert.AreEqual(expectedClassName, firstSegment.ClassName),
                () => Assert.AreEqual(expectedMethodName, firstSegment.MethodName),
                () => Assert.AreEqual(0, firstSegment.Children.Count),
                () => Assert.True(expectedParameters.All(kvp => expectedParameters[kvp.Key] == firstSegment.Parameters[kvp.Key]))
                );
        }
示例#12
0
        public void Equals_CreateCollection_CollectionIsEqualsItself()
        {
            var list       = A.CollectionOfFake <object>(10);
            var collection = new AttributeValueCollection(list);

            Assert.IsTrue(collection.Equals(collection));
        }
        public void GetTransactionTrace_PrependsTreeWithRootNodeAndFauxTopLevelSegment()
        {
            var expectedStartTimeDifference = TimeSpan.FromSeconds(0);
            var expectedEndTimeDifference   = TimeSpan.FromSeconds(10);
            var transaction           = BuildTestTransaction(duration: expectedEndTimeDifference);
            var segments              = new[] { BuildNode() };
            var transactionMetricName = new TransactionMetricName("WebTransaction", "TrxName");
            var attributes            = new AttributeValueCollection(AttributeDestinations.TransactionTrace);

            var trace = _transactionTraceMaker.GetTransactionTrace(transaction, segments, transactionMetricName, attributes);
            var root  = trace.TransactionTraceData.RootSegment;
            var fauxTopLevelSegment = root.Children.First();

            NrAssert.Multiple(
                // ROOT
                () => Assert.AreEqual(expectedStartTimeDifference, root.TimeBetweenTransactionStartAndSegmentStart),
                () => Assert.AreEqual(expectedEndTimeDifference, root.TimeBetweenTransactionStartAndSegmentEnd),
                () => Assert.AreEqual("ROOT", root.Name),
                () => Assert.AreEqual(1, root.Children.Count),

                // Faux top-level segment
                () => Assert.AreEqual(expectedStartTimeDifference, fauxTopLevelSegment.TimeBetweenTransactionStartAndSegmentStart),
                () => Assert.AreEqual(expectedEndTimeDifference, fauxTopLevelSegment.TimeBetweenTransactionStartAndSegmentEnd),
                () => Assert.AreEqual("Transaction", fauxTopLevelSegment.Name),
                () => Assert.AreEqual(1, fauxTopLevelSegment.Children.Count)
                );
        }
            public void Verify_setting_priority()
            {
                var attribValues = new AttributeValueCollection(AttributeDestinations.TransactionEvent);

                _attribDefs.Timestamp.TrySetValue(attribValues, DateTime.UtcNow);

                float priority        = 0.5f;
                var   emptyDictionary = new Dictionary <string, object>();
                var   object1         = new TransactionEventWireModel(attribValues, false, priority);

                Assert.That(priority == object1.Priority);

                priority         = 0.0f;
                object1.Priority = priority;
                Assert.That(priority == object1.Priority);

                priority         = 1.0f;
                object1.Priority = priority;
                Assert.That(priority == object1.Priority);

                priority         = 1.1f;
                object1.Priority = priority;
                Assert.That(priority == object1.Priority);

                priority = -0.00001f;
                Assert.Throws <ArgumentException>(() => object1.Priority = priority);
                priority = float.NaN;
                Assert.Throws <ArgumentException>(() => object1.Priority = priority);
                priority = float.NegativeInfinity;
                Assert.Throws <ArgumentException>(() => object1.Priority = priority);
                priority = float.PositiveInfinity;
                Assert.Throws <ArgumentException>(() => object1.Priority = priority);
                priority = float.MinValue;
                Assert.Throws <ArgumentException>(() => object1.Priority = priority);
            }
        public void GetTransactionTrace_RetainsComplicatedSegmentTreeStructure()
        {
            var node1   = GetNodeBuilder(name: "1");
            var node2   = GetNodeBuilder(name: "2");
            var node11  = GetNodeBuilder(name: "1.1");
            var node12  = GetNodeBuilder(name: "1.2");
            var node121 = GetNodeBuilder(name: "1.2.1");

            node1.Children.Add(node11);
            node1.Children.Add(node12);
            node12.Children.Add(node121);

            var transaction           = BuildTestTransaction();
            var topLevelSegments      = new[] { node1.Build(), node2.Build() };
            var transactionMetricName = new TransactionMetricName("WebTransaction", "TrxName");
            var attributes            = new AttributeValueCollection(AttributeDestinations.TransactionTrace);

            var trace = _transactionTraceMaker.GetTransactionTrace(transaction, topLevelSegments, transactionMetricName, attributes);

            var realSegments = trace.TransactionTraceData.RootSegment.Children.First().Children;
            var segment1     = realSegments.ElementAt(0);
            var segment2     = realSegments.ElementAt(1);
            var segment11    = segment1.Children.ElementAt(0);
            var segment12    = segment1.Children.ElementAt(1);
            var segment121   = segment12.Children.ElementAt(0);

            NrAssert.Multiple(
                () => Assert.AreEqual("1", segment1.Name),
                () => Assert.AreEqual("2", segment2.Name),
                () => Assert.AreEqual("1.1", segment11.Name),
                () => Assert.AreEqual("1.2", segment12.Name),
                () => Assert.AreEqual("1.2.1", segment121.Name)
                );
        }
        public void Validate(string appenderName, AttributeValueCollection attributeValues)
        {
            // Ensure that if any of the buffer specific attributes are provided, they are all provided, and that they make sense.

            if (attributeValues.ContainsKey(Constants.AttributeNameSendWithBufferLevel) ||
                attributeValues.ContainsKey(Constants.AttributeNameStoreInBufferLevel) ||
                attributeValues.ContainsKey(Constants.AttributeNameBufferSize))
            {
                if ((!attributeValues.ContainsKey(Constants.AttributeNameSendWithBufferLevel)) ||
                    (!attributeValues.ContainsKey(Constants.AttributeNameStoreInBufferLevel)) ||
                    (!attributeValues.ContainsKey(Constants.AttributeNameBufferSize)))
                {
                    throw new GeneralAppenderException(appenderName, string.Format(
                        "If any of {0}, {1} or {2} is specified, than the other two need to be specified as well",
                        Constants.AttributeNameSendWithBufferLevel, Constants.AttributeNameStoreInBufferLevel, Constants.AttributeNameBufferSize));
                }

                int level =
                    attributeValues.ContainsKey(Constants.AttributeNameLevel) ?
                    LevelUtils.LevelNumber(attributeValues[Constants.AttributeNameLevel].Text) :
                    (int)Constants.DefaultAppenderLevel;

                int storeInBufferLevel = LevelUtils.LevelNumber(attributeValues[Constants.AttributeNameStoreInBufferLevel].Text);
                int sendWithBufferLevel = LevelUtils.LevelNumber(attributeValues[Constants.AttributeNameSendWithBufferLevel].Text);

                if ((storeInBufferLevel > level) || (level > sendWithBufferLevel))
                {
                    throw new GeneralAppenderException(appenderName, string.Format(
                        "{0} must be equal or greater than {1} and equal or smaller than {2}",
                        Constants.AttributeNameLevel, Constants.AttributeNameStoreInBufferLevel, 
                        Constants.AttributeNameSendWithBufferLevel));
                }
            }
        }
        public void GetTransactionTrace_CreatesTraceWithDatastoreInstanceInformation()
        {
            var expectedDatabaseParameter = "My Database";
            var expectedPortParameter     = "My Port";
            var expectedHostParameter     = "My Host";

            var transaction           = BuildTestTransaction();
            var segments              = new[] { BuildDataStoreSegmentNodeWithInstanceData() };
            var transactionMetricName = new TransactionMetricName("WebTransaction", "TrxName");
            var attributes            = new AttributeValueCollection(AttributeDestinations.TransactionTrace);

            var trace = _transactionTraceMaker.GetTransactionTrace(transaction, segments, transactionMetricName, attributes);

            Assert.IsTrue(trace.TransactionTraceData.RootSegment.Children[0].Children[0].Parameters.ContainsKey("database_name"));
            Assert.IsTrue(trace.TransactionTraceData.RootSegment.Children[0].Children[0].Parameters.ContainsKey("host"));
            Assert.IsTrue(trace.TransactionTraceData.RootSegment.Children[0].Children[0].Parameters.ContainsKey("port_path_or_id"));

            var actualDatabaseParameter = trace.TransactionTraceData.RootSegment.Children[0].Children[0].Parameters["database_name"];
            var actualHostParameter     = trace.TransactionTraceData.RootSegment.Children[0].Children[0].Parameters["host"];
            var actualPathPortParameter = trace.TransactionTraceData.RootSegment.Children[0].Children[0].Parameters["port_path_or_id"];

            Assert.AreEqual(expectedDatabaseParameter, actualDatabaseParameter);
            Assert.AreEqual(expectedHostParameter, actualHostParameter);
            Assert.AreEqual(expectedPortParameter, actualPathPortParameter);
        }
        public void GetErrorEvent_NoTransaction_WithException_ContainsCorrectAttributes()
        {
            // Arrange
            var customAttributes = new AttributeValueCollection(AttributeDestinations.ErrorEvent);

            _attribDefs.GetCustomAttributeForError("custom attribute name").TrySetValue(customAttributes, "custom attribute value");
            var errorData = _errorService.FromException(new NullReferenceException("NRE message"));

            // Act
            float priority   = 0.5f;
            var   errorEvent = _errorEventMaker.GetErrorEvent(errorData, customAttributes, priority);

            var agentAttributes     = errorEvent.AgentAttributes().Keys.ToArray();
            var intrinsicAttributes = errorEvent.IntrinsicAttributes().Keys.ToArray();
            var userAttributes      = errorEvent.UserAttributes().Keys.ToArray();

            // Assert
            NrAssert.Multiple(
                () => Assert.AreEqual(false, errorEvent.IsSynthetics),
                () => Assert.AreEqual(0, agentAttributes.Length),
                () => Assert.AreEqual(4, intrinsicAttributes.Length),
                () => Assert.AreEqual(1, userAttributes.Length),

                () => Assert.Contains("error.class", intrinsicAttributes),
                () => Assert.Contains("error.message", intrinsicAttributes),
                () => Assert.Contains("timestamp", intrinsicAttributes),
                () => Assert.Contains("type", intrinsicAttributes),

                () => Assert.Contains("custom attribute name", userAttributes)
                );
        }
示例#19
0
        public ActionResult AddValue(policyData vData, int id, bool literal, int linkId)
        {
            AttributeValueEntity ave = new AttributeValueEntity();

            ave.AttributeMatchId = id;
            ave.Literal          = literal;

            AttributeValueCollection maxColl = new AttributeValueCollection();
            PredicateExpression      pe      = new PredicateExpression(AttributeValueFields.AttributeMatchId == id);
            object maxObj = maxColl.GetScalar(AttributeValueFieldIndex.Order, null, AggregateFunction.Max, pe);

            if (maxObj != null && maxObj != DBNull.Value)
            {
                ave.Order = (int)maxObj + 1;
            }
            else
            {
                ave.Order = 0;
            }

            if (literal)
            {
                ave.Value = string.Empty;
            }
            else
            {
                ave.Value = null;
            }

            ave.Save();

            return(RedirectToAction("EditMatch", new { id = id, linkId = linkId }));
        }
示例#20
0
        public void OnReadAttributeComplete(int dwTransactionID, int hrStatus, int hClient, int dwNumItems, OPCHDA_ATTRIBUTE[] pAttributeValues, int[] phrErrors)
        {
            try
            {
                lock (this)
                {
                    Request request = (Request)m_requests[dwTransactionID];
                    if (request != null)
                    {
                        ItemAttributeCollection itemAttributeCollection = new ItemAttributeCollection();
                        itemAttributeCollection.ServerHandle = hClient;
                        AttributeValueCollection[] array = new AttributeValueCollection[pAttributeValues.Length];
                        for (int i = 0; i < pAttributeValues.Length; i++)
                        {
                            array[i]          = Interop.GetAttributeValueCollection(pAttributeValues[i], deallocate: false);
                            array[i].ResultID = OpcCom.Interop.GetResultID(phrErrors[i]);
                            itemAttributeCollection.Add(array[i]);
                        }

                        if (request.InvokeCallback(itemAttributeCollection))
                        {
                            m_requests.Remove(request.RequestID);
                        }
                    }
                }
            }
            catch (Exception exception)
            {
                HandleException(dwTransactionID, exception);
            }
        }
		public void Contains_AddCollectionWithTenObjects_AllObjectsAreInCollection() {
			var list = A.CollectionOfFake<object>(10);
			var collection = new AttributeValueCollection(list);
			foreach(var attribute in list) {
				Assert.IsTrue(collection.Contains(attribute));
			}
		}
示例#22
0
            public void when_default_fixture_values_are_used_then_serializes_correctly()
            {
                var attribValues = new AttributeValueCollection(AttributeDestinations.ErrorTrace);

                var attributes     = new ErrorTraceWireModel.ErrorTraceAttributesWireModel(attribValues, _stackTrace);
                var errorTraceData = new ErrorTraceWireModel(_timestamp, _path, _message, _exceptionClassName, attributes, _guid);

                var expectedResult =
                    "["
                    + _timestamp.ToUnixTimeMilliseconds()
                    + ",\"" + _path + "\",\""
                    + _message + "\",\""
                    + _exceptionClassName + "\",{"
                    + "\"stack_trace\":"
                    +
                    "[\"System.Exception: Inner Exception\",\"at WebApplication.Contact.Baz() in c:\\\\code\\\\dotnet_agent\\\\Agent\\\\NewRelic\\\\Profiler\\\\WebApplication1\\\\Contact.aspx.cs:line 50\",\"at WebApplication.Contact.Foo() in c:\\\\code\\\\dotnet_agent\\\\Agent\\\\NewRelic\\\\Profiler\\\\WebApplication1\\\\Contact.aspx.cs:line 40\",\"--- End of inner exception stack trace ---\",\"at WebApplication.Contact.Foo() in c:\\\\code\\\\dotnet_agent\\\\Agent\\\\NewRelic\\\\Profiler\\\\WebApplication1\\\\Contact.aspx.cs:line 46\",\"at WebApplication.Contact.Bar() in c:\\\\code\\\\dotnet_agent\\\\Agent\\\\NewRelic\\\\Profiler\\\\WebApplication1\\\\Contact.aspx.cs:line 28\",\"--- End of inner exception stack trace ---\",\"at WebApplication.Contact.Bar() in c:\\\\code\\\\dotnet_agent\\\\Agent\\\\NewRelic\\\\Profiler\\\\WebApplication1\\\\Contact.aspx.cs:line 34\",\"at WebApplication.Contact.Page_Load(Object sender, EventArgs e) in c:\\\\code\\\\dotnet_agent\\\\Agent\\\\NewRelic\\\\Profiler\\\\WebApplication1\\\\Contact.aspx.cs:line 22\",\"at System.Web.UI.Control.LoadRecursive()\",\"at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)\",\"at System.Web.UI.Page.HandleError(Exception e)\",\"at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)\",\"at System.Web.UI.Page.ProcessRequest(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)\",\"at System.Web.UI.Page.ProcessRequest(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)\",\"at System.Web.UI.Page.ProcessRequest()\",\"at System.Web.UI.Page.ProcessRequest(HttpContext context)\",\"at ASP.contact_aspx.ProcessRequest(HttpContext context) in c:\\\\Windows\\\\Microsoft.NET\\\\Framework64\\\\v4.0.30319\\\\Temporary ASP.NET Files\\\\webapplication1\\\\734e4ee5\\\\213b041b\\\\App_Web_lag4whrl.2.cs:line 0\",\"at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()\",\"at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()\",\"at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)}\"],"
                    + "\"" + AgentAttributesKey + "\":{},"
                    + "\"" + UserAttributesKey + "\":{},"
                    + "\"" + IntrinsicsKey + "\":{}},"
                    + "\"123\"]";

                var actualResult = JsonConvert.SerializeObject(errorTraceData);

                Assert.AreEqual(expectedResult, actualResult);
            }
示例#23
0
        public void Validate(string appenderName, AttributeValueCollection attributeValues)
        {
            // Ensure that if any of the buffer specific attributes are provided, they are all provided, and that they make sense.

            if (attributeValues.ContainsKey(Constants.AttributeNameSendWithBufferLevel) ||
                attributeValues.ContainsKey(Constants.AttributeNameStoreInBufferLevel) ||
                attributeValues.ContainsKey(Constants.AttributeNameBufferSize))
            {
                if ((!attributeValues.ContainsKey(Constants.AttributeNameSendWithBufferLevel)) ||
                    (!attributeValues.ContainsKey(Constants.AttributeNameStoreInBufferLevel)) ||
                    (!attributeValues.ContainsKey(Constants.AttributeNameBufferSize)))
                {
                    throw new GeneralAppenderException(appenderName, string.Format(
                                                           "If any of {0}, {1} or {2} is specified, than the other two need to be specified as well",
                                                           Constants.AttributeNameSendWithBufferLevel, Constants.AttributeNameStoreInBufferLevel, Constants.AttributeNameBufferSize));
                }

                int level =
                    attributeValues.ContainsKey(Constants.AttributeNameLevel) ?
                    LevelUtils.LevelNumber(attributeValues[Constants.AttributeNameLevel].Text) :
                    (int)Constants.DefaultAppenderLevel;

                int storeInBufferLevel  = LevelUtils.LevelNumber(attributeValues[Constants.AttributeNameStoreInBufferLevel].Text);
                int sendWithBufferLevel = LevelUtils.LevelNumber(attributeValues[Constants.AttributeNameSendWithBufferLevel].Text);

                if ((storeInBufferLevel > level) || (level > sendWithBufferLevel))
                {
                    throw new GeneralAppenderException(appenderName, string.Format(
                                                           "{0} must be equal or greater than {1} and equal or smaller than {2}",
                                                           Constants.AttributeNameLevel, Constants.AttributeNameStoreInBufferLevel,
                                                           Constants.AttributeNameSendWithBufferLevel));
                }
            }
        }
        public void GetTransactionTrace_AddsAsyncParametersToAllNodes()
        {
            var now    = new TimeSpan();
            var node1  = GetNodeBuilder(name: "1", startTime: now, duration: TimeSpan.FromSeconds(1));
            var node2  = GetNodeBuilder(name: "2", startTime: now, duration: TimeSpan.FromSeconds(.5));
            var node11 = GetNodeBuilder(name: "1.1", startTime: now, duration: TimeSpan.FromSeconds(.25));

            node1.Children.Add(node11);
            node1.Segment.ChildFinished(node11.Segment);

            var transaction           = BuildTestTransaction();
            var topLevelSegments      = new[] { node1.Build(), node2.Build() };
            var transactionMetricName = new TransactionMetricName("WebTransaction", "TrxName");
            var attributes            = new AttributeValueCollection(AttributeDestinations.TransactionTrace);

            var trace = _transactionTraceMaker.GetTransactionTrace(transaction, topLevelSegments, transactionMetricName, attributes);

            var realSegments = trace.TransactionTraceData.RootSegment.Children.First().Children;
            var segment1     = realSegments.ElementAt(0);
            var segment2     = realSegments.ElementAt(1);
            var segment11    = segment1.Children.ElementAt(0);

            NrAssert.Multiple(
                () => Assert.AreEqual(750, segment1.Parameters["exclusive_duration_millis"]),
                () => Assert.AreEqual(500, segment2.Parameters["exclusive_duration_millis"]),
                () => Assert.AreEqual(250, segment11.Parameters["exclusive_duration_millis"])
                );
        }
示例#25
0
        public void Verify_setting_priority()
        {
            var priority = 0.5f;

            var attribValues = new AttributeValueCollection(AttributeDestinations.ErrorEvent);

            _attribDefs.TimestampForError.TrySetValue(attribValues, DateTime.UtcNow);

            var wireModel = new ErrorEventWireModel(attribValues, false, priority);

            Assert.That(priority == wireModel.Priority);

            priority           = 0.0f;
            wireModel.Priority = priority;
            Assert.That(priority == wireModel.Priority);

            priority           = 1.0f;
            wireModel.Priority = priority;
            Assert.That(priority == wireModel.Priority);

            priority           = 1.1f;
            wireModel.Priority = priority;
            Assert.That(priority == wireModel.Priority);

            priority = -0.00001f;
            Assert.Throws <ArgumentException>(() => wireModel.Priority = priority);
            priority = float.NaN;
            Assert.Throws <ArgumentException>(() => wireModel.Priority = priority);
            priority = float.NegativeInfinity;
            Assert.Throws <ArgumentException>(() => wireModel.Priority = priority);
            priority = float.PositiveInfinity;
            Assert.Throws <ArgumentException>(() => wireModel.Priority = priority);
            priority = float.MinValue;
            Assert.Throws <ArgumentException>(() => wireModel.Priority = priority);
        }
示例#26
0
        /// <summary>
        /// Generates the JavaScript for a JSON object.
        /// </summary>
        /// <param name="optionValues"></param>
        /// <returns>
        /// JS code with the JSON object.
        /// </returns>
        public static string GenerateJson(AttributeValueCollection optionValues)
        {
            StringBuilder sb = new StringBuilder();

            sb.Append("{");

            bool firstItem = true;

            foreach (KeyValuePair <string, Value> option in optionValues)
            {
                string jsValue = null;

                // Do not test for IsNullOrEmpty. For example, appenders="" is legitimate (use 0 appenders)
                if (option.Value.Text != null)
                {
                    jsValue = option.Value.ValueInfo.ToJavaScript(option.Value.Text);
                }
                else if (option.Value.TextCollection != null)
                {
                    jsValue = "[" + String.Join(",", option.Value.TextCollection.Select(t => option.Value.ValueInfo.ToJavaScript(t))) + "]";
                }
                else
                {
                    continue;
                }

                sb.AppendFormat("{0}\"{1}\": {2}", firstItem ? "" : ", ", option.Key, jsValue);
                firstItem = false;
            }

            sb.Append("}");

            return(sb.ToString());
        }
示例#27
0
        public void Equals_CreateCollection_CollectionIsNotEquaNull()
        {
            var list       = A.CollectionOfFake <object>(10);
            var collection = new AttributeValueCollection(list);

            Assert.IsFalse(collection.Equals(null));
        }
示例#28
0
        public void Equals_CreateTwoIdenticallCollection_CollectionsAreNotEqual()
        {
            var list        = A.CollectionOfFake <object>(10);
            var collection1 = new AttributeValueCollection(list);
            var collection2 = new AttributeValueCollection(list);

            Assert.IsFalse(collection1.Equals(collection2));
        }
        public void WithNoValuesReturnsCorrectly()
        {
            var attributeValueCollection = new AttributeValueCollection();

            var result = attributeValueCollection.ToString();

            Assert.AreEqual( string.Empty, result );
        }
示例#30
0
            public void when_construtor_used_guid_property_is_set()
            {
                var attribValues = new AttributeValueCollection(AttributeDestinations.ErrorTrace);

                var attributes     = new ErrorTraceWireModel.ErrorTraceAttributesWireModel(attribValues, _stackTrace);
                var errorTraceData = new ErrorTraceWireModel(_timestamp, _path, _message, _exceptionClassName, attributes, _guid);

                Assert.AreEqual(_guid, errorTraceData.Guid);
            }
示例#31
0
        private IAttributeValueCollection GetCustomEventAttribs()
        {
            var result = new AttributeValueCollection(AttributeDestinations.CustomEvent);

            _attribDefs.CustomEventType.TrySetValue(result, "event_type");
            _attribDefs.Timestamp.TrySetDefault(result);

            return(result);
        }
        public void GetTransactionTrace_Throws_IfSegmentTreeIsEmpty()
        {
            var transaction           = BuildTestTransaction();
            var segments              = Enumerable.Empty <ImmutableSegmentTreeNode>();
            var transactionMetricName = new TransactionMetricName("WebTransaction", "TrxName");
            var attributes            = new AttributeValueCollection(AttributeDestinations.TransactionTrace);

            Assert.Throws <ArgumentException>(() => _transactionTraceMaker.GetTransactionTrace(transaction, segments, transactionMetricName, attributes));
        }
        protected EventWireModel(AttributeDestinations targetObject, IAttributeValueCollection attribValues, bool isSynthetics, float priority)
        {
            _targetObject   = targetObject;
            AttributeValues = new AttributeValueCollection(attribValues, _targetObject);
            Priority        = priority;
            IsSynthetics    = isSynthetics;

            AttributeValues.MakeImmutable();
        }
示例#34
0
        public IAttributeValueCollection GetAttributes(ImmutableTransaction immutableTransaction, TransactionMetricName transactionMetricName, TimeSpan?apdexT, TimeSpan totalTime, TransactionMetricStatsCollection txStats)
        {
            var attribVals = new AttributeValueCollection(AttributeValueCollection.AllTargetModelTypes);

            SetUserAndAgentAttributes(attribVals, immutableTransaction.TransactionMetadata);
            SetIntrinsicAttributes(attribVals, immutableTransaction, transactionMetricName, apdexT, totalTime, txStats);

            return(attribVals);
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="StructureValue"/> class.
        /// Values are populated with defaults
        /// </summary>
        /// <param name="theStructureDefinition">The structure definition.</param>
        /// <param name="parent">The parent.</param>
        public StructureValue(StructureDefinition theStructureDefinition, Value parent)
            : base(theStructureDefinition, parent)
        {
            m_StructureDefinition = theStructureDefinition;
            m_AttributeValues = new AttributeValueCollection(m_StructureDefinition.Name);

            foreach (var item in m_StructureDefinition.AttributeDefinitions)
            {
                AddAttributeValue(item, item.Type.Instantiate(this));
            }
        }
示例#36
0
        /// <summary>
        /// Generates the JavaScript for the call to setOptions to set the options for an object
        /// (the JL object itself, an appender or a logger).
        /// </summary>
        /// <param name="parentName">
        /// JavaScript variable that holds the element.
        /// </param>
        /// <param name="xe">
        /// XML element. The attributes on this element will provide the values for the options.
        /// </param>
        /// <param name="attributeInfos">
        /// Describes which attributes to use as options and how to validate them.
        /// 
        /// As regards attributeInfos that have a SubTagName:
        /// * The value of such an attribute is an array, for example [ 'a', 'b' ]
        /// * If there are no child elements with the given sub tag name, there is no value, and no entry for that attributeinfo in 
        ///   the generated setOption.
        /// * If there is only one child element and it does not have an attribute, the value is an empty array [].
        /// </param>
        /// <param name="initialAttributeValues">
        /// Initial attribute values. The elements found in xe will be added to this.
        /// If null, this method will create an empty collection itself.
        /// </param>
        /// <param name="sb">
        /// The JS code is added to this.
        /// </param>
        /// <param name="validate">
        /// If not null, this method is called on the generated attribute values. This can be used to throw an exception
        /// if the given parameters are not valid.
        /// </param>
        public static void ProcessOptionAttributes(string parentName, XmlElement xe, IEnumerable<AttributeInfo> attributeInfos,
            AttributeValueCollection initialAttributeValues, StringBuilder sb,
            Action<AttributeValueCollection> validate = null)
        {
            var attributeValues = initialAttributeValues ?? new AttributeValueCollection();
            XmlHelpers.ProcessAttributes(xe, attributeInfos, attributeValues);

            if (validate != null) { validate(attributeValues); }

            JavaScriptHelpers.GenerateSetOptions(parentName, attributeValues, sb);
        }
        /// <summary>
        /// Represents the HTML attribute "accept-charset". Multiple calls add additional values.
        /// </summary>
        /// <param name="characterSets">The list of values.</param>
        /// <returns>The same instance of <see cref="Hex.AttributeBuilders.HtmlAttributeBuilder"/>.</returns>
        public HtmlAttributeBuilder AddAcceptCharsets( params string[] characterSets )
        {
            AttributeValueCollection attributeValues = null;
            if( !this.Attributes.TryGetValue<AttributeValueCollection>( HtmlAttributes.AcceptCharset, out attributeValues ) )
            {
                attributeValues = new AttributeValueCollection();
                this.Attributes[ HtmlAttributes.AcceptCharset ] = attributeValues;
            }

            attributeValues.AddRange( characterSets );
            return this;
        }
        /// <summary>
        /// Represents the HTML attribute "form". Multiple calls add additional values.
        /// </summary>
        /// <param name="formIds">The list of values.</param>
        /// <returns>The same instance of <see cref="Hex.AttributeBuilders.HtmlAttributeBuilder"/>.</returns>
        public HtmlAttributeBuilder AddForm( params string[] formIds )
        {
            AttributeValueCollection attributeValues = null;
            if( !this.Attributes.TryGetValue<AttributeValueCollection>( HtmlAttributes.Form, out attributeValues ) )
            {
                attributeValues = new AttributeValueCollection();
                this.Attributes[ HtmlAttributes.Form ] = attributeValues;
            }

            attributeValues.AddRange( formIds );
            return this;
        }
        public void ReturnsCorrectly()
        {
            string attributeValue1 = "AttributeValue1";
            string attributeValue2 = "AttributeValue2";

            var attributeValueCollection = new AttributeValueCollection();
            attributeValueCollection.Add( attributeValue1 );
            attributeValueCollection.Add( attributeValue2 );

            var result = attributeValueCollection.ToString();

            string expectedResult = string.Format( "{0} {1}", attributeValue1, attributeValue2 );
            Assert.AreEqual( expectedResult, result );
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="StructureValue"/> class.
        /// </summary>
        /// <param name="theBytes">The bytes.</param>
        /// <param name="theStructureDefinition">The structure definition.</param>
        /// <param name="parent">The parent.</param>
        public StructureValue(ByteStore theBytes, StructureDefinition theStructureDefinition, Value parent)
            : base(theStructureDefinition, parent)
        {
            m_StructureDefinition = theStructureDefinition;
            m_AttributeValues = new AttributeValueCollection(m_StructureDefinition.Name); 

            int startPosition = theBytes.ReadPosition;
            foreach (var attribute in m_StructureDefinition.AttributeDefinitions)
            {
                int localOffset = theBytes.ReadPosition - startPosition;

                // Adjust alignment within current structure 
                if (attribute.ByteOffset.HasValue)
                {
                    while (attribute.ByteOffset.Value > localOffset)
                    {
                        theBytes.GetByte();
                        localOffset++;
                    }
                }

                // Error handling - trap decode errors for structure attributes and replace the attribute
                // value with an error value
                try
                {
                    // Decode the value from the binary data
                    Value theValue = attribute.Type.Decode(theBytes, this);

                    // Values decoded from switch cases need to have their name tweaked
                    if (attribute.Type.TypeId == TypeId.SwitchType)
                    {
                        SwitchDefinition switchDefinition = attribute.Type as SwitchDefinition;
                        SwitchCaseDefinition theCase = switchDefinition.GetSwitchCaseDefinition(this);
                        AddAttributeValue(attribute, theCase.Name, theValue);
                    }
                    else
                    {
                        AddAttributeValue(attribute, theValue);
                    }
                }
                catch (DataDictionaryException ex)
                {
                    AddAttributeValue(attribute, new ErrorValue (string.Format ("{0} Error: {1}", InitialType.Name, ex.Message), this));
                    throw new PartialDecodeException(GetTopParent(), ex.Message);
                }
            }
        }
示例#41
0
        // --------------------------------

        public void ProcessLogger(XmlElement xe, string parentName, Dictionary<string, string> appenderNames, Sequence sequence,
            IEnumerable<AttributeInfo> loggerAttributes, StringBuilder sb)
        {
            if (xe == null) { return; }

            var appendersValue = new AppendersValue(appenderNames);
            string appenders = XmlHelpers.OptionalAttribute(xe, "appenders", null, appendersValue.ValidValueRegex);
            string loggerName = XmlHelpers.OptionalAttribute(xe, "name", "");

            JavaScriptHelpers.GenerateLogger(Constants.JsLoggerVariable, loggerName, sb);

            AttributeValueCollection attributeValues = new AttributeValueCollection();
            if (appenders != null)
            {
                attributeValues[Constants.JsLoggerAppendersOption] = new Value(appenders, appendersValue);
            }

            Utils.ProcessOptionAttributes(Constants.JsLoggerVariable, xe, loggerAttributes, attributeValues, sb);
        }
        public ActionResult AddValue(policyData vData, int id, bool literal, int linkId)
        {
            AttributeValueEntity ave = new AttributeValueEntity();
            ave.AttributeMatchId = id;
            ave.Literal = literal;

            AttributeValueCollection maxColl = new AttributeValueCollection();
            PredicateExpression pe = new PredicateExpression(AttributeValueFields.AttributeMatchId == id);
            object maxObj = maxColl.GetScalar(AttributeValueFieldIndex.Order, null, AggregateFunction.Max,pe);
            if (maxObj != null && maxObj != DBNull.Value)
                ave.Order = (int)maxObj + 1;
            else
                ave.Order = 0;

            if (literal)
                ave.Value = string.Empty;
            else
                ave.Value = null;

            ave.Save();

            return RedirectToAction("EditMatch", new { id = id, linkId = linkId });
        }
        /// <summary>
        /// Reads the attributes of xe and adds their names and values to attributeValues.
        /// 
        /// Validates the attributes based on the contents of attributeInfos. Attributes that have been
        /// listed as Ignore will not be added to attributeValues.
        /// 
        /// As regards attributeInfos that have a SubTagName:
        /// * If there are no child elements with that sub tag name, than nothing will be added to attributeValues.
        /// * If there is a child element, but it has no attribute, than no value will be added to the collection of
        ///   values of that sub tag. This means that if there is only one child element and it has no attribute,
        ///   you get an empty collection.
        /// </summary>
        /// <param name="xe"></param>
        /// <param name="attributeInfos"></param>
        /// <param name="attributeValues">
        /// key: attribute name
        /// value: value of the attribute. Cannot be null.
        /// </param>
        public static void ProcessAttributes(
            XmlElement xe, IEnumerable<AttributeInfo> attributeInfos, AttributeValueCollection attributeValues)
        {
            // Ensure there are no unknown attributes - that is, not listed in attributeInfos

            EnsureAllAttributesKnown(xe, attributeInfos);

            // Process all attributes that should not be ignored

            foreach (AttributeInfo attributeInfo in attributeInfos)
            {
                // Get value of the attribute and validate that it is correct. We want to do this for all attributes.
                // Note that if the attribute has a SubTagName, it will not appear as an xml attribute in the xml,
                // so attributeValueText will always be null.

                string attributeName = attributeInfo.Name;
                string attributeValueText = OptionalAttribute(xe, attributeName, null, attributeInfo.ValueInfo.ValidValueRegex);

                if (attributeInfo.AttributeValidity == AttributeInfo.AttributeValidityEnum.NoOption) { continue; }

                if (attributeInfo.SubTagName != null)
                {
                    IEnumerable<string> subTagValues = SubTagValues(xe, attributeInfo);

                    if (subTagValues != null)
                    {
                        attributeValues[attributeInfo.SubTagName] = new Value(subTagValues, attributeInfo.ValueInfo);
                    }
                }
                else
                {
                    // Attribute is a real xml attribute, rather than a sub tag.

                    if (attributeValueText != null)
                    {
                        attributeValues[attributeName] = new Value(attributeValueText, attributeInfo.ValueInfo);
                    }
                    else if (attributeInfo.AttributeValidity == AttributeInfo.AttributeValidityEnum.RequiredOption)
                    {
                        throw new MissingAttributeException(xe.Name, attributeName);
                    }
                }
            }
        }
 /// <summary>
 /// Generates the JavaScript to set options on an object
 /// </summary>
 /// <param name="parentName">
 /// Name of the JavaScript variable that holds the object.
 /// </param>
 /// <param name="optionValues">
 /// The names and values of the options.
 /// </param>
 /// <param name="sb">
 /// The JavaScript code is added to this StringBuilder.
 /// </param>
 public static void GenerateSetOptions(string parentName, AttributeValueCollection optionValues, StringBuilder sb)
 {
     string optionsJson = GenerateJson(optionValues);
     sb.AppendLine(string.Format("{0}.setOptions({1});", parentName, optionsJson));
 }
		public void Index_AddCollectionWithOneObject_SameObjectFromIndex() {
			var list = A.CollectionOfFake<object>(1);
			var collection = new AttributeValueCollection(list);
			Assert.AreSame(list.First(), collection[0]);
		}
		public void Count_AddCollectionWithTenObjects_ReturnsTen() {
			var list = A.CollectionOfFake<object>(10);
			var collection = new AttributeValueCollection(list);
			Assert.AreEqual(10, collection.Count);
		}
		public void Index_AddCollectionWithTenObjects_LastOjbectSameObjectAsLastIndex() {
			var list = A.CollectionOfFake<object>(10);
			var collection = new AttributeValueCollection(list);
			Assert.AreSame(list.Last(), collection[9]);
		}
		public void Equals_CreateCollection_CollectionIsEqualsItself() {
			var list = A.CollectionOfFake<object>(10);
			var collection = new AttributeValueCollection(list);
			Assert.IsTrue(collection.Equals(collection));
		}
		public void Equals_CreateTwoIdenticallCollection_CollectionsAreNotEqual() {
			var list = A.CollectionOfFake<object>(10);
			var collection1 = new AttributeValueCollection(list);
			var collection2 = new AttributeValueCollection(list);
			Assert.IsFalse(collection1.Equals(collection2));
		}
        // This version is not reliant on sitting in a web site, so can be unit tested.
        // generateClosure - if false, no function closure is generated around the generated JS code. Only set to false when unit testing.
        // Doing this assumes that jsnlog.js has loaded before the code generated by the method is executed.
        //
        // You want to set this to false during unit testing, because then you need direct access outside the closure of variables
        // that are private to the closure, specifically dummyappenders that store the log messages you receive, so you can unit test them.
        public void ProcessRootExec(XmlElement xe, StringBuilder sb, Func<string, string> virtualToAbsoluteFunc, string userIp, string requestId, bool generateClosure)
        {
            string loggerProductionLibraryVirtualPath = XmlHelpers.OptionalAttribute(xe, "productionLibraryPath", "");
            bool loggerEnabled = bool.Parse(XmlHelpers.OptionalAttribute(xe, "enabled", "true", Constants.RegexBool));

            string loggerProductionLibraryPath = null;
            if (!string.IsNullOrEmpty(loggerProductionLibraryVirtualPath))
            {
                // Every hard coded path must be resolved. See the declaration of DefaultDefaultAjaxUrl
                loggerProductionLibraryPath = virtualToAbsoluteFunc(loggerProductionLibraryVirtualPath);
            }

            if (!loggerEnabled)
            {
                if (!string.IsNullOrWhiteSpace(loggerProductionLibraryPath))
                {
                    JavaScriptHelpers.WriteScriptTag(loggerProductionLibraryPath, sb);
                }

                JavaScriptHelpers.WriteJavaScriptBeginTag(sb);
                Utils.ProcessOptionAttributes(Constants.JsLogObjectName, xe, Constants.JSNLogAttributes, null, sb);
                JavaScriptHelpers.WriteJavaScriptEndTag(sb);

                return;
            }

            JavaScriptHelpers.WriteJavaScriptBeginTag(sb);
            if (generateClosure) 
            {
                JavaScriptHelpers.WriteLine(string.Format("var {0} = function () {{", Constants.GlobalMethodCalledAfterJsnlogJsLoaded), sb); 
            }

            // Generate setOptions for JSNLog object itself

            AttributeValueCollection attributeValues = new AttributeValueCollection();

            attributeValues[Constants.JsLogObjectClientIpOption] = new Value(userIp, new StringValue());
            attributeValues[Constants.JsLogObjectRequestIdOption] = new Value(requestId, new StringValue());

            // Set default value for defaultAjaxUrl attribute
            attributeValues[Constants.JsLogObjectDefaultAjaxUrlOption] = 
                new Value(virtualToAbsoluteFunc(Constants.DefaultDefaultAjaxUrl), new StringValue());

            Utils.ProcessOptionAttributes(Constants.JsLogObjectName, xe, Constants.JSNLogAttributes,
                attributeValues, sb);

            // Process all loggers and appenders

            Dictionary<string, string> appenderNames = new Dictionary<string, string>();
            Sequence sequence = new Sequence();

            // -----------------
            // First process all assembly tags

            topLeveltagInfos =
                new List<XmlHelpers.TagInfo>(
                    new[] {
                            new XmlHelpers.TagInfo(Constants.TagAssembly, ProcessAssembly, Constants.AssemblyAttributes, (int)Constants.OrderNbr.Assembly)
                        });

            XmlHelpers.ProcessNodeList(
                xe.ChildNodes,
                topLeveltagInfos.Where(t => t.Tag == Constants.TagAssembly).ToList(),
                null, appenderNames, sequence, sb,
                string.Format("^{0}*", Constants.TagAssembly));

            // -----------------
            // The elements (if any) from external assemblies have now been loaded (with the assembly elements).
            // Now add the elements from the executing assembly after the external ones. 
            // This way, logger elements are processed last - after any new appenders.

            AddAssemblyTagInfos(Assembly.GetExecutingAssembly());

            // Now process the external and internal elements, but not the assembly elements.

            XmlHelpers.ProcessNodeList(
                xe.ChildNodes,
                topLeveltagInfos,
                null, appenderNames, sequence, sb,
                string.Format("^((?!{0}).)*$", Constants.TagAssembly));

            // -------------

            if (generateClosure) 
            {
                // Generate code to execute the function, in case jsnlog.js has already been loaded.
                // Wrap in try catch, so if jsnlog.js hasn't been loaded, the resulting exception will be swallowed.
                JavaScriptHelpers.WriteLine(string.Format("}}; try {{ {0}(); }} catch(e) {{}};", Constants.GlobalMethodCalledAfterJsnlogJsLoaded), sb); 
            }
            JavaScriptHelpers.WriteJavaScriptEndTag(sb);

            // Write the script tag that loads jsnlog.js after the code generated from the web.config.
            // When using jsnlog.js as an AMD module or in a bundle, jsnlog.js will be loaded after that code as well,
            // and creating a similar situation in the default out of the box loading option makes it more likely
            // you pick up bugs during testing.
            if (!string.IsNullOrWhiteSpace(loggerProductionLibraryPath))
            {
                JavaScriptHelpers.WriteScriptTag(loggerProductionLibraryPath, sb);
            }
        }
		public void Equals_CreateCollection_CollectionIsNotEquaNull() {
			var list = A.CollectionOfFake<object>(10);
			var collection = new AttributeValueCollection(list);
			Assert.IsFalse(collection.Equals(null));
		}
        public ActionResult ValueOrder(policyData vData, int id, int id2, int linkId, FormCollection collection)
        {
            AttributeValueEntity attrValue = new AttributeValueEntity(id2);
            AttributeValueCollection coll = new AttributeValueCollection();

            PredicateExpression pe = new PredicateExpression(AttributeValueFields.Id != attrValue.Id);
            pe.Add(AttributeValueFields.AttributeMatchId == id);
            SortExpression se = null;

            if (collection["up"] != null)
            {
                // Find all categories with display index less than ours.
                pe.Add(AttributeValueFields.Order <= attrValue.Order);

                // Order by display index, highest first.
                se = new SortExpression(AttributeValueFields.Order | SortOperator.Descending);
            }
            else
            {
                // Find all categories with display index greater than ours.
                pe.Add(AttributeValueFields.Order >= attrValue.Order);

                // Order by display index, lowest first.
                se = new SortExpression(AttributeValueFields.Order | SortOperator.Ascending);
            }

            // Swap with closest one.
            if (coll.GetMulti(pe, 1, se) && coll.Count > 0)
            {
                int temp = coll[0].Order;
                coll[0].Order = attrValue.Order;
                attrValue.Order = temp;

                attrValue.Save();
                coll.SaveMulti();
            }

            return RedirectToAction("EditMatch", new { id = id, linkId = linkId });
        }