Example #1
0
        public static SummaryType GetRaceTagCalcType(int nType)
        {
            SummaryType st = SummaryType.asAverage;

            switch (nType)
            {
            case 1:
                st = SummaryType.asMaximum;
                break;

            case 2:
                st = SummaryType.asMinimum;
                break;

            case 3:
                st = SummaryType.asAverage;
                break;

            default:
                st = SummaryType.asAverage;
                break;
            }

            return(st);
        }
Example #2
0
        public override Task WriteToStreamAsync(Type type, object value, Stream writeStream, HttpContent content, TransportContext transportContext)
        {
            XmlWriter   writer  = new XmlTextWriter(writeStream, new UTF8Encoding(false));
            SummaryType summary = requestMessage.RequestSummary();

            if (type == typeof(OperationOutcome))
            {
                Resource resource = (Resource)value;
                _serializer.Serialize(resource, writer, summary);
            }
            else if (typeof(Resource).IsAssignableFrom(type))
            {
                Resource resource = (Resource)value;
                _serializer.Serialize(resource, writer, summary);
            }
            else if (type == typeof(FhirResponse))
            {
                FhirResponse response = (value as FhirResponse);
                if (response.HasBody)
                {
                    _serializer.Serialize(response.Resource, writer, summary);
                }
            }

            writer.Flush();
            return(Task.CompletedTask);
        }
Example #3
0
        [InlineData("http://example.org/fhir/Patient?_summary=", SummaryType.False)]        // _summary=      is SummaryType.False
        public void RequestSummary_SummaryTypeDefaultIsFalse(string url, SummaryType expected)
        {
            var request = new HttpRequestMessage(HttpMethod.Get, url);
            var actual  = request.RequestSummary();

            Assert.Equal(expected, actual);
        }
Example #4
0
        public override Tasks.Task WriteToStreamAsync(Type type, object value, Stream writeStream, HttpContent content, TransportContext transportContext)
        {
            using (StreamWriter streamwriter = new StreamWriter(writeStream))
                using (JsonWriter writer = new JsonTextWriter(streamwriter))
                {
                    SummaryType summary = requestMessage.RequestSummary();

                    if (type == typeof(OperationOutcome))
                    {
                        Resource resource = (Resource)value;
                        _serializer.Serialize(resource, writer, summary);
                    }
                    else if (typeof(Resource).IsAssignableFrom(type))
                    {
                        Resource resource = (Resource)value;
                        _serializer.Serialize(resource, writer, summary);
                    }
                    else if (typeof(FhirResponse).IsAssignableFrom(type))
                    {
                        FhirResponse response = (value as FhirResponse);
                        if (response.HasBody)
                        {
                            _serializer.Serialize(response.Resource, writer, summary);
                        }
                    }
                }

            return(Tasks.Task.CompletedTask);
        }
Example #5
0
        internal ITaskSummary CreateTaskSummary(SummaryType summaryType, bool scheduled)
        {
            switch (summaryType)
            {
            case SummaryType.Text:
                return(new StringTaskSummary("{0}{1} = {2} s".FormatInvariant(
                                                 scheduled ? "Scheduled: " : string.Empty,
                                                 string.Join(" + ", this.Durations.Select(d => d.DurationInSeconds)),
                                                 this.Durations.Sum(d => d.DurationInSeconds))));

            case SummaryType.Dictionary:
                DictionaryTaskSummary dictionary = new DictionaryTaskSummary();

                if (scheduled)
                {
                    dictionary.Add("Scheduled", scheduled.ToString());
                }

                for (int i = 0; i < this.Durations.Length; i++)
                {
                    dictionary.Add("Duration " + i, "{0} s".FormatInvariant(this.Durations[i].DurationInSeconds));
                }

                return(dictionary);

            default:
                throw new NotSupportedException <SummaryType>(summaryType);
            }
        }
Example #6
0
        public override System.Threading.Tasks.Task WriteToStreamAsync(Type type, object value, Stream writeStream, HttpContent content, TransportContext transportContext)
        {
            XmlWriter writer = new XmlTextWriter(writeStream, Encoding.UTF8);

            if (type == typeof(OperationOutcome))
            {
                Resource resource = (Resource)value;
                FhirSerializer.SerializeResource(resource, writer);
            }
            else if (typeof(Resource).IsAssignableFrom(type))
            {
                if (value != null)
                {
                    Resource    r  = value as Resource;
                    SummaryType st = SummaryType.False;
                    if (r.HasAnnotation <SummaryType>())
                    {
                        st = r.Annotation <SummaryType>();
                    }
                    FhirSerializer.SerializeResource(r, writer, st);
                }
            }

            writer.Flush();

            return(System.Threading.Tasks.Task.FromResult(false));
            // return System.Threading.Tasks.Task.CompletedTask;
        }
Example #7
0
        public SensorTemplate(string unit, float upperLimit, float lowerLimit, float maxRateOfChange, MatchStyle matchStyle, string pattern, SummaryType sType)
        {
            if (String.IsNullOrWhiteSpace(unit))
            {
                throw new ArgumentException("You must a non-blank default unit.");
            }

            if (pattern == null)
            {
                throw new ArgumentException("The pattern to match a sensor on cannot be blank.");
            }

            if (lowerLimit > upperLimit)
            {
                throw new ArgumentOutOfRangeException(
                          "The lower limit must be less than the upper limit for this preset.");
            }

            _unit            = unit;
            _upperLimit      = upperLimit;
            _lowerLimit      = lowerLimit;
            _maxRateOfChange = maxRateOfChange;
            _sType           = sType;

            _matchStyle = matchStyle;
            _pattern    = pattern;
        }
Example #8
0
        protected static ITypedElement MakeElementStack(Base instance, SummaryType summary)
        {
            if (summary == SummaryType.False)
            {
                return(instance.ToTypedElement());
            }

            var patchedInstance = (Base)instance.DeepCopy();

            MetaSubsettedAdder.AddSubsetted(patchedInstance, atRoot: true);

            var baseNav = new ScopedNode(patchedInstance.ToTypedElement());

            switch (summary)
            {
            case SummaryType.True:
                return(MaskingNode.ForSummary(baseNav));

            case SummaryType.Text:
                return(MaskingNode.ForText(baseNav));

            case SummaryType.Data:
                return(MaskingNode.ForData(baseNav));

            case SummaryType.Count:
                return(MaskingNode.ForCount(baseNav));

            default:
                return(baseNav);
            }
        }
        public override async System.Threading.Tasks.Task WriteResponseBodyAsync(OutputFormatterWriteContext context)
        {
            using (StringWriter strWriter = new StringWriter())
                using (JsonWriter writer = new JsonTextWriter(strWriter))
                {
                    SummaryType summary = SummaryType.False;//;requestMessage.RequestSummary();

                    Type type = context.Object.GetType();
                    if (type == typeof(OperationOutcome))
                    {
                        Resource resource = context.Object as Resource;
                        jsonSerializer.Serialize(resource, writer, summary);
                    }
                    else if (typeof(Resource).IsAssignableFrom(type))
                    {
                        Resource resource = context.Object as Resource;
                        jsonSerializer.Serialize(resource, writer, summary);
                    }
                    else if (typeof(ServerFhirResponse).IsAssignableFrom(type))
                    {
                        ServerFhirResponse fhirResponse = (context.Object as ServerFhirResponse);
                        if (fhirResponse.HasBody)
                        {
                            jsonSerializer.Serialize(fhirResponse.Resource, writer, summary);
                        }
                    }

                    HttpResponse response = context.HttpContext.Response;
                    await response.WriteAsync(strWriter.ToString());
                }
        }
Example #10
0
        public override Task WriteToStreamAsync(Type type, object value, Stream writeStream, HttpContent content, TransportContext transportContext)
        {
            return(Task.Factory.StartNew(() =>
            {
                XmlWriter writer = new XmlTextWriter(writeStream, new UTF8Encoding(false));
                SummaryType summary = requestMessage.RequestSummary();

                if (type == typeof(OperationOutcome))
                {
                    Resource resource = (Resource)value;
                    FhirSerializer.SerializeResource(resource, writer, summary);
                }
                else if (typeof(Resource).IsAssignableFrom(type))
                {
                    Resource resource = (Resource)value;
                    FhirSerializer.SerializeResource(resource, writer, summary);

                    content.Headers.ContentLocation = resource.ExtractKey().ToUri();
                }
                else if (type == typeof(FhirResponse))
                {
                    FhirResponse response = (value as FhirResponse);
                    if (response.HasBody)
                    {
                        FhirSerializer.SerializeResource(response.Resource, writer, summary);
                    }
                }

                writer.Flush();
            }));
        }
Example #11
0
        public override System.Threading.Tasks.Task WriteToStreamAsync(Type type, object value, Stream writeStream, HttpContent content, TransportContext transportContext)
        {
            StreamWriter writer     = new StreamWriter(writeStream);
            JsonWriter   jsonwriter = SerializationUtil.CreateJsonTextWriter(writer); // This will use the BetterJsonWriter which handles precision correctly

            if (type == typeof(OperationOutcome))
            {
                Resource resource = (Resource)value;
                FhirSerializer.SerializeResource(resource, jsonwriter);
            }
            else if (typeof(Resource).IsAssignableFrom(type))
            {
                if (value != null)
                {
                    Resource    r  = value as Resource;
                    SummaryType st = SummaryType.False;
                    if (r.HasAnnotation <SummaryType>())
                    {
                        st = r.Annotation <SummaryType>();
                    }
                    FhirSerializer.SerializeResource(r, jsonwriter, st);
                }
            }
            writer.Flush();
            return(System.Threading.Tasks.Task.FromResult(false));
            // return System.Threading.Tasks.Task.CompletedTask;
        }
        private string SerializeResponse(Resource fhirResource, string responseType, SummaryType st)
        {
            string rv = string.Empty;

            OutgoingWebResponseContext context = WebOperationContext.Current.OutgoingResponse;

            if (responseType == "json")
            {
                FhirJsonSerializer fjs = new FhirJsonSerializer();
                rv = fjs.SerializeToString(fhirResource, st);
                //rv = FhirSerializer.SerializeResourceToJson(fhirResource,st);
                //context.ContentType = "application/json";
                context.ContentType = "application/fhir+json;charset=UTF-8"; // when IANA registered
                context.Format      = WebMessageFormat.Json;
            }
            else
            {
                FhirXmlSerializer fxs = new FhirXmlSerializer();
                rv = fxs.SerializeToString(fhirResource, st);
                //rv = FhirSerializer.SerializeResourceToXml(fhirResource,st);
                //context.ContentType = "application/xml";
                context.ContentType = "application/fhir+xml;charset=UTF-8"; // when IANA registered
                context.Format      = WebMessageFormat.Xml;
            }

            return(rv);
        }
Example #13
0
        public CapabilityStatement GetConformance(ModelBaseInputs request, SummaryType summary)
        {
            CapabilityStatement con = new CapabilityStatement
            {
                Url           = request.BaseUri + "metadata",
                Description   = new Markdown("CDR based FHIR server"),
                DateElement   = new Hl7.Fhir.Model.FhirDateTime("2017-04-30"),
                Version       = "1.0.0.0",
                Name          = "CDR FHIR API",
                Experimental  = true,
                Status        = PublicationStatus.Active,
                FhirVersion   = Hl7.Fhir.Model.ModelInfo.Version,
                AcceptUnknown = CapabilityStatement.UnknownContentCode.Extensions,
                Format        = new string[] { "xml", "json" },
                Kind          = CapabilityStatement.CapabilityStatementKind.Instance,
                Meta          = new Meta()
            };

            con.Meta.LastUpdatedElement = Instant.Now();

            con.Rest = new List <CapabilityStatement.RestComponent>()
            {
                new CapabilityStatement.RestComponent
                {
                    Mode      = CapabilityStatement.RestfulCapabilityMode.Server,
                    Resource  = new List <CapabilityStatement.ResourceComponent>(),
                    Operation = new List <CapabilityStatement.OperationComponent>(),
                    Security  = new CapabilityStatement.SecurityComponent
                    {
                        Extension = new List <Extension>()
                        {
                            new Extension()
                            {
                                Url       = "http://fhir-registry.smarthealthit.org/StructureDefinition/oauth-uris",
                                Extension = new List <Extension>()
                                {
                                    new Extension
                                    {
                                        Url   = "token",
                                        Value = new FhirString("https://teams-fhir-auth.dapasoft.com/connect/token")
                                    },
                                    new Extension
                                    {
                                        Url   = "authorize",
                                        Value = new FhirString("https://teams-fhir-auth.dapasoft.com/connect/authorize")
                                    }
                                }
                            }
                        }
                    }
                }
            };
            //foreach (var model in ModelFactory.GetAllModels(GetInputs(buri)))
            //{
            //    con.Rest[0].Resource.Add(model.GetRestResourceComponent());
            //}

            return(con);
        }
Example #14
0
        public static string SummaryUser(SummaryType fromType, Int32 userId = 0, Int32 idCommunity = 0)
        {
            string mybaseurl = String.Format(_SummaryUser, fromType.ToString());

            mybaseurl += (userId == 0) ? "" : "&" + String.Format(_ParamUser, userId);
            mybaseurl += (idCommunity == 0) ? "" : "&" + String.Format(_ParamCmnt, idCommunity);
            return(mybaseurl);
        }
Example #15
0
 public static void AddGridSummary(UltraGrid grid, SummaryType st, string strFormat, int icol)
 {
     //添加汇总
     grid.DisplayLayout.Bands[0].Summaries.Add(
         st,
         grid.DisplayLayout.Bands[0].Columns[icol]);
     grid.DisplayLayout.Bands[0].Summaries[icol].DisplayFormat = strFormat;
 }
Example #16
0
        public static void AddGridSummary(UltraGrid grid, SummaryType st, string strFormat, string strColName)
        {
            //添加汇总
            SummarySettings summary = grid.DisplayLayout.Bands[0].Summaries.Add(
                st,
                grid.DisplayLayout.Bands[0].Columns[strColName]);

            summary.DisplayFormat = strFormat;
        }
        public override System.Threading.Tasks.Task WriteResponseBodyAsync(OutputFormatterWriteContext context, Encoding selectedEncoding)
        {
            //try
            //{
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }
            if (selectedEncoding == null)
            {
                throw new ArgumentNullException(nameof(selectedEncoding));
            }

            if (selectedEncoding != Encoding.UTF8)
            {
                //throw Error.BadRequest($"FHIR supports UTF-8 encoding exclusively, not {selectedEncoding.WebName}");
                throw new InterneuronBusinessException((short)HttpStatusCode.BadRequest, $"FHIR supports UTF-8 encoding exclusively, not {selectedEncoding.WebName}");
            }

            using (TextWriter writer = context.WriterFactory(context.HttpContext.Response.Body, selectedEncoding))
                using (XmlWriter xmlWriter = new XmlTextWriter(writer))
                {
                    if (!(context.HttpContext.RequestServices.GetService(typeof(FhirXmlSerializer)) is FhirXmlSerializer serializer))
                    {
                        //throw Error.Internal($"Missing required dependency '{nameof(FhirXmlSerializer)}'");
                        throw new InterneuronBusinessException((short)HttpStatusCode.InternalServerError, $"Missing required dependency '{nameof(FhirJsonSerializer)}'");
                    }


                    SummaryType summaryType = context.HttpContext.Request.RequestSummary();
                    if (typeof(FhirResponse).IsAssignableFrom(context.ObjectType))
                    {
                        FhirResponse response = context.Object as FhirResponse;
                        context.HttpContext.Response.StatusCode = (int)response.StatusCode;
                        if (response.Resource != null)
                        {
                            serializer.Serialize(response.Resource, xmlWriter, summaryType);
                        }
                    }
                    else if (context.ObjectType == typeof(OperationOutcome) || typeof(Resource).IsAssignableFrom(context.ObjectType))
                    {
                        if (context.Object != null)
                        {
                            serializer.Serialize(context.Object as Resource, xmlWriter, summaryType);
                        }
                    }
                }

            return(System.Threading.Tasks.Task.CompletedTask);
            //}
            //catch(Exception ex)
            //{
            //    var x = ex;
            //    return System.Threading.Tasks.Task.CompletedTask;

            //}
        }
 public MarkerSummaryEntry(string name, float msAtMedian, float msMedian, float x, float w, int medianFrameIndex, SummaryType summaryType)
 {
     this.name             = name;
     this.msAtMedian       = msAtMedian;
     this.msMedian         = msMedian;
     this.x                = x;
     this.w                = w;
     this.medianFrameIndex = medianFrameIndex;
     this.summaryType      = summaryType;
 }
        public override Task WriteResponseBodyAsync(OutputFormatterWriteContext context, Encoding selectedEncoding)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }
            if (selectedEncoding == null)
            {
                throw new ArgumentNullException(nameof(selectedEncoding));
            }
            if (selectedEncoding != Encoding.UTF8)
            {
                throw Error.BadRequest($"FHIR supports UTF-8 encoding exclusively, not {selectedEncoding.WebName}");
            }

            context.HttpContext.AllowSynchronousIO();

            using (TextWriter writer = context.WriterFactory(context.HttpContext.Response.Body, selectedEncoding))
                using (XmlWriter xmlWriter = new XmlTextWriter(writer))
                {
                    if (!(context.HttpContext.RequestServices.GetService(typeof(FhirXmlSerializer)) is FhirXmlSerializer serializer))
                    {
                        throw Error.Internal($"Missing required dependency '{nameof(FhirXmlSerializer)}'");
                    }

                    SummaryType summaryType = context.HttpContext.Request.RequestSummary();
                    if (typeof(FhirResponse).IsAssignableFrom(context.ObjectType))
                    {
                        FhirResponse response = context.Object as FhirResponse;

                        context.HttpContext.Response.AcquireHeaders(response);
                        context.HttpContext.Response.StatusCode = (int)response.StatusCode;

                        if (response.Resource != null)
                        {
                            serializer.Serialize(response.Resource, xmlWriter, summaryType);
                        }
                    }
                    else if (context.ObjectType == typeof(OperationOutcome) || typeof(Resource).IsAssignableFrom(context.ObjectType))
                    {
                        if (context.Object != null)
                        {
                            serializer.Serialize(context.Object as Resource, xmlWriter, summaryType);
                        }
                    }
                    else if (context.Object is ValidationProblemDetails validationProblems)
                    {
                        OperationOutcome outcome = new OperationOutcome();
                        outcome.AddValidationProblems(context.HttpContext.GetResourceType(), (HttpStatusCode)context.HttpContext.Response.StatusCode, validationProblems);
                        serializer.Serialize(outcome, xmlWriter, summaryType);
                    }
                }

            return(Task.CompletedTask);
        }
Example #20
0
        public static (string, string, double, SummaryType) Parse(string[] args)
        {
            string      inputFile      = FuzzySetParser.DefaultPath;
            string      outputFile     = SummaryResultWriter.DefaultPath;
            double      T1_THRESHOLD   = 0.1;
            SummaryType typeToGenerate = SummaryType.First;

            CommandLineParam currentOption = CommandLineParam.None;

            foreach (string param in args)
            {
                switch (param)
                {
                case "-i":
                    currentOption = CommandLineParam.InputFile;
                    break;

                case "-o":
                    currentOption = CommandLineParam.OutputFile;
                    break;

                case "-t":
                    currentOption = CommandLineParam.SummaryType;
                    break;

                case "-d":
                    currentOption = CommandLineParam.Threshold;
                    break;

                default:
                    switch (currentOption)
                    {
                    case CommandLineParam.InputFile:
                        inputFile = param;
                        break;

                    case CommandLineParam.OutputFile:
                        outputFile = param;
                        break;

                    case CommandLineParam.SummaryType:
                        typeToGenerate = param.StartsWith("f") ? SummaryType.First : SummaryType.Second;
                        break;

                    case CommandLineParam.Threshold:
                        T1_THRESHOLD = Double.Parse(param, CultureInfo.InvariantCulture);
                        break;
                    }
                    currentOption = CommandLineParam.None;
                    break;
                }
            }

            return(inputFile, outputFile, T1_THRESHOLD, typeToGenerate);
        }
Example #21
0
 public static byte[] SerializeToXmlBytes(Base instance, SummaryType summary = SummaryType.False, string root = null)
 {
     // [WMR 20160421] Explicit disposal
     return(xmlWriterToBytes(xw => {
         using (var writer = new XmlFhirWriter(xw))
         {
             Serialize(instance, writer, summary, root);
             xw.Flush();
         }
     }));
 }
Example #22
0
 public static string SerializeToXml(Base data, SummaryType summary = SummaryType.False, string root = null)
 {
     // [WMR 20160421] Explicit disposal
     return(xmlWriterToString(xw => {
         using (var writer = new XmlFhirWriter(xw))
         {
             Serialize(data, writer, summary, root);
             xw.Flush();
         }
     }));
 }
Example #23
0
 // [WMR 20180409] NEW
 // https://github.com/ewoutkramer/fhir-net-api/issues/545
 public JObject SerializeToDocument(Base instance, SummaryType summary = SummaryType.False)
 {
     return(jsonWriterToDocument(jw =>
     {
         using (var writer = new JsonDomFhirWriter(jw))
         {
             Serialize(instance, writer, summary, null);
             jw.Flush();
         }
     }));
 }
Example #24
0
 // [WMR 20160421] Caller is responsible for disposing writer
 internal protected void Serialize(Base instance, IFhirWriter writer, SummaryType summary = SummaryType.False, string root = null)
 {
     if (instance is Resource resource)
     {
         new ResourceWriter(writer, Settings).Serialize(resource, summary);
     }
     else
     {
         new ComplexTypeWriter(writer, Settings).Serialize(instance, summary, root: root);
     }
 }
Example #25
0
 // [WMR 20180409] NEW
 // https://github.com/ewoutkramer/fhir-net-api/issues/545
 public XDocument SerializeToDocument(Base instance, SummaryType summary = SummaryType.False, string root = null)
 {
     return(xmlWriterToDocument(xw =>
     {
         using (var writer = new XmlFhirWriter(xw))
         {
             Serialize(instance, writer, summary, root);
             xw.Flush();
         }
     }));
 }
 public void SetSummaryValue(SummaryType type, SummaryPhase phase, double val)
 {
     int str = (int)type;
     int ph = (int)phase;
     String sum = summaries[str];
     List<double> phases = summData[sum];
     if (phases.Count <= ph)
         phases.Add(val);
     else
         phases[ph] = val;
 }
Example #27
0
        public static string SummarizeByCompressionRatio(TDM miTDM,
                                                         List <PositionValue> phrasesList,
                                                         SummaryType summaryType,
                                                         int summaryLength, out List <KeyValuePair <string, int> > summaryXML)
        {
            var genSummary = "";

            summaryXML = new List <KeyValuePair <string, int> >();
            var i = 0;

            if (summaryType == SummaryType.Words)
            {
                string[] words;
                do
                {
                    genSummary += miTDM.PhrasesList[phrasesList[i].Position].OriginalText + " ";
                    summaryXML.Add(new KeyValuePair <string, int>(miTDM.PhrasesList[phrasesList[i].Position].OriginalText, phrasesList[i].Position));
                    i++;
                    words = genSummary.TrimEnd(' ').Split(' ');
                } while (words.Length < summaryLength && i < phrasesList.Count);

                genSummary = "";
                for (i = 0; i < summaryLength; i++)
                {
                    if (i > words.Length - 1)
                    {
                        continue;
                    }
                    genSummary += words[i] + " ";
                }

                var myLength = genSummary.TrimEnd(' ').Split(' ').Length;
                if (myLength < summaryLength)
                {
                    Debug.WriteLine("**************OJO: short : " + myLength + " **************");
                }
                return(genSummary.Trim());
            }

            if (summaryType == SummaryType.Sentences)
            {
                for (var f = 0; f < phrasesList.Count; f++)
                {
                    if (f >= summaryLength)
                    {
                        break;
                    }
                    genSummary += miTDM.PhrasesList[phrasesList[f].Position].OriginalText + " ";
                }
                return(genSummary.Trim());
            }

            return(genSummary.Trim());
        }
Example #28
0
 public SummaryGrid(ISessionColumnCollection collection, DataTable data, SessionColumnType sheartype
                    , IAxis axis, SummaryType summarytype)
 {
     _collection  = collection;
     _rowdata     = data.AsDataView();
     _axis        = axis;
     _sheartype   = sheartype;
     _summarytype = summarytype;
     setCols();
     FilterData();
 }
Example #29
0
 public static byte[] SerializeToJsonBytes(Base instance, SummaryType summary = SummaryType.False, string root = null)
 {
     // [WMR 20160421] Explicit disposal
     // return jsonWriterToBytes(jw => Serialize(instance, new JsonDomFhirWriter(jw), summary, root));
     return(jsonWriterToBytes(jw => {
         using (var writer = new JsonDomFhirWriter(jw))
         {
             Serialize(instance, writer, summary, root);
             jw.Flush();
         }
     }));
 }
Example #30
0
 public TestCreateQuantaAll(
     SummaryType type, Action <string> sqlExecuter, string dimensionAndGroupTitlesJoined,
     string sumOfScalarTitlesJoined, string scalarTitlesJoined,
     List <Dimension> dimensionsAndGroups, List <Period> periods, List <Property> properties,
     List <string> propertyTitles, bool hasQuantaB)
     : base(
         type, sqlExecuter, dimensionAndGroupTitlesJoined,
         sumOfScalarTitlesJoined, scalarTitlesJoined,
         dimensionsAndGroups, periods, properties,
         propertyTitles, hasQuantaB)
 {
 }
        public void InitView()
        {
            if (UserContext.isAnonymous)
            {
                View.DisplaySessionTimeout();
            }
            else
            {
                Int32       idUser      = View.PreloadIdUser;
                Int32       idCommunity = View.SummaryIdCommunity;
                SummaryType type        = View.PreloadFromSummary;

                if (type != SummaryType.PortalIndex && idCommunity <= 0)
                {
                    type = SummaryType.PortalIndex;
                }
                else if (type != SummaryType.PortalIndex)
                {
                    type = SummaryType.CommunityIndex;
                    if (idCommunity == 0)
                    {
                        idCommunity = UserContext.CurrentCommunityID;
                    }
                }
                View.FromSummary        = type;
                View.SummaryIdCommunity = idCommunity;
                View.SummaryIdUser      = idUser;
                if (idUser == 0)
                {
                    View.DisplayNoUserSelected(RootObject.SummaryIndex(type, idCommunity));
                    View.SendUserAction(idCommunity, IdModule, ModuleEduPath.ActionType.UnselectedUserForSummaryUser);
                }
                else
                {
                    // VERIFICA PERMESSI
                    litePerson    currentPerson = CurrentManager.GetLitePerson(UserContext.CurrentUserID);
                    litePerson    person        = CurrentManager.GetLitePerson(idUser);
                    ModuleEduPath mEduPath      = PathService.ServiceStat.GetPermissionForSummaryUser(type, idCommunity, UserContext.CurrentUserID, idUser);
                    if (mEduPath.Administration || mEduPath.ViewMyStatistics)
                    {
                        View.SendUserAction(idCommunity, IdModule, ModuleEduPath.ActionType.ViewSummaryUser);
                        View.AllowOrganizationSelection = (currentPerson != null && (currentPerson.TypeID == (int)UserTypeStandard.Administrator || currentPerson.TypeID == (int)UserTypeStandard.SysAdmin));
                        View.LoadAvailableOrganizations(UserContext.CurrentUserID);
                        View.LoadData(idUser, person);
                    }
                    else
                    {
                        View.DisplayWrongPageAccess(RootObject.SummaryIndex(type, idCommunity));
                        View.SendUserAction(idCommunity, IdModule, ModuleEduPath.ActionType.WrongPageAccess);
                    }
                }
            }
        }
		public void SelectSummary(SummaryType summaryType)
		{
			switch (summaryType)
			{
				case SummaryType.Overview:
					_selectedOutput = BasicOverview;
					HelpButtonItem = Controller.Instance.BasicOverviewHelp;
					break;
				case SummaryType.MultiSummary:
					_selectedOutput = MultiSummary;
					HelpButtonItem = Controller.Instance.MultiSummaryHelp;
					break;
				case SummaryType.Snapshot:
					_selectedOutput = Snapshot;
					HelpButtonItem = Controller.Instance.SnapshotHelp;
					break;
				default:
					_selectedOutput = null;
					break;
			}

			if (_selectedOutput != null)
			{
				if (!pnMain.Controls.Contains(_selectedOutput as Control))
				{
					Application.DoEvents();
					pnEmpty.BringToFront();
					Application.DoEvents();
					pnMain.Controls.Add(_selectedOutput as Control);
					Application.DoEvents();
					pnMain.BringToFront();
					Application.DoEvents();
				}
				(_selectedOutput as Control).BringToFront();
				Controller.Instance.Supertip.SetSuperTooltip(HelpButtonItem, _selectedOutput.HelpToolTip);
			}
			else
			{
				pnEmpty.BringToFront();
				Controller.Instance.Supertip.SetSuperTooltip(HelpButtonItem, null);
			}
		}
Example #33
0
        public SensorTemplate(string unit, float upperLimit, float lowerLimit, float maxRateOfChange, MatchStyle matchStyle, string pattern,SummaryType sType)
        {
            if (String.IsNullOrWhiteSpace(unit))
                throw new ArgumentException("You must a non-blank default unit.");

            if (pattern == null)
                throw new ArgumentException("The pattern to match a sensor on cannot be blank.");

            if (lowerLimit > upperLimit)
                throw new ArgumentOutOfRangeException(
                    "The lower limit must be less than the upper limit for this preset.");

            _unit = unit;
            _upperLimit = upperLimit;
            _lowerLimit = lowerLimit;
            _maxRateOfChange = maxRateOfChange;
            _sType = sType;

            _matchStyle = matchStyle;
            _pattern = pattern;
        }
		/// <summary>
		/// Remove blank lines from a string.
		/// </summary>
		public static string EliminateMultipleBlanks(
			string s,
			SummaryType type)
		{
			s = s.Trim();

			s = s.Replace("\r\n", "\n");
			s = s.Replace("\r", "\n");

			s = Regex.Replace(
				s,
				"\\n[ \\t]*\\n",
				"\n",
				RegexOptions.IgnoreCase);

			if (type == SummaryType.Html)
			{
				s = HtmlHelper.FormatMultiLine(s);
			}

			return s;
		}
 /// <summary>
 /// 
 /// </summary>
 /// <param name="format_">e.g. "{0:$#,###;($#,###);$0}"</param>
 /// <param name="summaryType_"></param>
 public SummaryRowAttribute(string format_, SummaryType summaryType_)
 {
   m_format = format_;
   m_summaryType = summaryType_;
 }
 /// <summary>
 /// 
 /// </summary>
 /// <param name="format_">e.g. "{0:$#,###;($#,###);$0}"</param>
 /// <param name="summaryType_"></param>
 /// <param name="align_"></param>
 public SummaryRowAttribute(string format_, SummaryType summaryType_, HAlign align_)
   : this(format_, summaryType_)
 {
   m_align = align_;
 }
 public List<Double> GetSummaryByType(SummaryType type)
 {
     return summData[summaries[(int)type]];
 }
Example #38
0
        public bool ExpCalculatedData(string expression, DateTime stime, DateTime etime, string duration, string filter, SummaryType type, out double[] pdata)
        {
            //����ÿһ���㣬Ȼ���滻���ʽ,ʹ��.NET���ʽ���㺯�����㡣
            //Ȼ�����ExpressionSummaries���㣬����

            //PITimeServer.ITimeInterval ti;
            //PITimeServer.PITime pitime= new PITimeServer.PITimeClass();
            //pitime.LocalDate = stime;
            //DateTime dtime = ti.AddIntervals(pitime, 100); //PITimeServer.ITimeInterval

            //ti.AddIntervals = stime;

            //ti = new PITimeServer.ITimeInterval("2h");
            //ti = PITimeServer.ITimeIntervals("2h");

            //������������������������������������������������������������������������
            //��Ҫ���ƣ�����������������������������

            pdata = null;

            return true;
        }
Example #39
0
        public double ExpCalculatedData(string expression, DateTime stime, DateTime etime, string filter, SummaryType type)
        {
            //IPICalculation
            //Dim srv As Server
            //Dim ipiCalc As IPICalculation
            //Dim vals1 As PIValues, vals2 As PIValues, vals3 As PIValues
            //Dim expr1 As String, expr2 As String, startTime As String, endTime As String
            //Dim testTimes As Variant, cnt As Long, I As Long

            //Dim bCheck As Boolean, bValCheck As Boolean

            //    startTime = "y" ' yesterday midnight
            //    endTime = "y+1h"
            //    expr1 = "if 'cdm158' = ""auto"" then 1 else 0"
            //    expr2 = "'sinusoid' + 'cdt158'"

            //    Set srv = Servers("localhost")
            //    Set ipiCalc = srv                        ' Get pointer to IPICalculation Interface

            //' note that the SampleInterval argument is ignored if stRecordedValues is the SampleType
            //    Set vals1 = ipiCalc.Calculate(startTime, endTime, expr1, stRecordedValues, "")
            //    cnt = vals1.Count

            //ExpressionSummaries
            //This method creates a data stream from an arbitrary expression and calculate one or more summaries on the expression result. The method returns a NamedValues collection with the requested summaries as described below under Remarks. This method is currently not supported for PI2 servers.
            //Syntax
            //object.ExpressionSummaries StartTime, EndTime, SummaryDuration, Expression, SummaryType, CalculationBasis, stSampleType, SampleInterval, asynchStatus
            //Expression
            // A string containing the expression to be evaluated.  The syntax for the expression follows the Performance Equation syntax as described in the server documentation.
            //Syntax
            //object.PercentTrue StartTime, EndTime, CalculationDuration, Expression, SampleType, SampleInterval, asynchStatus

            double ReturnValue = double.MinValue;

            try {
                PISDK.IPICalculation ipicalc = (IPICalculation)piServer;

                PISDKCommon.NamedValues nvsSum;
                PIValues valsum;

                double dpercent = 0.0;

                if (filter != "") {
                    valsum = ipicalc.PercentTrue(stime, etime, "", filter);

                    if (valsum.Count == 1) {
                        dpercent = (double)valsum[1].Value;
                    }

                    //wugh,add at 2013.4.8
                    if (dpercent < 0.00001) {
                        return ReturnValue;
                    }
                }
                else {
                    dpercent = 100;
                }

                /////////////////////////////////////////////////////////////////////////////////////
                //
                if (dpercent < 100) {
                    int count = 0;
                    int startIndex = 0;
                    List<int> positionIndex = new List<int>();

                    while (true) {
                        int y = expression.IndexOf("'", startIndex);
                        if (y != -1) {
                            //��¼�ַ�("'")λ��
                            positionIndex.Add(y);

                            count++;
                            startIndex = y + 1;
                        }
                        else {
                            break;
                        }
                    }

                    if (count % 2 != 0) {
                        //error
                        return ReturnValue;
                    }

                    //Dictionary<string, double> tagdic = new Dictionary<string, double>();
                    string newexpression = expression;

                    for (int i = 0; i < count; i = i + 2) {
                        string tagname = expression.Substring(positionIndex[i] + 1, positionIndex[i + 1] - positionIndex[i] - 1);

                        double tagvalue = TagCalculatedData(tagname, stime, etime, "", type);

                        //tagdic.Add(tagname, tagvalue);

                        tagname = "'" + tagname + "'";

                        newexpression = newexpression.Replace(tagname, tagvalue.ToString());
                    }

                    //ReturnValue = Evaluator.Evaluator.EvaluateToDouble(newexpression);
                    ReturnValue = Evaluator.Evaluator.EvaluateToDouble(newexpression);

                    return ReturnValue;
                }

                ////////////////////////////////////////////////////////////////////////////
                valsum = null;

                switch (type) {
                    case SummaryType.asTotal:
                        nvsSum = ipicalc.ExpressionSummaries(stime, etime, "", expression, ArchiveSummariesTypeConstants.asTotal);
                        valsum = (PIValues)nvsSum["Total"].Value;
                        break;

                    case SummaryType.asMinimum:
                        nvsSum = ipicalc.ExpressionSummaries(stime, etime, "", expression, ArchiveSummariesTypeConstants.asMinimum);
                        valsum = (PIValues)nvsSum["Minimum"].Value;
                        break;

                    case SummaryType.asMaximum:
                        nvsSum = ipicalc.ExpressionSummaries(stime, etime, "", expression, ArchiveSummariesTypeConstants.asMaximum);
                        valsum = (PIValues)nvsSum["Maximum"].Value;
                        break;

                    case SummaryType.asStdDev:
                        nvsSum = ipicalc.ExpressionSummaries(stime, etime, "", expression, ArchiveSummariesTypeConstants.asStdDev);
                        valsum = (PIValues)nvsSum["StdDev"].Value;
                        break;

                    case SummaryType.asRange:
                        nvsSum = ipicalc.ExpressionSummaries(stime, etime, "", expression, ArchiveSummariesTypeConstants.asRange);
                        valsum = (PIValues)nvsSum["Range"].Value;
                        break;

                    case SummaryType.asAverage:
                        nvsSum = ipicalc.ExpressionSummaries(stime, etime, "", expression, ArchiveSummariesTypeConstants.asAverage);
                        valsum = (PIValues)nvsSum["Average"].Value;
                        break;

                    case SummaryType.asPStdDev:
                        nvsSum = ipicalc.ExpressionSummaries(stime, etime, "", expression, ArchiveSummariesTypeConstants.asPStdDev);
                        valsum = (PIValues)nvsSum["PStdDev"].Value;
                        break;

                    //case SummaryType.asTotal:
                    //nvsSum = ipicalc.ExpressionSummaries(stime, etime, "", expression, ArchiveSummariesTypeConstants.asAverage);
                    //valsum = (PIValues)nvsSum["Average"].Value;
                    //break;

                    default:
                        nvsSum = ipicalc.ExpressionSummaries(stime, etime, "", expression, ArchiveSummariesTypeConstants.asAverage);
                        valsum = (PIValues)nvsSum["Average"].Value;
                        break;
                }

                if (valsum.Count == 1) {
                    ReturnValue = (double)valsum[1].Value;
                }

            }
            catch (Exception ex) {
                LogUtil.LogMessage(ex.Message);
                //_ErrorInfo = ex.Message;
            }

            return ReturnValue;
        }
Example #40
0
        public bool ExpCalculatedData(string expression, DateTime stime, DateTime etime, string duration, string filter, SummaryType type, out double[] pdata)
        {
            pdata = null;

            return true;
        }
Example #41
0
        /// <summary>
        /// 指定开始结束时间
        /// 统计时间内的Total\Max\Min\StdDev\Range\Average\PStdDev,返回单个数据
        /// 注:expression 存放的是点名称  filter没用到
        /// </summary>
        public Double ExpCalculatedData(string expression, DateTime stime, DateTime etime, string filter, SummaryType type)
        {
            try {
                if (String.IsNullOrEmpty(expression)) {
                    return Double.MinValue;
                }
                TagVector tagVector = GetPointListByTagName(expression);
                if (null == tagVector || 0 >= tagVector.Count) {
                    return Double.MinValue;
                }
                HisDataSet hisDataSet = new HisDataSet();
                AggregateEnum aggregateType;
                switch (type) {
                    case SummaryType.asTotal:
                        aggregateType = AggregateEnum.TOTAL;
                        break;
                    case SummaryType.asMinimum:
                        aggregateType = AggregateEnum.MINIMUM;
                        break;
                    case SummaryType.asMaximum:
                        aggregateType = AggregateEnum.MAXIMUM;
                        break;
                    case SummaryType.asStdDev:
                        aggregateType = AggregateEnum.STDEV;
                        break;
                    case SummaryType.asRange:
                        aggregateType = AggregateEnum.RANGE;
                        break;
                    case SummaryType.asAverage:
                        aggregateType = AggregateEnum.AVERAGE;
                        break;
                    case SummaryType.asPStdDev:  //注:pSpace没有这类型
                        aggregateType = AggregateEnum.STDEV;
                        break;
                    default:
                        aggregateType = AggregateEnum.AVERAGE;
                        break;
                }

                BatchResults results = DataIO.ReadProcessed(dbConnector, tagVector, stime, etime, etime - stime, aggregateType, hisDataSet);
                if (results.HasErrors) {
                    foreach (DbError dberror in results.Errors) {
                        _ErrorInfo += dberror.ErrorMessage;
                    }
                    return Double.MinValue;
                }
                if (null != hisDataSet && 0 < hisDataSet.Count) {
                    return ConvertToDouble(hisDataSet[0].Data[0].Value);
                }
                return Double.MinValue;
            }
            catch (Exception ex) {
                _ErrorInfo = ex.Message;
                return Double.MinValue;
            }
        }
Example #42
0
 public double TagCalculatedData(string tagname, DateTime stime, DateTime etime, string filter, SummaryType type)
 {
     return 0.0;
 }
Example #43
0
        /// <summary>
        /// Creates a new sensor.
        /// </summary>
        /// <param name="name">The name of the sensor.</param>
        /// <param name="description">A description of the sensor's function or purpose.</param>
        /// <param name="upperLimit">The upper limit for values reported by this sensor.</param>
        /// <param name="lowerLimit">The lower limit for values reported by this sensor.</param>
        /// <param name="unit">The unit used to report values given by this sensor.</param>
        /// <param name="maxRateOfChange">The maximum rate of change allowed by this sensor.</param>
        /// <param name="manufacturer">The manufacturer of this sensor.</param>
        /// <param name="serial">The serial number associated with this sensor.</param>
        /// <param name="undoStack">A stack containing previous sensor states.</param>
        /// <param name="redoStack">A stack containing sensor states created after the modifications of the current state.</param>
        /// <param name="calibrations">A list of dates, on which calibration was performed.</param>
        /// <param name="errorThreshold">The number of times a failure-indicating value can occur before this sensor is flagged as failing.</param>
        /// <param name="owner">The dataset that owns the sensor</param>
        /// <param name="sType">Indicates whether the sensor's values should be averaged or summed when summarised</param>
        public Sensor(string name, string description, float upperLimit, float lowerLimit, string unit, float maxRateOfChange, Stack<SensorState> undoStack, Stack<SensorState> redoStack, List<Calibration> calibrations, int errorThreshold, Dataset owner, SummaryType sType)
        {
            if (name == "")
                throw new ArgumentNullException("Name");

               // if (unit == "")
             //   throw new ArgumentNullException("Unit");

            if (calibrations == null)
                throw new ArgumentNullException("Calibrations");

            if (undoStack == null)
                throw new ArgumentNullException("UndoStack");

            if (redoStack == null)
                throw new ArgumentNullException("RedoStack");

            if (upperLimit <= lowerLimit)
                throw new ArgumentOutOfRangeException("UpperLimit");

            _name = name;
            RawName = name;
            Description = description;
            UpperLimit = upperLimit;
            LowerLimit = lowerLimit;
            _unit = unit;
            MaxRateOfChange = maxRateOfChange;
            _undoStack = undoStack;
            _redoStack = redoStack;
            _calibrations = calibrations;

            ErrorThreshold = errorThreshold;
            Owner = owner;
            _summaryType = sType;

            _metaData = new ObservableCollection<SensorMetaData>();
            CurrentMetaData = new SensorMetaData("");

            Colour = Color.FromRgb((byte)(Common.Generator.Next()), (byte)(Common.Generator.Next()), (byte)(Common.Generator.Next()));
        }
Example #44
0
 public double ExpCalculatedData(string expression, DateTime stime, DateTime etime, string filter, SummaryType type)
 {
     return 0.0;
 }
Example #45
0
        /// <summary>
        /// 指定开始结束时间
        /// 统计时间内的Total\Max\Min\StdDev\Range\Average\PStdDev,根据时间间隔返回数据组
        /// </summary>
        public bool TagCalculatedData(string tagname, DateTime stime, DateTime etime, string duration, string filter, SummaryType type, out double[] pdata)
        {
            try {
                pdata = null;
                if (String.IsNullOrEmpty(tagname)) {
                    return false;
                }
                TagVector tagVector = GetPointListByTagName(tagname);
                if (null == tagVector || 0 >= tagVector.Count) {
                    return false;
                }
                HisDataSet hisDataSet = new HisDataSet();
                AggregateEnum aggregateType;
                switch (type) {
                    case SummaryType.asTotal:
                        aggregateType = AggregateEnum.TOTAL;
                        break;
                    case SummaryType.asMinimum:
                        aggregateType = AggregateEnum.MINIMUM;
                        break;
                    case SummaryType.asMaximum:
                        aggregateType = AggregateEnum.MAXIMUM;
                        break;
                    case SummaryType.asStdDev:
                        aggregateType = AggregateEnum.STDEV;
                        break;
                    case SummaryType.asRange:
                        aggregateType = AggregateEnum.RANGE;
                        break;
                    case SummaryType.asAverage:
                        aggregateType = AggregateEnum.AVERAGE;
                        break;
                    case SummaryType.asPStdDev:  //注:pSpace没有这类型
                        aggregateType = AggregateEnum.STDEV;
                        break;
                    default:
                        aggregateType = AggregateEnum.AVERAGE;
                        break;
                }

                BatchResults results = DataIO.ReadProcessed(dbConnector, tagVector, stime, etime, etime - stime, aggregateType, hisDataSet);
                if (results.HasErrors) {
                    foreach (DbError dberror in results.Errors) {
                        _ErrorInfo += dberror.ErrorMessage;
                    }
                    return false;
                }
                List<Double> list = new List<Double>();
                if (null != hisDataSet && 0 < hisDataSet.Count) {
                    foreach (var items in hisDataSet) {
                        if (null == items.Data || 0 >= items.Data.Count) {
                            continue;
                        }
                        foreach (RealHisData item in items.Data) {
                            list.Add(ConvertToDouble(item.Value));
                        }
                    }
                    pdata = list.ToArray();
                    return true;
                }
                return false;
            }
            catch (Exception ex) {
                _ErrorInfo = ex.Message;
                pdata = null;
                return false;
            }
        }
Example #46
0
        public double TagCalculatedData(string tagname, DateTime stime, DateTime etime, string filter, SummaryType type)
        {
            double ReturnValue = double.MinValue;

            try {
                PISDK.PIPoint piPoint = piServer.PIPoints[tagname];

                if (filter.Trim() != "") {
                    /////////////////////////////////////////////////////////////////////////////////
                    PISDK.IPIData2 ipda = (PISDK.IPIData2)piPoint.Data;

                    PISDKCommon.NamedValues nvsSum;
                    PIValues valsum;
                    //ReturnValue = Convert.ToDouble(ipda.Snapshot.Value);

                    ///////////////////////////////////////////////////////////////////////
                    PISDK.IPICalculation ipicalc = (IPICalculation)piServer;

                    if (filter != "") {
                        double dpercent = 0.0;
                        valsum = ipicalc.PercentTrue(stime, etime, "", filter);

                        if (valsum.Count == 1) {
                            dpercent = (double)valsum[1].Value;
                        }

                        //wugh,add at 2013.4.8
                        if (dpercent < 0.00001) {
                            return ReturnValue;
                        }

                    }
                    /////////////////////////////////////////////////////////////

                    switch (type) {
                        case SummaryType.asTotal:
                            nvsSum = ipda.FilteredSummaries(stime, etime, "", filter, ArchiveSummariesTypeConstants.asTotal);
                            valsum = (PIValues)nvsSum["Total"].Value;
                            break;

                        case SummaryType.asMinimum:
                            nvsSum = ipda.FilteredSummaries(stime, etime, "", filter, ArchiveSummariesTypeConstants.asMinimum);
                            valsum = (PIValues)nvsSum["Minimum"].Value;
                            break;

                        case SummaryType.asMaximum:
                            nvsSum = ipda.FilteredSummaries(stime, etime, "", filter, ArchiveSummariesTypeConstants.asMaximum);
                            valsum = (PIValues)nvsSum["Maximum"].Value;
                            break;

                        case SummaryType.asStdDev:
                            nvsSum = ipda.FilteredSummaries(stime, etime, "", filter, ArchiveSummariesTypeConstants.asStdDev);
                            valsum = (PIValues)nvsSum["StdDev"].Value;
                            break;

                        case SummaryType.asRange:
                            nvsSum = ipda.FilteredSummaries(stime, etime, "", filter, ArchiveSummariesTypeConstants.asRange);
                            valsum = (PIValues)nvsSum["Range"].Value;
                            break;

                        case SummaryType.asAverage:
                            nvsSum = ipda.FilteredSummaries(stime, etime, "", filter, ArchiveSummariesTypeConstants.asAverage);
                            valsum = (PIValues)nvsSum["Average"].Value;
                            break;

                        case SummaryType.asPStdDev:
                            nvsSum = ipda.FilteredSummaries(stime, etime, "", filter, ArchiveSummariesTypeConstants.asPStdDev);
                            valsum = (PIValues)nvsSum["PStdDev"].Value;
                            break;

                        //case SummaryType.asTotal:
                        //    nvsSum = ipda.FilteredSummaries(stime, etime, "", filter, ArchiveSummariesTypeConstants.asAverage);
                        //    valsum = (PIValues)nvsSum["Average"].Value;
                        //    break;

                        default:
                            nvsSum = ipda.FilteredSummaries(stime, etime, "", filter, ArchiveSummariesTypeConstants.asAverage);
                            valsum = (PIValues)nvsSum["Average"].Value;
                            break;
                    }

                    if (valsum.Count == 1) {
                        //LogUtil.LogMessage(valsum[1].Value.ToString());
                        ReturnValue = (double)valsum[1].Value;
                    }

                }
                else {
                    ////////////////////////////////////////////////////////////////////////////////////////////////////////
                    //No Filter
                    PISDK.PIValue rv = null;

                    switch (type) {
                        case SummaryType.asTotal:
                            rv = piPoint.Data.Summary(stime, etime, PISDK.ArchiveSummaryTypeConstants.astTotal);
                            break;

                        case SummaryType.asMinimum:
                            rv = piPoint.Data.Summary(stime, etime, PISDK.ArchiveSummaryTypeConstants.astMaximum);
                            break;

                        case SummaryType.asMaximum:
                            rv = piPoint.Data.Summary(stime, etime, PISDK.ArchiveSummaryTypeConstants.astMaximum);
                            break;

                        case SummaryType.asStdDev:
                            rv = piPoint.Data.Summary(stime, etime, PISDK.ArchiveSummaryTypeConstants.astStdDev);
                            break;

                        case SummaryType.asRange:
                            rv = piPoint.Data.Summary(stime, etime, PISDK.ArchiveSummaryTypeConstants.astRange);
                            break;

                        case SummaryType.asAverage:
                            rv = piPoint.Data.Summary(stime, etime, PISDK.ArchiveSummaryTypeConstants.astAverage);
                            break;

                        case SummaryType.asPStdDev:
                            rv = piPoint.Data.Summary(stime, etime, PISDK.ArchiveSummaryTypeConstants.astPStdDev);
                            break;

                        //case SummaryType.asTotal:
                        //    rv = piPoint.Data.Summary(stime, etime, PISDK.ArchiveSummaryTypeConstants.astMaximum);
                        //    break;

                        default:
                            rv = piPoint.Data.Summary(stime, etime, PISDK.ArchiveSummaryTypeConstants.astAverage);
                            break;

                    }

                    ReturnValue = Convert.ToDouble(rv.Value);
                }

            }
            catch (Exception ex) {
                LogUtil.LogMessage(ex.Message);
                //_ErrorInfo = ex.Message;
            }

            return ReturnValue;
        }
Example #47
0
 /// <summary>
 /// Takes a SummaryType as an argument and returns the corresponding Excel function name.
 ///             Returns null for SummaryType.Custom.
 /// 
 /// </summary>
 protected virtual string GetExcelFunctionName(SummaryType summaryType)
 {
     switch (summaryType)
     {
         case SummaryType.Count:
             return "COUNTA|COUNTBLANK";
         case SummaryType.Min:
             return "MIN";
         case SummaryType.Max:
             return "MAX";
         case SummaryType.Average:
             return "AVERAGE";
         case SummaryType.Sum:
             return "SUM";
         default:
             return (string)null;
     }
 }
Example #48
0
        public bool TagCalculatedData(string tagname, DateTime stime, DateTime etime, string duration, string filter, SummaryType type, out double[] pdata)
        {
            pdata = null;

            try {
                PISDK.PIPoint piPoint = piServer.PIPoints[tagname];

                /////////////////////////////////////////////////////////////////////////////////
                PISDK.IPIData2 ipda = (PISDK.IPIData2)piPoint.Data;
                PISDKCommon.NamedValues nvsSum;
                PIValues valsum;

                //////////////////////////////////////////////////////////////
                PISDK.IPICalculation ipicalc = (IPICalculation)piServer;

                if (filter != "") {
                    double dpercent = 0.0;
                    valsum = ipicalc.PercentTrue(stime, etime, "", filter);

                    if (valsum.Count == 1) {
                        dpercent = (double)valsum[1].Value;
                    }

                    //wugh,add at 2013.4.8
                    if (dpercent < 0.00001) {
                        return false;
                    }

                }

                switch (type) {
                    case SummaryType.asTotal:
                        nvsSum = ipda.FilteredSummaries(stime, etime, duration, filter, ArchiveSummariesTypeConstants.asTotal);
                        valsum = (PIValues)nvsSum["Total"].Value;
                        break;

                    case SummaryType.asMinimum:
                        nvsSum = ipda.FilteredSummaries(stime, etime, duration, filter, ArchiveSummariesTypeConstants.asMinimum);
                        valsum = (PIValues)nvsSum["Minimum"].Value;
                        break;

                    case SummaryType.asMaximum:
                        nvsSum = ipda.FilteredSummaries(stime, etime, duration, filter, ArchiveSummariesTypeConstants.asMaximum);
                        valsum = (PIValues)nvsSum["Maximum"].Value;
                        break;

                    case SummaryType.asStdDev:
                        nvsSum = ipda.FilteredSummaries(stime, etime, duration, filter, ArchiveSummariesTypeConstants.asStdDev);
                        valsum = (PIValues)nvsSum["StdDev"].Value;
                        break;

                    case SummaryType.asRange:
                        nvsSum = ipda.FilteredSummaries(stime, etime, duration, filter, ArchiveSummariesTypeConstants.asRange);
                        valsum = (PIValues)nvsSum["Range"].Value;
                        break;

                    case SummaryType.asAverage:
                        nvsSum = ipda.FilteredSummaries(stime, etime, duration, filter, ArchiveSummariesTypeConstants.asAverage);
                        valsum = (PIValues)nvsSum["Average"].Value;
                        break;

                    case SummaryType.asPStdDev:
                        nvsSum = ipda.FilteredSummaries(stime, etime, duration, filter, ArchiveSummariesTypeConstants.asPStdDev);
                        valsum = (PIValues)nvsSum["PStdDev"].Value;
                        break;

                    //case SummaryType.asTotal:
                    //    nvsSum = ipda.FilteredSummaries(stime, etime, duration, filter, ArchiveSummariesTypeConstants.asAverage);
                    //    valsum = (PIValues)nvsSum["Average"].Value;
                    //    break;

                    default:
                        nvsSum = ipda.FilteredSummaries(stime, etime, duration, filter, ArchiveSummariesTypeConstants.asAverage);
                        valsum = (PIValues)nvsSum["Average"].Value;
                        break;
                }

                if (valsum.Count > 0) {
                    pdata = new double[valsum.Count];

                    for (int i = 1; i <= valsum.Count; i++) {
                        pdata[i - 1] = (double)valsum[i].Value;
                    }

                    return true;
                }
                else {

                    return false;
                }

            }
            catch (Exception ex) {
                _ErrorInfo = ex.Message;

                return false;
            }
        }