static void Main(string[] args) { PIServers pIServers = new PIServers(); foreach (var server in pIServers) { Console.WriteLine("Server: {0}", server.Name); } PIServer piServer = pIServers.DefaultPIServer; Console.WriteLine("Default connection is: {0}", piServer.Name); piServer.Connect(); // do smth with the pi system // get a pi point var point = PIPoint.FindPIPoint(piServer, "PLCW00321500=S20NDD11BU900:XQ001"); var value = point.CurrentValue(); var timevalue = value.Timestamp; var valuevalue = value.Value; Console.WriteLine("Tag name: {0} and its Value is: {1}, {2}", point.Name, timevalue, valuevalue); var plotValues = point.PlotValues(new AFTimeRange("*-1w", "*"), 10); foreach (var pValue in plotValues) { Console.WriteLine("{0} {1}", pValue.Value, pValue.Timestamp); } piServer.Disconnect(); Console.ReadKey(); }
public void Disconnect() { if (piServer != null) { piServer.Disconnect(); } }
public void Disconnect() { if (MyPiServer != null) { if (MyPiServer.ConnectionInfo.IsConnected) { MyPiServer.Disconnect(); } } }
/// <summary> /// Closes <see cref="PIConnection"/>. /// </summary> public void Close() { m_connected = false; // Attempt to close OSI-PI connection if ((object)m_server != null) { if (m_server.ConnectionInfo.IsConnected) { m_server.Disconnect(); } // Detach from server disconnected event m_server.ConnectChanged -= PIConnection_ConnectChanged; } }
public bool Disconnect() { if (!_SitePI.ConnectionInfo.IsConnected) { return(true); } else { _logger.Information("Disconnecting from PI"); try { _SitePI.Disconnect(); _logger.Information("Successfully disconnected from PI Data Collective"); } catch (Exception e) { _logger.Error("Unable to disconnect from PI Data Collective. Error {0}", e.Message); } return(!_SitePI.ConnectionInfo.IsConnected); } }
public void Dispose() { try { server?.Disconnect(); } catch { } }
internal void Execute(string command, PIPointList pointsList, AFTime st, AFTime et, AFTimeSpan summaryDuration, string[] times, string addlparam1, PIServer myServer) { try { Console.WriteLine(); switch (command) { case "snap": { var sb = new StringBuilder(); sb.AppendLine($"Point Name(Point Id), Timestamp, Current Value"); sb.AppendLine(new string('-', 45)); AFListResults <PIPoint, AFValue> results = pointsList.EndOfStream(); if (results.HasErrors) { foreach (var e in results.Errors) { sb.AppendLine($"{e.Key}: {e.Value}"); } } foreach (var v in results.Results) { if (!results.Errors.ContainsKey(v.PIPoint)) { sb.AppendLine($"{string.Concat($"{v.PIPoint.Name} ({v.PIPoint.ID})"),-15}," + $" {v.Timestamp}, {v.Value}"); } } sb.AppendLine(); Console.Write(sb.ToString()); break; } case "arclist": { AFTimeRange timeRange = new AFTimeRange(st, et); if (!Int32.TryParse(addlparam1, out int maxcount)) { maxcount = 0; } // Holds the results keyed on the associated point var resultsMap = new Dictionary <PIPoint, AFValues>(); var pagingConfig = new PIPagingConfiguration(PIPageType.TagCount, GlobalConfig.PageSize); IEnumerable <AFValues> listResults = pointsList.RecordedValues(timeRange: timeRange, boundaryType: AFBoundaryType.Inside, filterExpression: null, includeFilteredValues: false, pagingConfig: pagingConfig, maxCount: maxcount ); foreach (var pointResults in listResults) { resultsMap[pointResults.PIPoint] = pointResults; } foreach (var pointValues in resultsMap) { var sb = new StringBuilder(); sb.AppendLine($"Point: {pointValues.Key} Archive Values " + $"Count: {pointValues.Value.Count}"); sb.AppendLine(new string('-', 45)); pointValues.Value.ForEach(v => sb.AppendLine($"{v.Timestamp}, {v.Value}")); sb.AppendLine(); Console.Write(sb.ToString()); } break; } case "plot": { AFTimeRange timeRange = new AFTimeRange(st, et); if (!Int32.TryParse(addlparam1, out int intervals)) { intervals = 640; //horizontal pixels in the trend } var resultsMap = new Dictionary <PIPoint, AFValues>(); var pagingConfig = new PIPagingConfiguration(PIPageType.TagCount, GlobalConfig.PageSize); IEnumerable <AFValues> listResults = pointsList.PlotValues(timeRange: timeRange, intervals: intervals, pagingConfig: pagingConfig ); foreach (var pointResults in listResults) { resultsMap[pointResults.PIPoint] = pointResults; } foreach (var pointValues in resultsMap) { var sb = new StringBuilder(); sb.AppendLine($"Point: {pointValues.Key} Plot Values Interval: {intervals}" + $" Count: {pointValues.Value.Count}"); sb.AppendLine(new string('-', 45)); pointValues.Value.ForEach(v => sb.AppendLine($"{v.Timestamp}, {v.Value}")); sb.AppendLine(); Console.Write(sb.ToString()); } break; } case "interp": { AFTimeRange timeRange = new AFTimeRange(st, et); var resultsMap = new Dictionary <PIPoint, AFValues>(); var pagingConfig = new PIPagingConfiguration(PIPageType.TagCount, GlobalConfig.PageSize); if (addlparam1.StartsWith("c=")) { if (!Int32.TryParse(addlparam1.Substring(2), out int count)) { count = 10; //default count } IEnumerable <AFValues> listResults = pointsList.InterpolatedValuesByCount(timeRange: timeRange, numberOfValues: count, filterExpression: null, includeFilteredValues: false, pagingConfig: pagingConfig ); foreach (var pointResults in listResults) { resultsMap[pointResults.PIPoint] = pointResults; } foreach (var pointValues in resultsMap) { var sb = new StringBuilder(); sb.AppendLine($"Point: {pointValues.Key} Interpolated Values " + $"Count: {pointValues.Value.Count}"); sb.AppendLine(new string('-', 45)); pointValues.Value.ForEach(v => sb.AppendLine($"{v.Timestamp}, {v.Value}")); sb.AppendLine(); Console.Write(sb.ToString()); } } else { if (!AFTimeSpan.TryParse(addlparam1, out AFTimeSpan interval) || interval == new AFTimeSpan(0)) { interval = summaryDuration; } IEnumerable <AFValues> listResults = pointsList.InterpolatedValues(timeRange: timeRange, interval: interval, filterExpression: null, includeFilteredValues: false, pagingConfig: pagingConfig ); foreach (var pointResults in listResults) { resultsMap[pointResults.PIPoint] = pointResults; } foreach (var pointValues in resultsMap) { var sb = new StringBuilder(); sb.AppendLine($"Point: {pointValues.Key} Interpolated Values " + $"Interval: {interval.ToString()}"); sb.AppendLine(new string('-', 45)); pointValues.Value.ForEach(v => sb.AppendLine($"{v.Timestamp}, {v.Value}")); sb.AppendLine(); Console.Write(sb.ToString()); } } break; } case "summaries": { var resultsMap = new Dictionary <PIPoint, AFValues>(); var pagingConfig = new PIPagingConfiguration(PIPageType.TagCount, GlobalConfig.PageSize); if (st > et) //summaries cannot handle reversed times { var temp = st; st = et; et = temp; } AFTimeRange timeRange = new AFTimeRange(st, et); var intervalDefinitions = new AFTimeIntervalDefinition(timeRange, 1); AFCalculationBasis calculationBasis = AFCalculationBasis.EventWeighted; if (addlparam1 == "t") { calculationBasis = AFCalculationBasis.TimeWeighted; } foreach (var pt in pointsList) { var summaryType = AFSummaryTypes.All; if (pt.PointType == PIPointType.Digital || pt.PointType == PIPointType.Timestamp || pt.PointType == PIPointType.Blob || pt.PointType == PIPointType.String || pt.PointType == PIPointType.Null) { summaryType = AFSummaryTypes.AllForNonNumeric; } IDictionary <AFSummaryTypes, AFValues> summaries = pt.Summaries(new List <AFTimeIntervalDefinition>() { intervalDefinitions }, reverseTime: false, summaryType: summaryType, calcBasis: calculationBasis, timeType: AFTimestampCalculation.Auto ); var sb = new StringBuilder(); sb.AppendLine($"Point: {pt.Name} {calculationBasis} Summary"); sb.AppendLine(new string('-', 45)); foreach (var s in summaries) { AFValues vals = s.Value; foreach (var v in vals) { if (v.Value.GetType() != typeof(PIException)) { if (string.Compare(s.Key.ToString(), "Minimum", true) == 0 || string.Compare(s.Key.ToString(), "Maximum", true) == 0) { sb.AppendLine($"{s.Key,-16}: {v.Value,-20} {v.Timestamp}"); } else { sb.AppendLine($"{s.Key,-16}: {v.Value}"); } } else { sb.AppendLine($"{s.Key,-16}: {v}"); } } } sb.AppendLine(); Console.Write(sb.ToString()); } /* * Non numeric tags in pointsList requires splitting of queries so the above is preferred. * The below implementation works when there are no non-numeric types or one particular summary needs to be run */ //var listResults = pointsList.Summaries(new List<AFTimeIntervalDefinition>() { // intervalDefinitions }, // reverseTime: false, // summaryTypes: AFSummaryTypes.All, // calculationBasis: calculationBasis, // timeType: AFTimestampCalculation.Auto, // pagingConfig: pagingConfig // ); //foreach (IDictionary<AFSummaryTypes, AFValues> summaries in listResults) //{ // foreach (IDictionary<AFSummaryTypes, AFValues> pointResults in listResults) // { // AFValues pointValues = pointResults[AFSummaryTypes.Average]; // PIPoint point = pointValues.PIPoint; // //Map the results back to the point // resultsMap[point] = pointValues; // } //} break; } case "update": case "annotate": { string addlparam2 = string.Empty; AFUpdateOption updateOption = AFUpdateOption.Replace; AFBufferOption bufOption = AFBufferOption.BufferIfPossible; AFValue val; if (times.Length > 0) { addlparam1 = times[0]; if (times.Length > 1) { addlparam2 = times[1]; } } switch (addlparam1) { case "i": updateOption = AFUpdateOption.Insert; break; case "nr": updateOption = AFUpdateOption.NoReplace; break; case "ro": updateOption = AFUpdateOption.ReplaceOnly; break; case "inc": updateOption = AFUpdateOption.InsertNoCompression; break; case "rm": updateOption = AFUpdateOption.Remove; break; } switch (addlparam2) { case "dnb": bufOption = AFBufferOption.DoNotBuffer; break; case "buf": bufOption = AFBufferOption.Buffer; break; } foreach (var pt in pointsList) { Console.WriteLine($"Point: {pt.Name} {command} ({updateOption} {bufOption})"); Console.WriteLine(new string('-', 45)); Console.Write("Enter timestamp: "); var time = Console.ReadLine(); if (!AFTime.TryParse(time, out AFTime ts)) { ParseArgs.PrintHelp("Invalid Timestamp"); break; } if (command == "update" || !(pt.RecordedValuesAtTimes(new List <AFTime>() { ts }, AFRetrievalMode.Exact)[0].IsGood)) { Console.Write("Enter new value: "); var data = Console.ReadLine(); if (!Double.TryParse(data, out var value)) { ParseArgs.PrintHelp("Invalid data"); break; } val = new AFValue(value, ts); } else { val = pt.RecordedValuesAtTimes(new List <AFTime>() { ts }, AFRetrievalMode.Exact)[0]; } if (command == "annotate") { Console.Write("Enter annotation: "); var ann = Console.ReadLine(); pt.SetAnnotation(val, ann); } pt.UpdateValue(value: val, option: updateOption, bufferOption: bufOption); Console.WriteLine($"Successfully {command}d"); } Console.WriteLine(); break; } case "delete": { AFTimeRange timeRange = new AFTimeRange(st, et); if (myServer.Supports(PIServerFeature.DeleteRange)) { foreach (var pt in pointsList) { int delcount = 0; var sb = new StringBuilder(); var intervalDefinitions = new AFTimeIntervalDefinition(timeRange, 1); //getting the count of events - optional IDictionary <AFSummaryTypes, AFValues> summaries = pt.Summaries(new List <AFTimeIntervalDefinition>() { intervalDefinitions }, reverseTime: false, summaryType: AFSummaryTypes.Count, calcBasis: AFCalculationBasis.EventWeighted, timeType: AFTimestampCalculation.Auto ); foreach (var s in summaries) { AFValues vals = s.Value; vals = s.Value; foreach (var v in vals) { if (v.Value.GetType() != typeof(PIException)) { delcount = v.ValueAsInt32(); //count } } } if (delcount > 0) { var errs = pt.ReplaceValues(timeRange, new List <AFValue>() { }); if (errs != null) { foreach (var e in errs.Errors) { sb.AppendLine($"{e.Key}: {e.Value}"); delcount--; } } } sb.AppendLine($"Point: {pt.Name} Deleted {delcount} events"); sb.AppendLine(new string('-', 45)); sb.AppendLine(); Console.Write(sb.ToString()); } } else { foreach (var pt in pointsList) { int delcount = 0; var sb = new StringBuilder(); AFValues vals = pt.RecordedValues(timeRange: timeRange, boundaryType: AFBoundaryType.Inside, filterExpression: null, includeFilteredValues: false, maxCount: 0 ); delcount = vals.Count; if (delcount > 0) { var errs = pt.UpdateValues(values: vals, updateOption: AFUpdateOption.Remove, bufferOption: AFBufferOption.BufferIfPossible); if (errs != null) { foreach (var e in errs.Errors) { sb.AppendLine($"{e.Key}: {e.Value}"); delcount--; } } } sb.AppendLine($"Point: {pt.Name} Deleted {delcount} events"); sb.AppendLine(new string('-', 45)); sb.AppendLine(); Console.Write(sb.ToString()); } } break; } case "sign,t": { Dictionary <PIPoint, int> errPoints = pointsList.ToDictionary(key => key, value => 0); //if (Int32.TryParse(myServer.ServerVersion.Substring(4, 3), out int srvbuild) && srvbuild >= 395); if (myServer.Supports(PIServerFeature.TimeSeriesDataPipe)) { PIDataPipe timeSeriesDatapipe = new PIDataPipe(AFDataPipeType.TimeSeries); Console.WriteLine("Signing up for TimeSeries events"); var errs = timeSeriesDatapipe.AddSignups(pointsList); if (errs != null) { foreach (var e in errs.Errors) { Console.WriteLine($"Failed timeseries signup: {e.Key}, {e.Value.Message}"); errPoints[e.Key]++; } foreach (var ep in errPoints) { if (ep.Value >= 1) { pointsList.Remove(ep.Key); } } if (pointsList.Count == 0) { ParseArgs.PrintHelp("No valid PI Points"); if (timeSeriesDatapipe != null) { timeSeriesDatapipe.Close(); timeSeriesDatapipe.Dispose(); } return; } } timeSeriesDatapipe.Subscribe(new DataPipeObserver("TimeSeries")); Console.WriteLine("Subscribed Points (current value): "); AFListResults <PIPoint, AFValue> results = pointsList.EndOfStream(); if (results.HasErrors) { foreach (var e in results.Errors) { Console.WriteLine($"{e.Key}: {e.Value}"); } } foreach (var v in results.Results) { if (!results.Errors.ContainsKey(v.PIPoint)) { Console.WriteLine($"{v.PIPoint.Name,-12}, {v.Timestamp}, {v.Value}"); } } Console.WriteLine(new string('-', 45)); //Fetch timeseries events till user termination while (!GlobalConfig.CancelSignups) { timeSeriesDatapipe.GetObserverEvents(GlobalConfig.PipeMaxEvtCount, out bool hasMoreEvents); Thread.Sleep(GlobalConfig.PipeCheckFreq); } Console.WriteLine("Cancelling signups ..."); if (timeSeriesDatapipe != null) { timeSeriesDatapipe.Close(); timeSeriesDatapipe.Dispose(); } } else { ParseArgs.PrintHelp($"Time series not supported in Archive version {myServer.ServerVersion}"); } break; } case "sign,as": case "sign,sa": case "sign,a": case "sign,s": { bool snapSubscribe = false; bool archSubscribe = false; PIDataPipe snapDatapipe = null; PIDataPipe archDatapipe = null; Dictionary <PIPoint, int> errPoints = pointsList.ToDictionary(key => key, value => 0); if (command.Substring(5).Contains("s")) { snapSubscribe = true; snapDatapipe = new PIDataPipe(AFDataPipeType.Snapshot); Console.WriteLine("Signing up for Snapshot events"); var errs = snapDatapipe.AddSignups(pointsList); snapDatapipe.Subscribe(new DataPipeObserver("Snapshot")); if (errs != null) { foreach (var e in errs.Errors) { Console.WriteLine($"Failed snapshot signup: {e.Key}, {e.Value.Message}"); errPoints[e.Key]++; } } } if (command.Substring(5).Contains("a")) { archSubscribe = true; archDatapipe = new PIDataPipe(AFDataPipeType.Archive); Console.WriteLine("Signing up for Archive events"); var errs = archDatapipe.AddSignups(pointsList); if (errs != null) { foreach (var e in errs.Errors) { Console.WriteLine($"Failed archive signup: {e.Key}, {e.Value.Message}"); errPoints[e.Key]++; } } archDatapipe.Subscribe(new DataPipeObserver("Archive ")); } //remove unsubscribable points int errorLimit = snapSubscribe ? 1 : 0; if (archSubscribe) { errorLimit++; } foreach (var ep in errPoints) { if (ep.Value >= errorLimit) { pointsList.Remove(ep.Key); } } if (pointsList.Count == 0) { ParseArgs.PrintHelp("No valid PI Points"); if (snapDatapipe != null) { snapDatapipe.Close(); snapDatapipe.Dispose(); } if (archDatapipe != null) { archDatapipe.Close(); archDatapipe.Dispose(); } return; } Console.WriteLine("Subscribed Points (current value): "); //foreach (var p in pointsList) //{ // Console.WriteLine($"{p.Name,-12}, {p.EndOfStream().Timestamp}, {p.EndOfStream()}"); //} AFListResults <PIPoint, AFValue> results = pointsList.EndOfStream(); if (results.HasErrors) { foreach (var e in results.Errors) { Console.WriteLine($"{e.Key}: {e.Value}"); } } foreach (var v in results.Results) { if (!results.Errors.ContainsKey(v.PIPoint)) { Console.WriteLine($"{v.PIPoint.Name,-12}, {v.Timestamp}, {v.Value}"); } } Console.WriteLine(new string('-', 45)); //Fetch events from the data pipes while (!GlobalConfig.CancelSignups) { if (snapSubscribe) { snapDatapipe.GetObserverEvents(GlobalConfig.PipeMaxEvtCount, out bool hasMoreEvents1); } if (archSubscribe) { archDatapipe.GetObserverEvents(GlobalConfig.PipeMaxEvtCount, out bool hasMoreEvents2); } Thread.Sleep(GlobalConfig.PipeCheckFreq); } Console.WriteLine("Cancelling signups ..."); if (snapDatapipe != null) { snapDatapipe.Close(); snapDatapipe.Dispose(); } if (archDatapipe != null) { archDatapipe.Close(); archDatapipe.Dispose(); } } break; } Console.WriteLine(new string('~', 45)); } catch (Exception ex) { ParseArgs.PrintHelp(ex.Message); if (myServer != null) { myServer.Disconnect(); if (GlobalConfig.Debug) { Console.WriteLine($"Disconnecting from {myServer.Name}"); } } } }
public void PiInsert(string Product, DataTable dt) { //**********************Insert records into pi******************************************** try { LabEntities db = new LabEntities(); PIServers myPIServers = new PIServers(); PIServer myPIServer = myPIServers.DefaultPIServer; NetworkCredential credential = new NetworkCredential("labserver", "labserver1"); myPIServer.Connect(credential); Dictionary <string, decimal?> piTagValues = new Dictionary <string, decimal?>(); var PiTaglist = (from v in db.Lab_TagTable orderby v.Id select v).Skip(39).Take(44); var date = Convert.ToDateTime(Session["alumina_date"].ToString()); int utc = DateTime.UtcNow.Hour; int dt_ = DateTime.Now.Hour; bool dst = DSTcheck(); if (dst) { dt_ = dt_ - 1; } int diff; if (utc > dt_) { diff = utc - dt_; } else { diff = utc + 24 - dt_; } //type is not feed moisture if (Product == "ALUMINA") { //string s = type.Substring(0, type.Length - 4); //string input = type.Substring(type.Length - 4); //int time = Convert.ToInt16(input.TrimEnd('0')); //DateTime datetime; //TimeSpan ts; //if (time == 24) //{ // ts = new TimeSpan(23, 59, 59); //} //else ts = new TimeSpan(time, 0, 0); //datetime = date + ts; //decimal? s = (decimal?)null; //bool nulloremtpy = string.IsNullOrWhiteSpace(dt.Rows[0]["value"].ToString()); piTagValues.Add("LABALUMINA_LOI", string.IsNullOrWhiteSpace(dt.Rows[0]["value"].ToString()) ? (decimal?)null : Convert.ToDecimal(dt.Rows[0]["value"].ToString())); piTagValues.Add("LABALUMINA_P100", string.IsNullOrWhiteSpace(dt.Rows[1]["value"].ToString()) ? (decimal?)null : Convert.ToDecimal(dt.Rows[1]["value"].ToString())); piTagValues.Add("LABALUMINA_P200", string.IsNullOrWhiteSpace(dt.Rows[2]["value"].ToString()) ? (decimal?)null : Convert.ToDecimal(dt.Rows[2]["value"].ToString())); piTagValues.Add("LABALUMINA_P325", string.IsNullOrWhiteSpace(dt.Rows[3]["value"].ToString()) ? (decimal?)null : Convert.ToDecimal(dt.Rows[3]["value"].ToString())); piTagValues.Add("LABALUMINA_BULKDENS", string.IsNullOrWhiteSpace(dt.Rows[4]["value"].ToString()) ? (decimal?)null : Convert.ToDecimal(dt.Rows[4]["value"].ToString())); piTagValues.Add("LABALUMINA_SI", string.IsNullOrWhiteSpace(dt.Rows[5]["value"].ToString()) ? (decimal?)null : Convert.ToDecimal(dt.Rows[5]["value"].ToString())); piTagValues.Add("LABALUMINA_FE", string.IsNullOrWhiteSpace(dt.Rows[6]["value"].ToString()) ? (decimal?)null : Convert.ToDecimal(dt.Rows[6]["value"].ToString())); piTagValues.Add("LABALUMINA_NA", string.IsNullOrWhiteSpace(dt.Rows[7]["value"].ToString()) ? (decimal?)null : Convert.ToDecimal(dt.Rows[7]["value"].ToString())); piTagValues.Add("LABALUMINA_ZN", string.IsNullOrWhiteSpace(dt.Rows[8]["value"].ToString()) ? (decimal?)null : Convert.ToDecimal(dt.Rows[8]["value"].ToString())); piTagValues.Add("LABALUMINA_MN", string.IsNullOrWhiteSpace(dt.Rows[9]["value"].ToString()) ? (decimal?)null : Convert.ToDecimal(dt.Rows[9]["value"].ToString())); piTagValues.Add("LABALUMINA_CA", string.IsNullOrWhiteSpace(dt.Rows[10]["value"].ToString()) ? (decimal?)null : Convert.ToDecimal(dt.Rows[10]["value"].ToString())); piTagValues.Add("LABALUMINA_TI", string.IsNullOrWhiteSpace(dt.Rows[11]["value"].ToString()) ? (decimal?)null : Convert.ToDecimal(dt.Rows[11]["value"].ToString())); piTagValues.Add("LABALUMINA_AI", string.IsNullOrWhiteSpace(dt.Rows[12]["value"].ToString()) ? (decimal?)null : Convert.ToDecimal(dt.Rows[12]["value"].ToString())); piTagValues.Add("LABALUMINA_M20", string.IsNullOrWhiteSpace(dt.Rows[13]["value"].ToString()) ? (decimal?)null : Convert.ToDecimal(dt.Rows[13]["value"].ToString())); foreach (KeyValuePair <string, decimal?> entry in piTagValues) { foreach (var item in PiTaglist) { string TagName = item.Pi_Tags_Test.Substring(0, item.Pi_Tags_Test.Length - 5); string TagName_test = item.Pi_Tags_Test; if (TagName == entry.Key) { //PIPoint myPIPoint = PIPoint.FindPIPoint(myPIServer, TagName_test); PIPoint myPIPoint = PIPoint.FindPIPoint(myPIServer, TagName); //use this when go to production AFValue currentTag = myPIPoint.CurrentValue(); currentTag.Value = Convert.ToString(entry.Value); //string ctv = currentTag.Value.ToString(); //DateTime cttimestamp = currentTag.Timestamp; //DateTime d = cttimestamp.Date; currentTag.Timestamp = date.AddHours(diff); if (!string.IsNullOrEmpty(currentTag.Value.ToString())) { //if (ctv != null && d != date) //{ myPIPoint.UpdateValue(currentTag, AFUpdateOption.Insert); //} //else //{ // currentTag.Timestamp = date.AddHours(diff); // myPIPoint.UpdateValue(currentTag, AFUpdateOption.Replace); //} } } } } } else if (Product == "HYDRATE") { piTagValues.Add("LABHYDRATE_P100", string.IsNullOrWhiteSpace(dt.Rows[0]["value"].ToString()) ? (decimal?)null : Convert.ToDecimal(dt.Rows[0]["value"].ToString())); piTagValues.Add("LABHYDRATE_P200", string.IsNullOrWhiteSpace(dt.Rows[1]["value"].ToString()) ? (decimal?)null : Convert.ToDecimal(dt.Rows[1]["value"].ToString())); piTagValues.Add("LABHYDRATE_P325", string.IsNullOrWhiteSpace(dt.Rows[2]["value"].ToString()) ? (decimal?)null : Convert.ToDecimal(dt.Rows[2]["value"].ToString())); piTagValues.Add("LABHYDRATE_SI", string.IsNullOrWhiteSpace(dt.Rows[3]["value"].ToString()) ? (decimal?)null : Convert.ToDecimal(dt.Rows[3]["value"].ToString())); piTagValues.Add("LABHYDRATE_FE", string.IsNullOrWhiteSpace(dt.Rows[4]["value"].ToString()) ? (decimal?)null : Convert.ToDecimal(dt.Rows[4]["value"].ToString())); piTagValues.Add("LABHYDRATE_NA", string.IsNullOrWhiteSpace(dt.Rows[5]["value"].ToString()) ? (decimal?)null : Convert.ToDecimal(dt.Rows[5]["value"].ToString())); piTagValues.Add("LABHYDRATE_ZN", string.IsNullOrWhiteSpace(dt.Rows[6]["value"].ToString()) ? (decimal?)null : Convert.ToDecimal(dt.Rows[6]["value"].ToString())); piTagValues.Add("LABHYDRATE_MN", string.IsNullOrWhiteSpace(dt.Rows[7]["value"].ToString()) ? (decimal?)null : Convert.ToDecimal(dt.Rows[7]["value"].ToString())); piTagValues.Add("LABHYDRATE_CA", string.IsNullOrWhiteSpace(dt.Rows[8]["value"].ToString()) ? (decimal?)null : Convert.ToDecimal(dt.Rows[8]["value"].ToString())); piTagValues.Add("LABHYDRATE_TI", string.IsNullOrWhiteSpace(dt.Rows[9]["value"].ToString()) ? (decimal?)null : Convert.ToDecimal(dt.Rows[9]["value"].ToString())); piTagValues.Add("LABHYDRATE_AI", string.IsNullOrWhiteSpace(dt.Rows[10]["value"].ToString()) ? (decimal?)null : Convert.ToDecimal(dt.Rows[10]["value"].ToString())); piTagValues.Add("LABHYDRATE_FREEMOIST", string.IsNullOrWhiteSpace(dt.Rows[11]["value"].ToString()) ? (decimal?)null : Convert.ToDecimal(dt.Rows[11]["value"].ToString())); piTagValues.Add("LABHYDRATE_CSEDS", string.IsNullOrWhiteSpace(dt.Rows[12]["value"].ToString()) ? (decimal?)null : Convert.ToDecimal(dt.Rows[12]["value"].ToString())); piTagValues.Add("LABHYDRATE_INSOLS", string.IsNullOrWhiteSpace(dt.Rows[13]["value"].ToString()) ? (decimal?)null : Convert.ToDecimal(dt.Rows[13]["value"].ToString())); piTagValues.Add("LABHYDRATE_BULKDENS", string.IsNullOrWhiteSpace(dt.Rows[14]["value"].ToString()) ? (decimal?)null : Convert.ToDecimal(dt.Rows[14]["value"].ToString())); piTagValues.Add("LABHYDRATE_HUNTERL", string.IsNullOrWhiteSpace(dt.Rows[15]["value"].ToString()) ? (decimal?)null : Convert.ToDecimal(dt.Rows[15]["value"].ToString())); piTagValues.Add("LABHYDRATE_HUNTERA", string.IsNullOrWhiteSpace(dt.Rows[16]["value"].ToString()) ? (decimal?)null : Convert.ToDecimal(dt.Rows[16]["value"].ToString())); piTagValues.Add("LABHYDRATE_HUNTERB", string.IsNullOrWhiteSpace(dt.Rows[17]["value"].ToString()) ? (decimal?)null : Convert.ToDecimal(dt.Rows[17]["value"].ToString())); foreach (KeyValuePair <string, decimal?> entry in piTagValues) { foreach (var item in PiTaglist) { string TagName = item.Pi_Tags_Test.Substring(0, item.Pi_Tags_Test.Length - 5); string TagName_test = item.Pi_Tags_Test; if (TagName == entry.Key) { //PIPoint myPIPoint = PIPoint.FindPIPoint(myPIServer, TagName_test); PIPoint myPIPoint = PIPoint.FindPIPoint(myPIServer, TagName); // use this when go to production AFValue currentTag = myPIPoint.CurrentValue(); currentTag.Value = Convert.ToString(entry.Value); //string ctv = currentTag.Value.ToString(); //DateTime cttimestamp = currentTag.Timestamp; //DateTime d = cttimestamp.Date; currentTag.Timestamp = date.AddHours(diff); if (!string.IsNullOrEmpty(currentTag.Value.ToString())) { //if (ctv != null && d != date) //{ // currentTag.Timestamp = date.AddHours(diff); myPIPoint.UpdateValue(currentTag, AFUpdateOption.Insert); // } // else // { // currentTag.Timestamp = date.AddHours(diff); // myPIPoint.UpdateValue(currentTag, AFUpdateOption.Replace); // } } } } } } else { piTagValues.Add("LABWETHYDRATE_P100", string.IsNullOrWhiteSpace(dt.Rows[0]["value"].ToString()) ? (decimal?)null : Convert.ToDecimal(dt.Rows[0]["value"].ToString())); piTagValues.Add("LABWETHYDRATE_P200", string.IsNullOrWhiteSpace(dt.Rows[1]["value"].ToString()) ? (decimal?)null : Convert.ToDecimal(dt.Rows[1]["value"].ToString())); piTagValues.Add("LABWETHYDRATE_P325", string.IsNullOrWhiteSpace(dt.Rows[2]["value"].ToString()) ? (decimal?)null : Convert.ToDecimal(dt.Rows[2]["value"].ToString())); piTagValues.Add("LABWETHYDRATE_SI", string.IsNullOrWhiteSpace(dt.Rows[3]["value"].ToString()) ? (decimal?)null : Convert.ToDecimal(dt.Rows[3]["value"].ToString())); piTagValues.Add("LABWETHYDRATE_FE", string.IsNullOrWhiteSpace(dt.Rows[4]["value"].ToString()) ? (decimal?)null : Convert.ToDecimal(dt.Rows[4]["value"].ToString())); piTagValues.Add("LABWETHYDRATE_NA", string.IsNullOrWhiteSpace(dt.Rows[5]["value"].ToString()) ? (decimal?)null : Convert.ToDecimal(dt.Rows[5]["value"].ToString())); piTagValues.Add("LABWETHYDRATE_ZN", string.IsNullOrWhiteSpace(dt.Rows[6]["value"].ToString()) ? (decimal?)null : Convert.ToDecimal(dt.Rows[6]["value"].ToString())); piTagValues.Add("LABWETHYDRATE_MN", string.IsNullOrWhiteSpace(dt.Rows[7]["value"].ToString()) ? (decimal?)null : Convert.ToDecimal(dt.Rows[7]["value"].ToString())); piTagValues.Add("LABWETHYDRATE_CA", string.IsNullOrWhiteSpace(dt.Rows[8]["value"].ToString()) ? (decimal?)null : Convert.ToDecimal(dt.Rows[8]["value"].ToString())); piTagValues.Add("LABWETHYDRATE_TI", string.IsNullOrWhiteSpace(dt.Rows[9]["value"].ToString()) ? (decimal?)null : Convert.ToDecimal(dt.Rows[9]["value"].ToString())); piTagValues.Add("LABWETHYDRATE_CSEDS", string.IsNullOrWhiteSpace(dt.Rows[10]["value"].ToString()) ? (decimal?)null : Convert.ToDecimal(dt.Rows[10]["value"].ToString())); piTagValues.Add("LABWETHYDRATE_INSOLS", string.IsNullOrWhiteSpace(dt.Rows[11]["value"].ToString()) ? (decimal?)null : Convert.ToDecimal(dt.Rows[11]["value"].ToString())); foreach (KeyValuePair <string, decimal?> entry in piTagValues) { foreach (var item in PiTaglist) { string TagName = item.Pi_Tags_Test.Substring(0, item.Pi_Tags_Test.Length - 5); string TagName_test = item.Pi_Tags_Test; if (TagName == entry.Key) { // PIPoint myPIPoint = PIPoint.FindPIPoint(myPIServer, TagName_test); PIPoint myPIPoint = PIPoint.FindPIPoint(myPIServer, TagName); // use this when go to production AFValue currentTag = myPIPoint.CurrentValue(); currentTag.Value = Convert.ToString(entry.Value); //string ctv = currentTag.Value.ToString(); //DateTime cttimestamp = currentTag.Timestamp; //DateTime d = cttimestamp.Date; currentTag.Timestamp = date.AddHours(diff); if (!string.IsNullOrEmpty(currentTag.Value.ToString())) { //if (ctv != null && d != date) //{ myPIPoint.UpdateValue(currentTag, AFUpdateOption.Insert); //} //else //{ // currentTag.Timestamp = date.AddHours(diff); // myPIPoint.UpdateValue(currentTag, AFUpdateOption.Replace); //} } } } } } myPIServer.Disconnect(); } catch (Exception ex) { } //*************************End******************************* }
public void PiInsert(string area, DataTable dt) { //**********************Insert records into pi******************************************** try { LabEntities db = new LabEntities(); PIServers myPIServers = new PIServers(); PIServer myPIServer = myPIServers.DefaultPIServer; NetworkCredential credential = new NetworkCredential("labserver", "labserver1"); myPIServer.Connect(credential); var date = Convert.ToDateTime(Session["sec3_date"].ToString()); int utc = DateTime.UtcNow.Hour; int dt_ = DateTime.Now.Hour; bool dst = DSTcheck(); if (dst) { dt_ = dt_ - 1; } int diff; if (utc > dt_) { diff = utc - dt_; } else { diff = utc + 24 - dt_; } if (area == "caustic_clean") { var PiTagList = (from v in db.Lab_TagTable where v.Tag_Name == area orderby v.Max, v.Min select v).ToList(); DataTable dt_copy = new DataTable(); dt_copy = dt.Copy(); dt_copy.Columns.RemoveAt(0); dt_copy.Columns.RemoveAt(3); for (int i = 0; i < dt_copy.Rows.Count; i++) { for (int j = 0; j < dt_copy.Columns.Count; j++) { string TagName = PiTagList[j].Pi_Tags; string TagName_test = PiTagList[j].Pi_Tags_Test;; { //PIPoint myPIPoint = PIPoint.FindPIPoint(myPIServer, TagName_test); PIPoint myPIPoint = PIPoint.FindPIPoint(myPIServer, TagName); //-- use this when go to production AFValue currentTag = myPIPoint.CurrentValue(); currentTag.Timestamp = date; currentTag.Value = Convert.ToString(dt_copy.Rows[i][j]); string ctv = currentTag.Value.ToString(); DateTime cttimestamp = currentTag.Timestamp; DateTime d = cttimestamp.Date; if (!string.IsNullOrEmpty(currentTag.Value.ToString())) { currentTag.Value = Convert.ToString(dt_copy.Rows[i][j]); currentTag.Timestamp = date.AddHours(diff + i); myPIPoint.UpdateValue(currentTag, AFUpdateOption.Insert); } } } } } else { var PiTagList = (from v in db.Lab_TagTable where v.Tag_Name == area orderby v.Max, v.Min select v).ToList(); DataTable dt_copy = new DataTable(); dt_copy = dt.Copy(); dt_copy.Columns.RemoveAt(0); dt_copy.Columns.RemoveAt(0); { for (int i = 0; i < dt_copy.Rows.Count; i++) { for (int j = 0; j < dt_copy.Columns.Count; j++) { //string TagName = item.Pi_Tags_Test.Substring(0, item.Pi_Tags_Test.Length - 5); //string TagName_test = item.Pi_Tags_Test; //int g; //if (i != 0) //{ // g = (8 * i) + j; //} //else // g = j; if (area == "st_topsamples" || area == "tt_topsamples") { TagName = PiTagList[j].Pi_Tags; TagName_test = PiTagList[j].Pi_Tags_Test;; } else { int g; if (i != 0) { g = (8 * i) + j; TagName = PiTagList[g].Pi_Tags; TagName_test = PiTagList[g].Pi_Tags_Test; } else { TagName = PiTagList[j].Pi_Tags; TagName_test = PiTagList[j].Pi_Tags_Test; } } { //PIPoint myPIPoint = PIPoint.FindPIPoint(myPIServer, TagName_test); PIPoint myPIPoint = PIPoint.FindPIPoint(myPIServer, TagName); //-- use this when go to production AFValue currentTag = myPIPoint.CurrentValue(); string s = Convert.ToString(dt_copy.Rows[i][j]); currentTag.Value = Convert.ToString(dt_copy.Rows[i][j]); currentTag.Timestamp = date.AddHours(diff); if (!string.IsNullOrEmpty(currentTag.Value.ToString())) { myPIPoint.UpdateValue(currentTag, AFUpdateOption.Insert); } } } } } myPIServer.Disconnect(); } } catch (Exception exs) { string filePath = @"C:\Error.txt"; using (StreamWriter writer = new StreamWriter(filePath, true)) { writer.WriteLine("Message :" + exs.Message + "<br/>" + Environment.NewLine + "StackTrace :" + exs.StackTrace + "" + Environment.NewLine + "Date :" + DateTime.Now.ToString()); writer.WriteLine(Environment.NewLine + "-----------------------------------------------------------------------------" + Environment.NewLine); } } //*************************End******************************* }