public void EventDataSet_GetStreamValue_SimpleGet() { EventDataSet testSet = new EventDataSet(); testSet.AddSample(0, 0, 1); Assert.AreEqual(1, testSet.GetStreamValue(0, 0)); }
void DrawGraph(EventDataSet dataSet, Rect rect, int startTime, int duration, bool expanded) { if (Event.current.type != EventType.Repaint) { return; } rect = new Rect(rect.x + 1, rect.y + 1, rect.width - 2, rect.height - 2); GraphDefinition gd; if (!m_GraphDefinitions.TryGetValue(dataSet.Graph, out gd)) { return; } if (m_GraphMaterial == null) { // best material options are "Unlit/Color" or "UI/Default". // Unlit/Color is more efficient, but does not support alpha // UI/Default does support alpha m_GraphMaterial = new Material(Shader.Find("Unlit/Color")); } int maxValue = gd.GetMaxValue(dataSet); foreach (var l in gd.layers) { l.Draw(dataSet, rect, startTime, duration, m_InspectFrame, expanded, m_GraphMaterial, maxValue); } }
public void EventDataSet_HasDataAfterFrame_ProperBehaviorOnNoChildCase() { EventDataSet parentSet = new EventDataSet(); parentSet.AddSample(0, 0, 1); Assert.AreEqual(true, parentSet.HasDataAfterFrame(0), "Returned false despite the fact that the last frame of the stream should be nonzero."); }
public void EventDataPlayerSession_HandleOperationDestroy_DestroyedEventHasParentCase() { EventDataPlayerSession edps = new EventDataPlayerSession(); DiagnosticEvent dependencyEvt = CreateNewGenericEvent(ResourceManager.DiagnosticEventType.AsyncOperationReferenceCount, 0, 0, 1001); DiagnosticEvent creationEvt = CreateNewGenericEvent(ResourceManager.DiagnosticEventType.AsyncOperationCreate, 0, 1, 1000, new int[] { dependencyEvt.ObjectId }); DiagnosticEvent deletionEvt = CreateNewGenericEvent(ResourceManager.DiagnosticEventType.AsyncOperationDestroy, 1, 1, 1001); bool entryCreated = false; edps.AddSample(dependencyEvt, false, ref entryCreated); Assert.IsTrue(entryCreated, "Either a new entry was supposed to be created, but was not, or the value of entryCreated was not properly updated."); edps.AddSample(creationEvt, false, ref entryCreated); Assert.IsTrue(entryCreated, "Either a new entry was supposed to be created, but was not, or the value of entryCreated was not properly updated."); edps.AddSample(deletionEvt, false, ref entryCreated); Assert.IsFalse(entryCreated, "Either a new entry was created when it shouldn't have been, or the value of entryCreated was not properly updated."); Assert.AreEqual(1, edps.m_RootStreamEntry.Children.Count(), "DependencyEvt's id should have been removed from RootStreamEntry's children because it is a dependency."); Assert.AreEqual(1, edps.m_Queue.Count, "Deletion event should have been added to the removal queue."); edps.HandleOperationDestroy(deletionEvt); Assert.IsFalse(edps.m_DataSets.ContainsKey(deletionEvt.ObjectId), "DataSet was not properly removed after dependency was cleared. "); EventDataSet creationEvtEds = null; Assert.IsTrue(edps.m_DataSets.TryGetValue(creationEvt.ObjectId, out creationEvtEds), "Parent event was removed from m_DataSets incorrectly."); Assert.IsNull(creationEvtEds.m_Children, "dependencyEvt's dataset should have been removed from the children of creationEvt's dataset. "); Assert.AreEqual(1, edps.m_Queue.Count, "No further deletion events should have been added to the deletion queue."); }
private List <COMTRADEChannelData> GetDigitalChannelData(EventDataSet eventDataSet) { // Get an arbitrary data series from the collection of waveforms so // that we can use it to determine the timestamp of each data point DataSeries series = eventDataSet.DataGroup[0]; // Create the function to convert a name and an index to a COMTRADEChannelData Func <string, int, COMTRADEChannelData> toChannelData = (name, index) => new COMTRADEChannelData() { GroupOrder = 0, LoadOrder = index, OriginalChannelIndex = index, Name = name, Data = series.Multiply(0.0D) }; // Get the collection of COMTRADEChannelData for the fault-related digitals List <COMTRADEChannelData> digitalChannelData = new string[] { "Fault Detected" } .Concat(GetAllFaultTypes().Select(faultType => string.Format("{0} Fault Type", faultType))) .Select(toChannelData) .ToList(); // Populate the data points for each digital channel // based on the fault type of each segment of fault data foreach (Fault.Segment segment in eventDataSet.Faults.SelectMany(fault => fault.Segments)) { // Get the fault type of the segment FaultType faultType = segment.FaultType; // Get the value of each digital in this segment bool[] digitals = { faultType != FaultType.None, faultType == FaultType.AN, faultType == FaultType.BN, faultType == FaultType.CN, faultType == FaultType.AB, faultType == FaultType.BC, faultType == FaultType.CA, faultType == FaultType.ABG, faultType == FaultType.BCG, faultType == FaultType.CAG, faultType == FaultType.ABC }; // Populate the data points for this segment with the proper values based on fault type for (int i = 0; i < digitalChannelData.Count; i++) { double value = Convert.ToDouble(digitals[i]); for (int j = segment.StartSample; j <= segment.EndSample; j++) { digitalChannelData[i].Data.DataPoints[j].Value = value; } } } return(digitalChannelData); }
public override global::System.Data.DataSet Clone() { EventDataSet cln = ((EventDataSet)(base.Clone())); cln.InitVars(); cln.SchemaSerializationMode = this.SchemaSerializationMode; return(cln); }
public void DataStreamEntry_IdEqualsDataSetObjectId() { EventDataSet eds = new EventDataSet(100, "graph", "name", 0); EventGraphListView.DataStreamEntry entry = new EventGraphListView.DataStreamEntry(eds, 0); Assert.AreEqual(eds.ObjectId, entry.id, "Event Hiding functionality relies on DataStreamEntry ids being the same as their underlying ObjectId."); }
public void EventDataSet_HasRefcountAfterFrame_ReturnsTrueOnTrivialCase() { EventDataSet testSet = new EventDataSet(); //Add sample to the refcount stream testSet.AddSample((int)ResourceManager.DiagnosticEventType.AsyncOperationReferenceCount, 5, 1); Assert.AreEqual(true, testSet.HasRefcountAfterFrame(0, true), "Refcount after frame was considered 0 when sample should have been added."); }
public void EventDataSet_AddChild_SimpleAdd() { EventDataSet testSet = new EventDataSet(); EventDataSet childSet = new EventDataSet(); testSet.AddChild(childSet); Assert.AreEqual(true, testSet.HasChildren, "hasChildren not properly updated."); Assert.AreEqual(childSet.ObjectId, testSet.m_Children[childSet.ObjectId].ObjectId, "Child not successfully retrieved from dictionary. "); }
public void EventDataSet_GetStream_SimpleGet() { EventDataSet testSet = new EventDataSet(); testSet.AddSample(0, 0, 1); var soughtStream = testSet.m_Streams[0]; Assert.AreEqual(soughtStream, testSet.GetStream(0), "Correct stream not returned by GetStream"); }
public void EventDataSet_AddSample_AddsToCorrectStream() { EventDataSet testSet = new EventDataSet(); testSet.AddSample(2, 0, 2); Assert.NotNull(testSet.m_Streams, "List of streams not properly initialized."); Assert.AreEqual(true, testSet.m_Streams.Count > 0, "List of streams was initialized, but not assigned to."); Assert.NotNull(testSet.m_Streams[2], "Stream 2 should not be null, as a sample should've been added to it."); Assert.AreEqual(2, testSet.m_Streams[2].GetValue(0), "Value retrieved from stream was incorrect."); }
public void EventDataSet_GetStream_ReturnsNullOnNonexistentStream() { EventDataSet testSet = new EventDataSet(); Assert.IsNull(testSet.GetStream(1), "GetStream should return null when queried with a stream index greater than the count of total streams."); testSet.AddSample(2, 0, 2); Assert.IsNull(testSet.GetStream(1), "GetStream should return null when querying an uninitialized stream. "); }
public static global::System.Xml.Schema.XmlSchemaComplexType GetTypedDataSetSchema(global::System.Xml.Schema.XmlSchemaSet xs) { EventDataSet ds = new EventDataSet(); global::System.Xml.Schema.XmlSchemaComplexType type = new global::System.Xml.Schema.XmlSchemaComplexType(); global::System.Xml.Schema.XmlSchemaSequence sequence = new global::System.Xml.Schema.XmlSchemaSequence(); global::System.Xml.Schema.XmlSchemaAny any = new global::System.Xml.Schema.XmlSchemaAny(); any.Namespace = ds.Namespace; sequence.Items.Add(any); type.Particle = sequence; global::System.Xml.Schema.XmlSchema dsSchema = ds.GetSchemaSerializable(); if (xs.Contains(dsSchema.TargetNamespace)) { global::System.IO.MemoryStream s1 = new global::System.IO.MemoryStream(); global::System.IO.MemoryStream s2 = new global::System.IO.MemoryStream(); try { global::System.Xml.Schema.XmlSchema schema = null; dsSchema.Write(s1); for (global::System.Collections.IEnumerator schemas = xs.Schemas(dsSchema.TargetNamespace).GetEnumerator(); schemas.MoveNext();) { schema = ((global::System.Xml.Schema.XmlSchema)(schemas.Current)); s2.SetLength(0); schema.Write(s2); if ((s1.Length == s2.Length)) { s1.Position = 0; s2.Position = 0; for (; ((s1.Position != s1.Length) && (s1.ReadByte() == s2.ReadByte()));) { ; } if ((s1.Position == s1.Length)) { return(type); } } } } finally { if ((s1 != null)) { s1.Close(); } if ((s2 != null)) { s2.Close(); } } } xs.Add(dsSchema); return(type); }
public void EventDataSet_HasDataAfterFrame_ProperBehaviorOnChildHasNoStreamCase() { EventDataSet parentSet = new EventDataSet(); EventDataSet childSet = new EventDataSet(); Assert.AreEqual(false, parentSet.HasDataAfterFrame(0), "HasDataAfterFrame should always be false for a dataset with no streams and no children."); Assert.AreEqual(false, childSet.HasDataAfterFrame(0), "HasDataAfterFrame should always be false for a dataset with no streams and no children."); parentSet.AddChild(childSet); Assert.AreEqual(false, parentSet.HasDataAfterFrame(0), "HasDataAfterFrame should always be false for a dataset with no streams and a child that has no samples/streams."); }
public void EventDataSet_GetStreamValue_ReturnsZeroOnNullStreamIndex() { EventDataSet testSet = new EventDataSet(); //stream number > stream count case Assert.AreEqual(0, testSet.GetStreamValue(1, 1), "GetStreamValue should return 0 when queried with a stream index greater than the count of total streams. "); testSet.AddSample(2, 0, 2); //null stream case Assert.AreEqual(0, testSet.GetStreamValue(1, 0), "GetStreamValue should return 0 when querying the index of an uninitialized stream. "); }
public void EventDataSet_HasDataAfterFrame_ProperBehaviorOnChildHasStreamCase() { EventDataSet parentSet = new EventDataSet(); EventDataSet childSet = new EventDataSet(); childSet.AddSample(0, 0, 1); Assert.AreEqual(false, parentSet.HasDataAfterFrame(0), "HasDataAfterFrame should always be false for a dataset with no streams and no children."); Assert.AreEqual(true, childSet.HasDataAfterFrame(0), "HasDataAfterFrame should return true because the last sample of one of it's streams is nonzero."); parentSet.AddChild(childSet); Assert.AreEqual(true, parentSet.HasDataAfterFrame(0), "HasDataAfterFrame returned false even though a child EventDataSet has data past frame 0."); }
public void EventDataSet_AddChild_ConfirmChildObjectConsistentWithReference() { EventDataSet parentSet1 = new EventDataSet(); EventDataSet parentSet2 = new EventDataSet(); EventDataSet childSet = new EventDataSet(); parentSet1.AddChild(childSet); parentSet2.AddChild(childSet); childSet.DisplayName = "SameChild"; Assert.AreEqual("SameChild", parentSet1.m_Children[childSet.ObjectId].DisplayName, "Display name not changed in m_Children despite being changed on child EventDataSet itself."); Assert.AreEqual("SameChild", parentSet2.m_Children[childSet.ObjectId].DisplayName, "Display name not changed in m_Children despite being changed on child EventDataSet itself."); }
public void EventDataSet_RemoveChild_SimpleAddRemove() { EventDataSet parentSet = new EventDataSet(); EventDataSet childSet = new EventDataSet(); parentSet.AddChild(childSet); Assert.AreEqual(true, parentSet.HasChildren, "HasChildren should be true after a child is added. "); parentSet.RemoveChild(childSet.ObjectId); Assert.AreEqual(false, parentSet.HasChildren, "HasChildren should be false after child is removed. "); Assert.IsNull(parentSet.m_Children, "m_Children should be set to null after last child is removed. "); }
public override void Draw(EventDataSet dataSet, Rect rect, int startFrame, int frameCount, int inspectFrame, bool expanded, Material material, int maxValue) { if (dataSet == null || material == null) { return; } var stream = dataSet.GetStream(Stream); if (stream != null && stream.samples.Count > 0) { material.color = GraphColor; if (m_Mesh == null) { m_Mesh = new Mesh(); } m_Verts.Clear(); m_Indices.Clear(); var endTime = startFrame + frameCount; m_Bounds = new Rect(rect); m_GridSize.x = m_Bounds.width / frameCount; m_GridSize.y = m_Bounds.height / maxValue; int previousFrameNumber = endTime; int currentFrame = endTime; for (int i = stream.samples.Count - 1; i >= 0 && currentFrame > startFrame; --i) { currentFrame = stream.samples[i].frame; var frame = Mathf.Max(currentFrame, startFrame); if (stream.samples[i].data > 0) { AddQuadToMesh(frame - startFrame, previousFrameNumber - startFrame, 0, stream.samples[i].data); } previousFrameNumber = frame; } if (m_Verts.Count > 0) { m_Mesh.Clear(true); m_Mesh.SetVertices(m_Verts); m_Mesh.triangles = m_Indices.ToArray(); material.SetPass(0); Graphics.DrawMeshNow(m_Mesh, Vector3.zero, Quaternion.identity); } } }
public void WriteResults(DbAdapterContainer dbAdapterContainer, MeterDataSet meterDataSet) { CycleDataResource cycleDataResource; FaultDataResource faultDataResource; DataGroup dataGroup; FaultGroup faultGroup; List <int> seriesIDs; EventDataSet eventDataSet; string rootFileName; string fileName; cycleDataResource = meterDataSet.GetResource(() => CycleDataResource.GetResource(meterDataSet, dbAdapterContainer)); faultDataResource = meterDataSet.GetResource(() => new FaultDataResource(dbAdapterContainer)); if (!Directory.Exists(m_resultsPath)) { Directory.CreateDirectory(m_resultsPath); } for (int i = 0; i < cycleDataResource.DataGroups.Count; i++) { dataGroup = cycleDataResource.DataGroups[i]; if (faultDataResource.FaultLookup.TryGetValue(dataGroup, out faultGroup)) { rootFileName = FilePath.GetFileNameWithoutExtension(meterDataSet.FilePath); fileName = string.Format("{0},{1:000},Line{2}.dat", rootFileName, i, dataGroup.Line.AssetKey); seriesIDs = dataGroup.DataSeries .Select(series => series.SeriesInfo.ID) .ToList(); eventDataSet = new EventDataSet() { ResultsPath = Path.Combine(m_resultsPath, fileName), MeterDataSet = meterDataSet, TimeZoneOffset = GetTimeZoneOffset(meterDataSet.Meter.TimeZone, dataGroup.StartTime), DataGroup = dataGroup, VICycleDataGroup = cycleDataResource.VICycleDataGroups[i], Faults = faultGroup.Faults, OutputChannels = dbAdapterContainer.GetAdapter <FaultLocationInfoDataContext>().OutputChannels.Where(channel => seriesIDs.Contains(channel.SeriesID)).ToList() }; WriteResults(eventDataSet); } } }
public void EventDataSet_HasRefcountAfterFrame_ReturnsTrueOnChildCase() { EventDataSet testSet = new EventDataSet(); testSet.AddSample((int)ResourceManager.DiagnosticEventType.AsyncOperationReferenceCount, 2, 1); testSet.AddSample((int)ResourceManager.DiagnosticEventType.AsyncOperationReferenceCount, 4, 0); EventDataSet childSet = new EventDataSet(); childSet.AddSample((int)ResourceManager.DiagnosticEventType.AsyncOperationReferenceCount, 5, 1); testSet.AddChild(childSet); Assert.AreEqual(true, testSet.HasRefcountAfterFrame(3, true), "Child refcount not properly considered when checking parent's refcount."); }
public void EventDataSet_AddSample_ProperlyCreatesNullStreams() { EventDataSet testSet = new EventDataSet(); testSet.AddSample(4, 0, 2); Assert.NotNull(testSet.m_Streams, "List of streams not properly initialized."); Assert.AreEqual(true, testSet.m_Streams.Count > 0, "List of streams was initialized, but not assigned to."); Assert.IsNull(testSet.m_Streams[0], "0th stream was not null initialized like expected."); Assert.IsNull(testSet.m_Streams[1], "1th stream was not null initialized like expected."); Assert.IsNull(testSet.m_Streams[2], "2nd stream was not null initialized like expected."); Assert.IsNull(testSet.m_Streams[3], "3rd stream was not null initialized like expected."); Assert.NotNull(testSet.m_Streams[4], "4th stream was null initialized when it should have had a value added to it."); Assert.AreEqual(2, testSet.m_Streams[4].GetValue(0), "Value retrieved from stream was incorrect."); }
private void WriteResults(EventDataSet eventDataSet) { const StringComparison IgnoreCase = StringComparison.OrdinalIgnoreCase; // Get the path to the original data file string dataFilePath; string directory; string rootFileName; string schemaFilePath; Parser originalFileParser = null; dataFilePath = eventDataSet.MeterDataSet.FileGroup.DataFiles .Select(dataFile => dataFile.FilePath) .FirstOrDefault(path => path.EndsWith(".dat", IgnoreCase) || path.EndsWith(".d00", IgnoreCase)); if (File.Exists(dataFilePath)) { // Get the path to the original schema file directory = FilePath.GetDirectoryName(dataFilePath); rootFileName = FilePath.GetFileNameWithoutExtension(dataFilePath); schemaFilePath = Path.Combine(directory, rootFileName + ".cfg"); if (File.Exists(schemaFilePath)) { // Create a parser to parse the original COMTRADE files originalFileParser = new Parser() { FileName = dataFilePath, InferTimeFromSampleRates = true, Schema = new Schema(schemaFilePath) }; } } using (originalFileParser) { if ((object)originalFileParser != null) { originalFileParser.OpenFiles(); } // Write results to the COMTRADE fault record using the parser WriteResults(eventDataSet, originalFileParser); } }
private void WriteResults(EventDataSet eventDataSet, Parser originalFileParser) { // Assume the data file path is the same as the results file path // and determine the path to the header and schema files string directory = FilePath.GetDirectoryName(eventDataSet.ResultsPath); string rootFileName = FilePath.GetFileNameWithoutExtension(eventDataSet.ResultsPath); string headerFilePath = Path.Combine(directory, rootFileName + ".hdr"); string schemaFilePath = Path.Combine(directory, rootFileName + ".cfg"); string dataFilePath = eventDataSet.ResultsPath; Schema schema; // Get structures containing the data to be written to the results files COMTRADEData comtradeData = new COMTRADEData(); // If there are no waveforms to be written to the file, give up if (!eventDataSet.OutputChannels.Any()) { return; } comtradeData.StationName = eventDataSet.MeterDataSet.Meter.Name; comtradeData.DeviceID = eventDataSet.MeterDataSet.Meter.AssetKey; comtradeData.DataStartTime = eventDataSet.DataGroup.StartTime; comtradeData.SampleCount = eventDataSet.DataGroup.Samples; comtradeData.SamplingRate = eventDataSet.DataGroup.Samples / (eventDataSet.DataGroup.EndTime - eventDataSet.DataGroup.StartTime).TotalSeconds; comtradeData.AnalogChannelData = GetAnalogChannelData(eventDataSet); comtradeData.DigitalChannelData = GetDigitalChannelData(eventDataSet); // If the original file is available, use data from the original file // in order to update the data to be written to the results files if ((object)originalFileParser != null) { FixCOMTRADEData(comtradeData, originalFileParser, eventDataSet.TimeZoneOffset); } // Write data to the header file WriteHeaderFile(eventDataSet, headerFilePath); // Write data to the schema file schema = WriteSchemaFile(comtradeData, schemaFilePath); // Write data to the data file WriteDataFile(comtradeData, schema, dataFilePath); }
public override void Draw(EventDataSet dataSet, Rect rect, int startFrame, int frameCount, int inspectFrame, bool expanded, Material material, int maxValue) { if (dataSet == null) { return; } var endTime = startFrame + frameCount; var stream = dataSet.GetStream(Stream); if (stream != null) { var prevCol = UnityEngine.GUI.color; UnityEngine.GUI.color = GraphColor; if (expanded) { var text = new GUIContent(maxValue.ToString()); var size = UnityEngine.GUI.skin.label.CalcSize(text); var labelRect = new Rect(rect.xMin + 2, rect.yMin, size.x, size.y); EditorGUI.LabelField(labelRect, text); labelRect = new Rect(rect.xMax - size.x, rect.yMin, size.x, size.y); EditorGUI.LabelField(labelRect, text); } if (inspectFrame != endTime) { var val = stream.GetValue(inspectFrame); if (val > 0) { var text = new GUIContent(m_LabelFunc(val)); var size = UnityEngine.GUI.skin.label.CalcSize(text); var x = GraphUtility.ValueToPixel(inspectFrame, startFrame, endTime, rect.width); float pixelVal = GraphUtility.ValueToPixel(val, 0, maxValue, rect.height); var labelRect = new Rect(rect.xMin + x + 5, Mathf.Max(rect.yMin, rect.yMax - (pixelVal + size.y)), size.x, size.y); UnityEngine.GUI.DrawTexture(labelRect, EditorGUIUtility.whiteTexture, ScaleMode.StretchToFill, true, 0, m_BgColor, 50, 5); EditorGUI.LabelField(labelRect, text, UnityEngine.GUI.skin.label); } } UnityEngine.GUI.color = prevCol; } }
private List <COMTRADEChannelData> GetAnalogChannelData(EventDataSet eventDataSet) { int sourceIndex; // Get COMTRADE channel information for each waveform to be output to the COMTRADE file IEnumerable <COMTRADEChannelData> waveformChannelData = eventDataSet.OutputChannels .Join(eventDataSet.DataGroup.DataSeries, channel => channel.SeriesID, series => series.SeriesInfo.ID, (channel, series) => new { OutputChannel = channel, DataSeries = series }) .Select(waveformChannel => new COMTRADEChannelData() { GroupOrder = 0, LoadOrder = waveformChannel.OutputChannel.LoadOrder, OriginalChannelIndex = int.TryParse(waveformChannel.DataSeries.SeriesInfo.SourceIndexes, out sourceIndex) ? sourceIndex : -1, Name = waveformChannel.OutputChannel.ChannelKey, Units = GetUnits(waveformChannel.OutputChannel.ChannelKey), Data = waveformChannel.DataSeries }); // Get COMTRADE channel information for each fault curve IEnumerable <COMTRADEChannelData> faultCurveChannelData = ToFaultCurves(eventDataSet.DataGroup, eventDataSet.Faults) .Select(tuple => new { Algorithm = tuple.Item1, DataSeries = tuple.Item2 }) .Select((faultCurve, i) => new COMTRADEChannelData() { GroupOrder = 1, LoadOrder = i, OriginalChannelIndex = -1, Name = faultCurve.Algorithm, Units = string.Empty, Data = faultCurve.DataSeries }); // Get COMTRADE channel information for each cycle data series to be output to the file IEnumerable <COMTRADEChannelData> cycleChannelData = GetCycleChannelData(eventDataSet.VICycleDataGroup, eventDataSet.OutputChannels); // Return all the analog channel data in one list return(waveformChannelData .Concat(faultCurveChannelData) .Concat(cycleChannelData) .OrderBy(channelData => channelData.GroupOrder) .ThenBy(channelData => channelData.LoadOrder) .ToList()); }
public override void Draw(EventDataSet dataSet, Rect rect, int startFrame, int frameCount, int inspectFrame, bool expanded, Material material, int maxValue) { if (dataSet == null) { return; } int endFrame = startFrame + frameCount; EventDataSetStream refStream = dataSet.GetStream(Stream); if (refStream != null) { foreach (GraphUtility.Segment s in GraphUtility.IterateSegments(refStream, startFrame, endFrame, IsContinuationOfSegment)) { if (s.data != 0) { float x = rect.xMin + GraphUtility.ValueToPixel(s.frameStart, startFrame, endFrame, rect.width); float w = (rect.xMin + GraphUtility.ValueToPixel(s.frameEnd, startFrame, endFrame, rect.width)) - x; EditorGUI.DrawRect(new Rect(x, rect.yMin, w, rect.height), GraphColor); } } } EventDataSetStream loadStream = dataSet.GetStream(m_LoadStatusStream); if (loadStream != null) { foreach (GraphUtility.Segment s in GraphUtility.IterateSegments(loadStream, startFrame, endFrame, IsContinuationOfSegment)) { if (s.data == 0) { float x = rect.xMin + GraphUtility.ValueToPixel(s.frameStart, startFrame, endFrame, rect.width); float w = (rect.xMin + GraphUtility.ValueToPixel(s.frameEnd, startFrame, endFrame, rect.width)) - x; EditorGUI.DrawRect(new Rect(x, rect.yMin, w, rect.height), m_LoadColor); } } } }
public override void Draw(EventDataSet dataSet, Rect rect, int startFrame, int frameCount, int inspectFrame, bool expanded, Material material, int maxValue) { if (dataSet == null) { return; } var endTime = startFrame + frameCount; var stream = dataSet.GetStream(Stream); if (stream != null) { for (int i = stream.samples.Count - 1; i >= 0; --i) { var frame = stream.samples[i].frame; if (frame < startFrame) { break; } EditorGUI.DrawRect(new Rect(rect.xMin + GraphUtility.ValueToPixel(frame, startFrame, endTime, rect.width), rect.yMin, 2, rect.height), stream.samples[i].data == 0 ? m_EndColor : GraphColor); } } }
public void EventDataPlayerSession_AddSample_SimpleRecordEventCase() { EventDataPlayerSession edps = new EventDataPlayerSession(); DiagnosticEvent evt1 = CreateNewGenericEvent(ResourceManager.DiagnosticEventType.AsyncOperationReferenceCount, 0, 1); DiagnosticEvent evt2 = CreateNewGenericEvent(ResourceManager.DiagnosticEventType.AsyncOperationCreate, 0, 2); DiagnosticEvent evt3 = CreateNewGenericEvent(ResourceManager.DiagnosticEventType.AsyncOperationReferenceCount, 1, 1); bool entryCreated = false; edps.AddSample(evt1, true, ref entryCreated); Assert.IsTrue(entryCreated, "Either a new entry was supposed to be created, but was not, or the value of entryCreated was not properly updated."); edps.AddSample(evt2, true, ref entryCreated); Assert.IsFalse(entryCreated, "evt2: Either a new entry wasn't supposed to be created, but was, or the value of entryCreated was not properly updated."); edps.AddSample(evt3, true, ref entryCreated); Assert.IsFalse(entryCreated, "evt3: Either a new entry wasn't supposed to be created for, but was, or the value of entryCreated was not properly updated."); Assert.AreEqual(new List <DiagnosticEvent> { evt1, evt2 }, edps.m_FrameEvents[0], "evt1 and evt2 were not properly added to m_FrameEvents"); Assert.AreEqual(2, edps.m_EventCountDataSet.GetStreamValue(0, 0), "Value of the stream for m_EventCountDataSet was not properly set."); Assert.AreEqual(new List <DiagnosticEvent> { evt3 }, edps.m_FrameEvents[1], "evt3 was not properly added to m_FrameEvents"); Assert.IsTrue(edps.m_DataSets.ContainsKey(evt1.ObjectId), "The corresponding EventDataSet for evt1-3 was not added to m_DataSets"); EventDataSet eds = null; bool edsFound = edps.m_DataSets.TryGetValue(evt1.ObjectId, out eds); Assert.IsTrue(edsFound); Assert.AreEqual(2, eds.GetStream((int)ResourceManager.DiagnosticEventType.AsyncOperationReferenceCount).samples.Count); Assert.AreEqual(1, eds.GetStream((int)ResourceManager.DiagnosticEventType.AsyncOperationCreate).samples.Count); }
public static global::System.Xml.Schema.XmlSchemaComplexType GetTypedTableSchema(global::System.Xml.Schema.XmlSchemaSet xs) { global::System.Xml.Schema.XmlSchemaComplexType type = new global::System.Xml.Schema.XmlSchemaComplexType(); global::System.Xml.Schema.XmlSchemaSequence sequence = new global::System.Xml.Schema.XmlSchemaSequence(); EventDataSet ds = new EventDataSet(); global::System.Xml.Schema.XmlSchemaAny any1 = new global::System.Xml.Schema.XmlSchemaAny(); any1.Namespace = "http://www.w3.org/2001/XMLSchema"; any1.MinOccurs = new decimal(0); any1.MaxOccurs = decimal.MaxValue; any1.ProcessContents = global::System.Xml.Schema.XmlSchemaContentProcessing.Lax; sequence.Items.Add(any1); global::System.Xml.Schema.XmlSchemaAny any2 = new global::System.Xml.Schema.XmlSchemaAny(); any2.Namespace = "urn:schemas-microsoft-com:xml-diffgram-v1"; any2.MinOccurs = new decimal(1); any2.ProcessContents = global::System.Xml.Schema.XmlSchemaContentProcessing.Lax; sequence.Items.Add(any2); global::System.Xml.Schema.XmlSchemaAttribute attribute1 = new global::System.Xml.Schema.XmlSchemaAttribute(); attribute1.Name = "namespace"; attribute1.FixedValue = ds.Namespace; type.Attributes.Add(attribute1); global::System.Xml.Schema.XmlSchemaAttribute attribute2 = new global::System.Xml.Schema.XmlSchemaAttribute(); attribute2.Name = "tableTypeName"; attribute2.FixedValue = "NoteDataTable"; type.Attributes.Add(attribute2); type.Particle = sequence; global::System.Xml.Schema.XmlSchema dsSchema = ds.GetSchemaSerializable(); if (xs.Contains(dsSchema.TargetNamespace)) { global::System.IO.MemoryStream s1 = new global::System.IO.MemoryStream(); global::System.IO.MemoryStream s2 = new global::System.IO.MemoryStream(); try { global::System.Xml.Schema.XmlSchema schema = null; dsSchema.Write(s1); for (global::System.Collections.IEnumerator schemas = xs.Schemas(dsSchema.TargetNamespace).GetEnumerator(); schemas.MoveNext();) { schema = ((global::System.Xml.Schema.XmlSchema)(schemas.Current)); s2.SetLength(0); schema.Write(s2); if ((s1.Length == s2.Length)) { s1.Position = 0; s2.Position = 0; for (; ((s1.Position != s1.Length) && (s1.ReadByte() == s2.ReadByte()));) { ; } if ((s1.Position == s1.Length)) { return(type); } } } } finally { if ((s1 != null)) { s1.Close(); } if ((s2 != null)) { s2.Close(); } } } xs.Add(dsSchema); return(type); }
/// <summary> /// Updates an event and saves it in the database /// </summary> /// <param name="userToken">The userToken of the user performing the request</param> /// <param name="sysParameter">The system parameter to be added</param> /// <returns>An integer whih is the id of the newly created user</returns> public int UpdateEvent(string userToken, EventDataSet sysParameter ) { int newId = -1; if (IsUserTokenValid(userToken)) { try { if (conn.State != System.Data.ConnectionState.Open) { conn.Open(); } SqlCommand cmd = conn.CreateCommand(); cmd.CommandType = System.Data.CommandType.StoredProcedure; cmd.CommandText = "spUpdateEvent"; var p2 = new SqlParameter[13]; for (int i = 0; i < 13; i++) p2[i] = new SqlParameter(); p2[0] = new SqlParameter("name", sysParameter.Event[0].Name); p2[1] = new SqlParameter("beginDate", DateTime.Parse(sysParameter.Event[0].BeginDate)); p2[2] = new SqlParameter("endDate", DateTime.Parse(sysParameter.Event[0].EndDate)); p2[3] = new SqlParameter("beginTime", sysParameter.Event[0].BeginTime); p2[4] = new SqlParameter("endTime", sysParameter.Event[0].EndTime); p2[5] = new SqlParameter("locationId", sysParameter.Event[0].LocationId); p2[6] = new SqlParameter("orgId", sysParameter.Event[0].OrganisationId); p2[7] = new SqlParameter("isRoutine", sysParameter.Event[0].isRoutine); p2[8] = new SqlParameter("active", sysParameter.Event[0].Active); p2[9] = new SqlParameter("updateUser", _userId); p2[10] = new SqlParameter("id",sysParameter.Event[0].Id); p2[11] = new SqlParameter("hasSession",sysParameter.Event[0].hasSession); p2[12] = new SqlParameter("comments", sysParameter.Event[0].Comments); cmd.Parameters.AddRange(p2); newId = int.Parse(cmd.ExecuteScalar().ToString()); if (conn.State != System.Data.ConnectionState.Closed) { conn.Close(); } //SetInterestsForEvent(newId, interests); } catch (Exception ex) { throw new OperationFailedException(ex.Message, ex); } finally { if (conn.State != System.Data.ConnectionState.Closed) { conn.Close(); } } } return newId; }
/// <summary> /// Returns the active events in the database /// </summary> /// <param name="userToken">The userToken of the user performing the request</param> /// <returns>An collection of inner variable which is an <see cref="SysParameterDataSet"/></returns> /*public EventDataSet GetActiveEvents(string userToken) { var retDataset = new EventDataSet(); if (IsUserTokenValid(userToken)) { try { if (conn.State != System.Data.ConnectionState.Open) { conn.Open(); } SqlCommand cmd = conn.CreateCommand(); cmd.CommandType = System.Data.CommandType.StoredProcedure; cmd.CommandText = "spGetActiveEvents"; SqlDataReader reader = cmd.ExecuteReader(); if (reader != null) { while (reader.Read()) { var sysParam = retDataset.Event.NewEventRow(); sysParam.Id = int.Parse(reader["Id"].ToString()); sysParam.Name = reader["Name"].ToString(); sysParam.BeginDate = DateTime.Parse(reader["BeginDate"].ToString()); sysParam.EndDate = DateTime.Parse(reader["EndDate"].ToString()); sysParam.BeginTime = DateTime.Parse(reader["BeginTime"].ToString()); sysParam.EndTime = DateTime.Parse(reader["EndTime"].ToString()); sysParam.VenueName = reader["VenueName"].ToString(); sysParam.OrganizerId = int.Parse(reader["OrganizerId"].ToString()); sysParam.OrganizerName = reader["OrganizerName"].ToString(); sysParam.VenueId = int.Parse(reader["VenueId"].ToString()); sysParam.MaxEntries = int.Parse(reader["MaxEntries"].ToString()); sysParam.HasExit = (bool)reader["HasExit"]; sysParam.Comments = reader["Comments"].ToString(); sysParam.Active = (bool)reader["Active"]; retDataset.Event.AddEventRow(sysParam); } reader.Close(); } } catch (Exception ex) { throw new OperationFailedException(ex.Message, ex); } finally { if (conn.State != System.Data.ConnectionState.Closed) { conn.Close(); } } } return retDataset; }*/ /// <summary> /// Returns all events in the database for the specified orgId /// </summary> /// <param name="userToken">The userToken of the user performing the request</param> /// <returns>An collection of inner variable which is an <see cref="SysParameterDataSet"/></returns> public EventDataSet GetEventsByOrgId(string userToken,int orgId) { var retDataset = new EventDataSet(); if (IsUserTokenValid(userToken)) { try { if (conn.State != System.Data.ConnectionState.Open) { conn.Open(); } SqlCommand cmd = conn.CreateCommand(); cmd.CommandType = System.Data.CommandType.StoredProcedure; cmd.CommandText = "spGetEventsByOrgId"; var p = new SqlParameter("orgId",orgId); cmd.Parameters.Add(p); SqlDataReader reader = cmd.ExecuteReader(); if (reader != null) { while (reader.Read()) { var sysParam = retDataset.Event.NewEventRow(); sysParam.Id = int.Parse(reader["Id"].ToString()); sysParam.Name = reader["Name"].ToString(); sysParam.BeginDate = DateTime.Parse(reader["BeginDate"].ToString()).ToLongDateString(); sysParam.EndDate = DateTime.Parse(reader["EndDate"].ToString()).ToLongDateString(); sysParam.BeginTime = TimeSpan.Parse(reader["BeginTime"].ToString()); sysParam.EndTime = TimeSpan.Parse(reader["EndTime"].ToString()); sysParam.Location = reader["Location"].ToString(); sysParam.LocationId = int.Parse(reader["LocationId"].ToString()); sysParam.OrganisationId = int.Parse(reader["OrganisationId"].ToString()); sysParam.isRoutine = bool.Parse(reader["isRoutine"].ToString()); sysParam.hasSession = bool.Parse(reader["hasSession"].ToString()); sysParam.Active = (bool)reader["Active"]; sysParam.Comments = reader["Comments"].ToString(); retDataset.Event.AddEventRow(sysParam); } reader.Close(); } } catch (Exception ex) { throw new OperationFailedException(ex.Message, ex); } finally { if (conn.State != System.Data.ConnectionState.Closed) { conn.Close(); } } } return retDataset; }
private void WriteResults(EventDataSet eventDataSet, Parser originalFileParser) { // Assume the data file path is the same as the results file path // and determine the path to the header and schema files string directory = FilePath.GetDirectoryName(eventDataSet.ResultsPath); string rootFileName = FilePath.GetFileNameWithoutExtension(eventDataSet.ResultsPath); string headerFilePath = Path.Combine(directory, rootFileName + ".hdr"); string schemaFilePath = Path.Combine(directory, rootFileName + ".cfg"); string dataFilePath = eventDataSet.ResultsPath; Schema schema; // Get structures containing the data to be written to the results files COMTRADEData comtradeData = new COMTRADEData(); // If there are no waveforms to be written to the file, give up if (!eventDataSet.OutputChannels.Any()) return; comtradeData.StationName = eventDataSet.MeterDataSet.Meter.Name; comtradeData.DeviceID = eventDataSet.MeterDataSet.Meter.AssetKey; comtradeData.DataStartTime = eventDataSet.DataGroup.StartTime; comtradeData.SampleCount = eventDataSet.DataGroup.Samples; comtradeData.SamplingRate = eventDataSet.DataGroup.Samples / (eventDataSet.DataGroup.EndTime - eventDataSet.DataGroup.StartTime).TotalSeconds; comtradeData.AnalogChannelData = GetAnalogChannelData(eventDataSet); comtradeData.DigitalChannelData = GetDigitalChannelData(eventDataSet); // If the original file is available, use data from the original file // in order to update the data to be written to the results files if ((object)originalFileParser != null) FixCOMTRADEData(comtradeData, originalFileParser, eventDataSet.TimeZoneOffset); // Write data to the header file WriteHeaderFile(eventDataSet, headerFilePath); // Write data to the schema file schema = WriteSchemaFile(comtradeData, schemaFilePath); // Write data to the data file WriteDataFile(comtradeData, schema, dataFilePath); }
private void WriteResults(EventDataSet eventDataSet) { const StringComparison IgnoreCase = StringComparison.OrdinalIgnoreCase; // Get the path to the original data file string dataFilePath; string directory; string rootFileName; string schemaFilePath; Parser originalFileParser = null; dataFilePath = eventDataSet.MeterDataSet.FileGroup.DataFiles .Select(dataFile => dataFile.FilePath) .FirstOrDefault(path => path.EndsWith(".dat", IgnoreCase) || path.EndsWith(".d00", IgnoreCase)); if (File.Exists(dataFilePath)) { // Get the path to the original schema file directory = FilePath.GetDirectoryName(dataFilePath); rootFileName = FilePath.GetFileNameWithoutExtension(dataFilePath); schemaFilePath = Path.Combine(directory, rootFileName + ".cfg"); if (File.Exists(schemaFilePath)) { // Create a parser to parse the original COMTRADE files originalFileParser = new Parser() { FileName = dataFilePath, InferTimeFromSampleRates = true, Schema = new Schema(schemaFilePath) }; } } using (originalFileParser) { if ((object)originalFileParser != null) originalFileParser.OpenFiles(); // Write results to the COMTRADE fault record using the parser WriteResults(eventDataSet, originalFileParser); } }
private void WriteHeaderFile(EventDataSet eventDataSet, string headerFilePath) { // Date-time format used in the header file const string DateTimeFormat = "yyyy-MM-dd HH:mm:ss.ffffff"; string lineName = eventDataSet.MeterDataSet.Meter.MeterLines .Where(ml => ml.LineID == eventDataSet.DataGroup.Line.ID) .Select(ml => ml.LineName) .FirstOrDefault() ?? eventDataSet.DataGroup.Line.AssetKey; using (FileStream stream = File.Create(FilePath.GetAbsolutePath(headerFilePath))) using (StreamWriter writer = new StreamWriter(stream, Encoding.ASCII)) { // Write out the original list of files containing // the data used to generate this fault record writer.WriteLine("Disturbance files:"); foreach (DataFile dataFile in eventDataSet.MeterDataSet.FileGroup.DataFiles) writer.WriteLine(dataFile.FilePath); writer.WriteLine(); // Write the meter name to the header file writer.WriteLine("Meter: " + eventDataSet.MeterDataSet.Meter.Name); // Write out the name and length of the line on which the fault(s) occurred writer.WriteLine("Line: {0} ({1} {2})", lineName, eventDataSet.DataGroup.Line.Length, LengthUnits); writer.WriteLine(); // For each fault, write the distance, the most prominent fault type, the time of // inception, the time of clearing, and the duration of the fault to the header file for (int i = 0; i < eventDataSet.Faults.Count; i++) { int faultNumber = i + 1; Fault fault = eventDataSet.Faults[i]; if (fault.IsSuppressed || fault.Summaries.All(summary => !summary.IsValid)) continue; DateTime startTime = fault.InceptionTime; DateTime endTime = fault.ClearingTime; int startSample = fault.StartSample; int endSample = fault.EndSample; double duration = fault.Duration.TotalSeconds; double distance = fault.Summaries .Where(summary => summary.IsSelectedAlgorithm) .Select(summary => summary.Distance) .DefaultIfEmpty(double.NaN) .First(); writer.WriteLine("Fault {0}:", faultNumber); writer.WriteLine("[{0}] Fault distance: {1:0.00} {2}", faultNumber, distance, LengthUnits); writer.WriteLine("[{0}] Prominent fault type: {1}", faultNumber, fault.Type); writer.WriteLine("[{0}] Fault inception: {1} (sample #{2})", faultNumber, startTime.ToString(DateTimeFormat), startSample); writer.WriteLine("[{0}] Fault clearing: {1} (sample #{2})", faultNumber, endTime.ToString(DateTimeFormat), endSample); writer.WriteLine("[{0}] Fault duration: {1:0.0000} seconds ({2:0.00} cycles)", faultNumber, duration, duration * m_systemFrequency); writer.WriteLine(); } } }
private List<COMTRADEChannelData> GetDigitalChannelData(EventDataSet eventDataSet) { // Get an arbitrary data series from the collection of waveforms so // that we can use it to determine the timestamp of each data point DataSeries series = eventDataSet.DataGroup[0]; // Create the function to convert a name and an index to a COMTRADEChannelData Func<string, int, COMTRADEChannelData> toChannelData = (name, index) => new COMTRADEChannelData() { GroupOrder = 0, LoadOrder = index, OriginalChannelIndex = index, Name = name, Data = series.Multiply(0.0D) }; // Get the collection of COMTRADEChannelData for the fault-related digitals List<COMTRADEChannelData> digitalChannelData = new string[] { "Fault Detected" } .Concat(GetAllFaultTypes().Select(faultType => string.Format("{0} Fault Type", faultType))) .Select(toChannelData) .ToList(); // Populate the data points for each digital channel // based on the fault type of each segment of fault data foreach (Fault.Segment segment in eventDataSet.Faults.SelectMany(fault => fault.Segments)) { // Get the fault type of the segment FaultType faultType = segment.FaultType; // Get the value of each digital in this segment bool[] digitals = { faultType != FaultType.None, faultType == FaultType.AN, faultType == FaultType.BN, faultType == FaultType.CN, faultType == FaultType.AB, faultType == FaultType.BC, faultType == FaultType.CA, faultType == FaultType.ABG, faultType == FaultType.BCG, faultType == FaultType.CAG, faultType == FaultType.ABC }; // Populate the data points for this segment with the proper values based on fault type for (int i = 0; i < digitalChannelData.Count; i++) { double value = Convert.ToDouble(digitals[i]); for (int j = segment.StartSample; j <= segment.EndSample; j++) digitalChannelData[i].Data.DataPoints[j].Value = value; } } return digitalChannelData; }
private List<COMTRADEChannelData> GetAnalogChannelData(EventDataSet eventDataSet) { int sourceIndex; // Get COMTRADE channel information for each waveform to be output to the COMTRADE file IEnumerable<COMTRADEChannelData> waveformChannelData = eventDataSet.OutputChannels .Join(eventDataSet.DataGroup.DataSeries, channel => channel.SeriesID, series => series.SeriesInfo.ID, (channel, series) => new { OutputChannel = channel, DataSeries = series }) .Select(waveformChannel => new COMTRADEChannelData() { GroupOrder = 0, LoadOrder = waveformChannel.OutputChannel.LoadOrder, OriginalChannelIndex = int.TryParse(waveformChannel.DataSeries.SeriesInfo.SourceIndexes, out sourceIndex) ? sourceIndex : -1, Name = waveformChannel.OutputChannel.ChannelKey, Units = GetUnits(waveformChannel.OutputChannel.ChannelKey), Data = waveformChannel.DataSeries }); // Get COMTRADE channel information for each fault curve IEnumerable<COMTRADEChannelData> faultCurveChannelData = ToFaultCurves(eventDataSet.DataGroup, eventDataSet.Faults) .Select(tuple => new { Algorithm = tuple.Item1, DataSeries = tuple.Item2 }) .Select((faultCurve, i) => new COMTRADEChannelData() { GroupOrder = 1, LoadOrder = i, OriginalChannelIndex = -1, Name = faultCurve.Algorithm, Units = string.Empty, Data = faultCurve.DataSeries }); // Get COMTRADE channel information for each cycle data series to be output to the file IEnumerable<COMTRADEChannelData> cycleChannelData = GetCycleChannelData(eventDataSet.VICycleDataGroup, eventDataSet.OutputChannels); // Return all the analog channel data in one list return waveformChannelData .Concat(faultCurveChannelData) .Concat(cycleChannelData) .OrderBy(channelData => channelData.GroupOrder) .ThenBy(channelData => channelData.LoadOrder) .ToList(); }
public void WriteResults(DbAdapterContainer dbAdapterContainer, MeterDataSet meterDataSet) { CycleDataResource cycleDataResource; FaultDataResource faultDataResource; DataGroup dataGroup; FaultGroup faultGroup; List<int> seriesIDs; EventDataSet eventDataSet; string rootFileName; string fileName; cycleDataResource = meterDataSet.GetResource(() => CycleDataResource.GetResource(meterDataSet, dbAdapterContainer)); faultDataResource = meterDataSet.GetResource(() => new FaultDataResource(dbAdapterContainer)); if (!Directory.Exists(m_resultsPath)) Directory.CreateDirectory(m_resultsPath); for (int i = 0; i < cycleDataResource.DataGroups.Count; i++) { dataGroup = cycleDataResource.DataGroups[i]; if (faultDataResource.FaultLookup.TryGetValue(dataGroup, out faultGroup)) { rootFileName = FilePath.GetFileNameWithoutExtension(meterDataSet.FilePath); fileName = string.Format("{0},{1:000},Line{2}.dat", rootFileName, i, dataGroup.Line.AssetKey); seriesIDs = dataGroup.DataSeries .Select(series => series.SeriesInfo.ID) .ToList(); eventDataSet = new EventDataSet() { ResultsPath = Path.Combine(m_resultsPath, fileName), MeterDataSet = meterDataSet, TimeZoneOffset = GetTimeZoneOffset(meterDataSet.Meter.TimeZone, dataGroup.StartTime), DataGroup = dataGroup, VICycleDataGroup = cycleDataResource.VICycleDataGroups[i], Faults = faultGroup.Faults, OutputChannels = dbAdapterContainer.GetAdapter<FaultLocationInfoDataContext>().OutputChannels.Where(channel => seriesIDs.Contains(channel.SeriesID)).ToList() }; WriteResults(eventDataSet); } } }
protected void btnSaveEvent_OnClick(object sender, EventArgs e) { TimeSpan add = new TimeSpan(0, 23, 59, 59); DateTime _beginDate = DateTime.Parse(dateBegin.Text).Date; DateTime _endDate; if (chkRoutine.Checked) { _endDate = DateTime.Parse("9999-12-31").Add(add); } else { _endDate = DateTime.Parse(dateEnd.Text).Add(add); } TimeSpan _beginTime = DateTime.Parse(timeBegin.Text).TimeOfDay; TimeSpan _endTime = DateTime.Parse(timeEnd.Text).TimeOfDay; var eventDS = new EventDataSet(); try { eventDS.Event.AddEventRow(Utilities.companyId, txtName.Text, _beginDate.ToString(), _endDate.ToString(), _beginTime, _endTime, int.Parse(cbLocations.SelectedValue), chkActive.Checked, chkRoutine.Checked, cbLocations.SelectedItem.ToString(), Utilities.editId, chkHasSessions.Checked,txtDesc.Text); } catch (Exception ex) { SetToast("Error","Check form data."); DisplayEventsInGrid(); return; } if (Utilities.editId == -1) { int result = dataProvider.AddEvent(Utilities.userToken, eventDS); if (result != -1) { Utilities.editId = -1; SetToast("success","Event Created succesfully."); btnCloseModal_OnClick(sender, e); } else { SetToast("error", "Event exists already."); return; } } else { int result = dataProvider.UpdateEvent(Utilities.userToken, eventDS); if (result != -1) { SetToast("success","Event updated succesfully"); btnCloseModal_OnClick(sender,e); Utilities.editId = -1; } else { SetToast("info","Event exists already"); return; } DisplayEventsInGrid(); } DisplayEventsInGrid(); // var eventDS2 = new EventDataSet(); // eventDS2.Event.AddEventRow(Utilities.companyId, txtName.Text, _beginDate, _endDate, _beginTime, // _endTime, // int.Parse(cbLocations.SelectedValue), chkActive.Checked, chkRoutine.Checked, // cbLocations.SelectedItem.ToString(), Utilities.editId,chkHasSessions.Checked); // // Session["eventId"] = Utilities.editId; // Session["eventName"] = txtName.Text; // TimeSpan sub = new TimeSpan(0,0,0,1); // Session["timeBeginCheck"] = _beginTime.Subtract(sub); // Session["timeEndCheck"] = _endTime; // Session["hasSession"] = chkHasSessions.Checked; // Session["eventParams"] = eventDS2; // Utilities.pageName = "btnManageEvents"; // //Utilities.editId = -1; // Response.Redirect("/Organisations/EventCategories.aspx"); }