0% found this document useful (0 votes)
198 views17 pages

Code Co Pack

This document contains C# code for a Windows Forms application that reads archived process data from a SQL Server database. It defines classes and methods for connecting to the database, selecting archive types (tags, alarms, user archives), reading tag information and IDs, and changing the enabled/visible state of form controls based on archive type selection. The main form initializes components, starts a loading form in a new thread, and handles loading and database connection events.

Uploaded by

Black Win
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
198 views17 pages

Code Co Pack

This document contains C# code for a Windows Forms application that reads archived process data from a SQL Server database. It defines classes and methods for connecting to the database, selecting archive types (tags, alarms, user archives), reading tag information and IDs, and changing the enabled/visible state of form controls based on archive type selection. The main form initializes components, starts a loading form in a new thread, and handles loading and database connection events.

Uploaded by

Black Win
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 17

using System;

using System.IO;
//using System.Collections.Generic;
//using System.ComponentModel;
using System.Data;
using System.Data.OleDb; //
using System.Data.SqlClient;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;
namespace appCopack
{
public partial class Form1 : Form
{
// selection archive type; 1=Tag Logging, 2=Alarm Logging, 3 User Archiv
es
int iArchiveSel = 0;
bool CrystalReportInstalled = false;
//
string szValueName;
string mySelectQuery = "";
System.DateTime localDateTimeFrom;
System.DateTime localDateTimeTo;
System.DateTime univDateTimeFrom;
System.DateTime univDateTimeTo;
OleDbConnection myConnection;
OleDbDataAdapter myAdapter;
DataTable myTableAlarms;
DataTable myTableAlarmsModify;
DataTable myTableTags;
DataTable myTableTagsModify;
DataTable myTableProducts;

Form_Start frmStarting = new Form_Start();
Thread StartingThread;

public static ManualResetEvent mre = new ManualResetEvent(false);

//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+++++++++++++++++++++++++++++++++
//++ funktions
++
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+++++++++++++++++++++++++++++++++
//################################################################
//#### Form1() ##
//################################################################

///==========================================
/// <summary>
/// Starr the "Starting"-Window in own thread
///
/// </summary>
public void StartingForm()
{
Thread.BeginThreadAffinity();
frmStarting.ShowDialog();
Thread.EndThreadAffinity();
}
//################################################################
//#### Form1() ##
//################################################################

///==========================================
/// <summary>
/// Configuration of first start
///
/// Initialize all objects of Form1 and
/// Set default values
/// </summary>
public Form1()
{
// Start the StartingForm
StartingThread = new Thread(new ThreadStart(this.StartingForm));
StartingThread.Start(); // Start the StartingForm

// Initialize all objects of Form1
InitializeComponent();// Initialize all objects of Form1


}
private void Form1_Load(object sender, EventArgs e)
{
try
{
TabPage CRTab = new myTabPageCR();
tabView.TabPages.Add(CRTab);
CrystalReportInstalled = true;
}
catch (Exception ex)
{
TabPage CRTab = new Error_CR();
tabView.TabPages.Add(CRTab);

MessageBox.Show("#E001: Warning caused by Crystal Report initial
iziing.\n"
+"Please install Crystal Report\n\n"
+"Crystal Report is not available for this sessi
on",
"Crystal Report WARNING",MessageBoxButtons.OK,Me
ssageBoxIcon.Warning);
CrystalReportInstalled = false;
}


//--------------------------------
// presets for Test-Environment
//--------------------------------
// data source name
txtCatalog.Text = "CC_DIEU_KHI_14_05_04_08_11_05R";
// name of WinCC-Server and instance of SQL-Server
txtSource.Text = "BLACKWIN\\WINCC";
txtUid.Text = "BLACKWIN";
txtPwd.Text = "080292";
// Provider
txtProvider.Text = "WinCCOLEDBProvider";
// data in between dtpFrom and dtpTo
dtpFrom.Format = DateTimePickerFormat.Custom;
dtpFrom.CustomFormat = "dd.MM.yyyy HH:mm:ss";
// dtpFrom.Value = DateTime.Now.AddHours(-1);
dtpFrom.Value = DateTime.Now.AddDays(-1);
dtpTo.Format = DateTimePickerFormat.Custom;
dtpTo.CustomFormat = "dd.MM.yyyy HH:mm:ss";
dtpTo.Value = DateTime.Now;
//Disable all parts
grpDataSelection.Enabled = false;
grpExport.Enabled = false;
grpTimeInterval.Enabled = false;
btnRead.Enabled = false;
myGrid.Visible = false;
//
// Tags: choisable Interval-Type
dblArray[] interpolArray = new dblArray[]
{
new dblArray("Without Aggreg.",0),
new dblArray("FIRST",1), new dblArray("LAST",2),
new dblArray("MIN",3), new dblArray("MAX",4),
new dblArray("AVG",5), new dblArray("SUM",6),
new dblArray("COUNT",7),
new dblArray("FIRST_INTERPOLATED",257), new dblArray("LAST_INTER
POLATED",258),
new dblArray("MIN_INTERPOLATED",259), new dblArray("MAX_INTERPOL
ATED",260),
new dblArray("AVG_INTERPOLATED",261), new dblArray("SUM_INTERPOL
ATED",262),
new dblArray("COUNT_INTERPOLATED",263)
};
cmbInterpol.DataSource = interpolArray;
cmbInterpol.ValueMember = "No";
cmbInterpol.DisplayMember = "Name";
StartingThread.Abort(); // Terminate the StartingForm
}
//################################################################
//#### ChangeComponent() ##
//################################################################
//=========================================
/// <summary>
/// enable/disabel the needed groups and fill the Data Selection
///
/// triggered by Button "connect to database"
/// of group "Archive"
///
/// </summary>
//=========================================
public void ChangeComponent()
{
//--------------------------------
//iArchiveSel
//--------------------------------
switch (iArchiveSel)
{
case 1: //Tag Logging
grpDataSelection.Enabled = true;
if (TLG_Archive() == 0) // read all prozess values without
{
grpTimeInterval.Enabled = true;
btnRead.Enabled = true;
myGrid.Visible = true;
}
break;
case 2: //Alarm Logging
grpDataSelection.Enabled = false;
btnRead.Enabled = true;
grpTimeInterval.Enabled = true;
break;
case 3: //User Archives
grpDataSelection.Enabled = false;
grpTimeInterval.Enabled = false;
btnRead.Enabled = true;
break;
default:
grpDataSelection.Enabled = false;
grpTimeInterval.Enabled = false;
btnRead.Enabled = false;
break;
}//switch (iArchiveSel)
}//ChangeComponent()
//################################################################
//#### TLG_Archive() ##
//################################################################
//=========================================
/// <summary>
/// reading IDs/Names of archived Tags
///
/// access by OleDB of SQL-Server
/// needed for the choise of archived Tag
/// </summary>
//=========================================
public int TLG_Archive()
{
try
{
tagInfos ti = new tagInfos("Provider=SQLOLEDB; Data Source =" +
txtSource.Text + "; uid=" + txtUid.Text + "; pwd=" + txtPwd.Text + "; Initial Ca
talog = " + txtCatalog.Text + ";");

cmbTags.DataSource = ti.getTaginfos();
cmbTags.ValueMember = "ValueID";
cmbTags.DisplayMember = "ValueName";
return (0);
} // try
catch (Exception)
{
//MessageBox.Show("#108-1 TLGArchive() faild...");
return (-1);
}// catch
}//TLG_Archive
//################################################################
//#### TLG_ArchiveGetID ##
//################################################################
public int TLG_ArchiveGetID(String strValueName)
{
string myConnectionString = "Provider=SQLOLEDB; Data Source =" + txt
Source.Text + "; uid=" + txtUid.Text + "; pwd=" + txtPwd.Text + "; Initial Catal
og = " + txtCatalog.Text + ";";
myTableTags = new DataTable();
string mySelectQuery = "SELECT * FROM Archive";
//------------
try
{
using (OleDbCommand myCommand = new OleDbCommand(mySelectQuery))
{
// Connection Archive-Database
myConnection = new OleDbConnection(myConnectionString);
myCommand.Connection = myConnection;
myAdapter = new OleDbDataAdapter(myCommand);
//
// Providing data for loop throug data table, data grid
myTableTags.TableName = "myTableTags";
myAdapter.Fill(myTableTags);
myGrid.DataSource = myTableTags;
lbl_AnzArchTag.Text = (myGrid.RowCount-1).ToString() + " Arc
hive-Tags found";
myConnection.Close();
//
//Loop through DataTable by DataRow
//
foreach (DataRow row in myTableTags.Rows)
{
// strLine = String.Format("{0}; {1}; {2:F3}; {3}; {4}"
, row[0], row[1], row[2], row[3], row[4]);
// streamTagLogging.WriteLine(strLine);
}//DataRow
}
return (myGrid.RowCount);
}
catch (Exception)
{
return (-1);
}
}//TLG_ArchiveGetID()
//################################################################
//#### TLG_Connect ##
//################################################################

///==========================================
/// <Connect to Database / Tags>
///
/// <connecting to database by OleDB-Provider of WinCC>
/// <reading data-rows by Data-Adapter>
/// <providing these rows in Data-Table for Datagrid>
/// <providing these rows in Data-Table for Report>
/// <aktivating of Crystal-Report>
///
/// <param name="mySelectQuery"></param>
/// <returns><Counter Rows/-1>
///==========================================
public int TLG_Connect(string mySelectQuery)
{
//StreamWriter streamTagLogging = null;
//string strLine = "";
//string strExportFile = "";
string myConnectionString = "Provider=" + txtProvider.Text + "; Data
Source =" + txtSource.Text + "; Catalog = " + txtCatalog.Text + ";";
myGrid.Name = "Tags";
myTableTags = new DataTable();
myTableTagsModify = new DataTable();
System.DateTime localDateTime;
//System.DateTime univDateTime;
//==============================================================
//
//Adding Columns and Rows to Data Table myTableTagsModify
//
//==============================================================
//
DataColumn newColumn = new DataColumn("localTimestamp", System.Type.
GetType("System.String"));
newColumn.Caption = "localTimestamp";
newColumn.DefaultValue = string.Empty;
myTableTagsModify.Columns.Add(newColumn);
//
newColumn = new DataColumn("RealValue", System.Type.GetType("System.
String"));
newColumn.Caption = "RealValue";
newColumn.DefaultValue = string.Empty;
myTableTagsModify.Columns.Add(newColumn);
//
newColumn = new DataColumn("Quality", System.Type.GetType("System.St
ring"));
newColumn.Caption = "Quality";
newColumn.DefaultValue = string.Empty;
myTableTagsModify.Columns.Add(newColumn);
//
newColumn = new DataColumn("Flags", System.Type.GetType("System.Stri
ng"));
newColumn.Caption = "Flags";
newColumn.DefaultValue = string.Empty;
myTableTagsModify.Columns.Add(newColumn);
//
newColumn = new DataColumn("ValueID", System.Type.GetType("System.St
ring"));
newColumn.AllowDBNull = false;
newColumn.Caption = "ValueID";
newColumn.DefaultValue = string.Empty;
myTableTagsModify.Columns.Add(newColumn);
//
newColumn = new DataColumn("ValueName", System.Type.GetType("System.
String"));
newColumn.Caption = "ValueName";
newColumn.DefaultValue = string.Empty;
myTableTagsModify.Columns.Add(newColumn);
//
newColumn = new DataColumn("localDateTimeFrom", System.Type.GetType(
"System.String"));
newColumn.Caption = "localDateTimeFrom";
newColumn.DefaultValue = string.Empty;
myTableTagsModify.Columns.Add(newColumn);
//
newColumn = new DataColumn("localDateTimeTo", System.Type.GetType("S
ystem.String"));
newColumn.Caption = "localDateTimeTo";
newColumn.DefaultValue = string.Empty;
myTableTagsModify.Columns.Add(newColumn);
//
newColumn = new DataColumn("univDateTimeFrom", System.Type.GetType("
System.String"));
newColumn.Caption = "univDateTimeFrom";
newColumn.DefaultValue = string.Empty;
myTableTagsModify.Columns.Add(newColumn);
//
newColumn = new DataColumn("univDateTimeTo", System.Type.GetType("Sy
stem.String"));
newColumn.Caption = "univDateTimeTo";
newColumn.DefaultValue = string.Empty;
myTableTagsModify.Columns.Add(newColumn);

//------------
try
{
using (OleDbCommand myCommand = new OleDbCommand(mySelectQuery))
{
// Connection Archive-Database
myConnection = new OleDbConnection(myConnectionString);
myCommand.Connection = myConnection;
myAdapter = new OleDbDataAdapter(myCommand);
//
// Providing data for Data-Grid
//
myTableTags.TableName = "myTableTags";
myTableTagsModify.TableName = "myTableTagsModify";
myAdapter.Fill(myTableTags);
//
//modify DataTable
//
myTableTagsModify.Clear();
foreach (DataRow row in myTableTags.Rows)
{
DataRow newRow = myTableTagsModify.NewRow();

//covert to local time
localDateTime = System.DateTime.Parse(row["Timestamp"].T
oString());
localDateTime = localDateTime.ToLocalTime();
newRow["localTimestamp"] = localDateTime.ToString();
newRow["RealValue"] = (String.Format("{0:F3}", row["Real
Value"])).PadLeft(20);
newRow["Quality"] = String.Format("0x{0:X}", row["Qualit
y"]).PadLeft(10);
newRow["Flags"] = String.Format("0x{0:X}", row["Flags"])
.PadLeft(10);
newRow["ValueID"] = row["ValueID"];
newRow["ValueName"] = szValueName;
newRow["localDateTimeFrom"] = localDateTimeFrom;
newRow["localDateTimeTo"] = localDateTimeTo;
newRow["univDateTimeFrom"] = univDateTimeFrom;
newRow["univDateTimeTo"] = univDateTimeTo;
myTableTagsModify.Rows.Add(newRow);
}//foreach(DataRow)


myGrid.DataSource = myTableTagsModify;
// myGrid.DataSource = myTableTags;

//
lblAnzEntries.Text = myGrid.RowCount.ToString() + " Rows fou
nd";
myConnection.Close();
if (CrystalReportInstalled)
{
// Update Crystal-Report
myTabPageCR ArchivCR = (myTabPageCR)tabView.TabPages["my
TabPageCR"];
ArchivCR.ShowInCristalReport(iArchiveSel, myTableTagsMod
ify);
}//if (CrystalReportInstalled)
}
return (myGrid.RowCount);
}
catch (Exception ex)
{
MessageBox.Show("#E110: TLG_Connect() - Failed connect to the d
atabase.\n"
+ "WinCC Connectivity Pack required"
+ "{0}" + ex.Message, "Failed connect to the dat
abase", MessageBoxButtons.OK, MessageBoxIcon.Error);
return (-1);
}
}//TLG_Connect()
//################################################################
//#### UA_Connect ##
//################################################################

///==========================================
/// <summary>
/// Connect to Database / User Archiv
///
/// connecting to database by OleDB-Provider of WinCC
/// </summary>
public int UA_Connect(string mySelectQuery)
{
string myConnectionString = "Provider=SQLOLEDB; Data Source =" + txt
Source.Text + "; uid=" + txtUid.Text + "; pwd=" + txtPwd.Text + "; Initial Catal
og = " + txtCatalog.Text + ";";
myTableProducts = new DataTable();
//------------
try
{
using (OleDbCommand myCommand = new OleDbCommand(mySelectQuery))
{
// Connection Archive-Database
myConnection = new OleDbConnection(myConnectionString);
myCommand.Connection = myConnection;
myAdapter = new OleDbDataAdapter(myCommand);
//
// Providing data for loop throug data table, data grid
myTableProducts.TableName = "myTableProducts";
myAdapter.Fill(myTableProducts);
myGrid.DataSource = myTableProducts;
myConnection.Close();
lblAnzEntries.Text = (myGrid.RowCount-1).ToString() + " Rows
found";
if (CrystalReportInstalled)
{
// Update Crystal-Report
myTabPageCR ArchivCR = (myTabPageCR)tabView.TabPages["my
TabPageCR"];
ArchivCR.ShowInCristalReport(iArchiveSel, myTableProduct
s);
}//if (CrystalReportInstalled)
}
return (myGrid.RowCount);
}
catch (Exception ex)
{
MessageBox.Show("#E310: UA_Connect() - Failed connect to the da
tabase.\n{0}" + ex.Message, "Failed connect to the database", MessageBoxButtons.
OK, MessageBoxIcon.Error);
return (-1);
}
}//UA_Connect()
//################################################################
//#### ALG_Connect(string mySelectQuery) ##
//################################################################

///==========================================
/// <summary>
/// Connect to Database / Alarms>
///
/// connecting to database by OleDB-Provider of WinCC
/// reading data-rows by Data-Adapter
/// providing these rows in Data-Table for Datagrid
/// providing these rows in Data-Table for Report
/// aktivating of Crystal-Report
/// </summary>
/// <param name="mySelectQuery"></param>
///==========================================
public int ALG_Connect(string mySelectQuery)
{
string myConnectionString = "Provider=" + txtProvider.Text
+ "; Data Source =" + txtSource.Text
+ "; Catalog = " + txtCatalog.Text + ";"
;
myGrid.Name = "Alarms";
myTableAlarms = new DataTable();
myTableAlarmsModify = new DataTable();
System.DateTime localDateTime;
//System.DateTime univDateTime;
//==============================================================
//Adding Columns and Rows to Data Table myTableAlarmsModify
//==============================================================
DataColumn newColumn = new DataColumn("localDateTime", System.Type.G
etType("System.String"));
newColumn.Caption = "localDateTime";
newColumn.DefaultValue = string.Empty;
myTableAlarmsModify.Columns.Add(newColumn);
//

newColumn = new DataColumn("MsgNr", System.Type.GetType("System.Stri
ng"));
newColumn.Caption = "MsgNr";
newColumn.DefaultValue = string.Empty;
myTableAlarmsModify.Columns.Add(newColumn);
//
newColumn = new DataColumn("State", System.Type.GetType("System.Stri
ng"));
newColumn.Caption = "State";
newColumn.DefaultValue = string.Empty;
myTableAlarmsModify.Columns.Add(newColumn);
//
newColumn = new DataColumn("Text1", System.Type.GetType("System.Stri
ng"));
newColumn.Caption = "Text1";
newColumn.DefaultValue = string.Empty;
myTableAlarmsModify.Columns.Add(newColumn);
//
newColumn = new DataColumn("Text3", System.Type.GetType("System.Stri
ng"));
newColumn.AllowDBNull = false;
newColumn.Caption = "Text3";
newColumn.DefaultValue = string.Empty;
myTableAlarmsModify.Columns.Add(newColumn);
//
newColumn = new DataColumn("localDateTimeFrom", System.Type.GetType(
"System.String"));
newColumn.Caption = "localDateTimeFrom";
newColumn.DefaultValue = string.Empty;
myTableAlarmsModify.Columns.Add(newColumn);
//
newColumn = new DataColumn("localDateTimeTo", System.Type.GetType("S
ystem.String"));
newColumn.Caption = "localDateTimeTo";
newColumn.DefaultValue = string.Empty;
myTableAlarmsModify.Columns.Add(newColumn);
//
newColumn = new DataColumn("univDateTimeFrom", System.Type.GetType("
System.String"));
newColumn.Caption = "univDateTimeFrom";
newColumn.DefaultValue = string.Empty;
myTableAlarmsModify.Columns.Add(newColumn);
//
newColumn = new DataColumn("univDateTimeTo", System.Type.GetType("Sy
stem.String"));
newColumn.Caption = "univDateTimeTo";
newColumn.DefaultValue = string.Empty;
myTableAlarmsModify.Columns.Add(newColumn);

try
{
using (OleDbCommand myCommand = new OleDbCommand(mySelectQuery))
{
// Connection Archive-Database
myConnection = new OleDbConnection(myConnectionString);
myCommand.Connection = myConnection;
myAdapter = new OleDbDataAdapter(myCommand);
// Providing data for Data-Grid
myTableAlarms.TableName = "myTableAlarms";
myTableAlarmsModify.TableName = "myTableAlarmsModify";
myAdapter.Fill(myTableAlarms);
// myAdapter.Fill(myTableAlarmsModify);
myTableAlarmsModify.Clear();

//
//modify DataTable
//
// myTableAlarmsModify = myTableAlarmsModify.select(SortOrder loca
lDateTime);
foreach (DataRow row in myTableAlarms.Rows)
{
string szState = "";
short iState;
DataRow newRow = myTableAlarmsModify.NewRow();
//covert to local time

localDateTime = System.DateTime.Parse(row["DateTime"].To
String());
localDateTime = localDateTime.ToLocalTime();
newRow["localDateTime"] = localDateTime.ToString();

newRow["MsgNr"] = (String.Format("{0}", row["MsgNr"])).P
adLeft(10);

//szState = String.Format("0x{0:X}", row["State"]).PadLe
ft(10);
iState = (short)(row["State"]);
switch (iState){
case 1:
szState = row["TxtCame"].ToString();
break;
case 2:
szState = row["TxtWent"].ToString();
break;
case 3:
szState = row["TxtAck"].ToString();
break;
case 16://0x10 (Quit System)
szState = row["TxtAck"].ToString();
break;
default:
szState = String.Format("0x{0:X}", row["State"])
.PadLeft(10);
break;
}//switch row["State"]
newRow["State"] = szState;
newRow["Text1"] = row["Text1"];
newRow["Text3"] = row["Text3"];
newRow["localDateTimeFrom"] = localDateTimeFrom;
newRow["localDateTimeTo"] = localDateTimeTo;
newRow["univDateTimeFrom"] = univDateTimeFrom;
newRow["univDateTimeTo"] = univDateTimeTo;
myTableAlarmsModify.Rows.Add(newRow);
}//foreach(DataRow)
myGrid.DataSource = myTableAlarmsModify;
myConnection.Close();
lblAnzEntries.Text = (myGrid.RowCount - 1).ToString() + " Ro
ws Found ";
if (CrystalReportInstalled)
{
// Update Crystal-Report
myTabPageCR ArchivCR = (myTabPageCR)tabView.TabPages["my
TabPageCR"];
ArchivCR.ShowInCristalReport(iArchiveSel, myTableAlarmsM
odify);
} //if (CrystalReportInstalled)
}
return (myGrid.RowCount);
}
catch (Exception ex)
{
MessageBox.Show("#E210: ALG_Connect() - Failed connect to the da
tabase.\n"
+ "WinCC Connectivity Pack required"
+ "\n{0}" + ex.Message, "Failed connect to the d
atabase", MessageBoxButtons.OK, MessageBoxIcon.Error);
return (-1);
}
}//ALG_Connect()
//################################################################
//#### GetData() ##
//################################################################

//==============================================
/// <summary>
/// get archived Data
///
/// depending on selected Archive: Alarms/Tags
/// creating select-statement, considering fro/to time
/// calling Fuction for access to database
/// </summary>
///==========================================
public void GetData()
{
string timeStep = "";

int cntData = 0;
//covert dtpFrom to universal time (utc)
localDateTimeFrom = dtpFrom.Value;
localDateTimeFrom = System.DateTime.Parse(localDateTimeFrom.ToString
());
univDateTimeFrom = localDateTimeFrom.ToUniversalTime();
string tfrom = dtpFrom.Value.Year.ToString() + "-"
+ string.Format("{0:MM}", univDateTimeFrom.Month.ToStrin
g()) + "-"
+ string.Format("{0:dd}", univDateTimeFrom.Day.ToString(
)) + " "
+ string.Format("{0:HH}", univDateTimeFrom.Hour.ToString
()) + ":"
+ string.Format("{0:mm}", univDateTimeFrom.Minute.ToStri
ng()) + ":"
+string.Format("{0:ss}", univDateTimeFrom.Second.ToStrin
g());
//covert dtpTo to universal time (utc)
localDateTimeTo = dtpTo.Value;
localDateTimeTo = System.DateTime.Parse(localDateTimeTo.ToString());
univDateTimeTo = localDateTimeTo.ToUniversalTime();
string tto = dtpTo.Value.Year.ToString() + "-"
+ string.Format("{0:MM}", univDateTimeTo.Month.ToString(
)) + "-"
+ string.Format("{0:dd}", univDateTimeTo.Day.ToString())
+ " "
+ string.Format("{0:HH}", univDateTimeTo.Hour.ToString()
) + ":"
+ string.Format("{0:mm}", univDateTimeTo.Minute.ToString
()) + ":"
+ string.Format("{0:ss}", univDateTimeTo.Second.ToString
());
switch (iArchiveSel)
{
case 1://TagLogging
grpExport.Enabled = true;
if (cmbInterpol.SelectedValue.ToString() != "0")
{
timeStep = ",'TIMESTEP=" + txtStep.Text + "," + cmbInter
pol.SelectedValue.ToString() + "'";
}
mySelectQuery = "TAG:R," + cmbTags.SelectedValue.ToString()
+ ",'" + tfrom + "','" + tto + "'" + timeStep;
try
{
cntData = TLG_Connect(mySelectQuery); //Start read out
}
catch (Exception ex)
{
MessageBox.Show("#E120: TLG_Connect() - Failed to retrie
ve the required data from database.\n{0}", ex.Message, MessageBoxButtons.OK, Mes
sageBoxIcon.Error);
return;
}
break;
case 2://Alarm Logging
grpExport.Enabled = true;
txtExportFile.Text = "AlarmLogging.txt";

mySelectQuery = "ALARMVIEW:SELECT * FROM AlgViewDeu Where Da
teTime>'" + tfrom + "' AND DateTime<'" + tto + "'";
try
{
cntData = ALG_Connect(mySelectQuery); //Start read out
}
catch (Exception ex)
{
MessageBox.Show("#E220: ALG_Connect() - Failed to retrie
ve the required data from the database.\n{0}", ex.Message, MessageBoxButtons.OK,
MessageBoxIcon.Error);
return;
}
break;
case 3://User Archive
grpExport.Enabled = true;
txtExportFile.Text = "UserArchive.txt";
mySelectQuery = "SELECT * FROM UA#Products" ;
try
{
cntData = UA_Connect(mySelectQuery); //Start read out
}
catch (Exception ex)
{
MessageBox.Show("#E320: UA_Connect() - Failed to retriev
e the required data from the database.\n{0}", ex.Message, MessageBoxButtons.OK,
MessageBoxIcon.Error);
return;
}
break;
default:
MessageBox.Show("#E920:invalid choice (" + iArchiveSel.ToStr
ing() + ")!");
break;
}//switch (iArchiveSel)
}//GetData()
//################################################################
//#### export() ##
//################################################################

///==========================================
/// <summary>
/// Configuration of first start
///
/// Initialize all objects of Form1 and
/// Set default values
/// </summary>
public void export()
{
StreamWriter streamTagLogging = null;
string strLine = "";
string strExportFile = "";
string myConnectionString = "Provider=" + txtProvider.Text + "; Data
Source =" + txtSource.Text + "; Catalog = " + txtCatalog.Text + ";";
//text file open
strExportFile = String.Format("{0}\\{1}", txtExportPath.Text, txtExp
ortFile.Text);
streamTagLogging = File.CreateText(strExportFile);
strLine = "strExportFile=" + txtExportFile.Text;
streamTagLogging.WriteLine(strLine);
streamTagLogging.WriteLine(myConnectionString);
strLine = String.Format("mySelectQuery=\"{0}\"", mySelectQuery);
streamTagLogging.WriteLine(strLine);

//export in file
try
{
// write column-header
foreach (DataGridViewColumn titel in myGrid.Columns)
{
strLine = String.Format("{0}; ", titel.HeaderText);
streamTagLogging.Write(strLine);
}
streamTagLogging.WriteLine();

//write data
foreach (DataGridViewRow row in myGrid.Rows)
{
foreach (DataGridViewColumn col in myGrid.Columns)
{
strLine = String.Format("{0}; ", row.Cells[col.Name].Va
lue);
streamTagLogging.Write(strLine);
};
streamTagLogging.WriteLine();
}//DataRow
} //try
catch (Exception)
{
streamTagLogging.Close();
MessageBox.Show("#410 - Export of User Archives faild", "ERROR",
MessageBoxButtons.OK, MessageBoxIcon.Error);
lblExportStatus.Text = "export faild";
}
if (streamTagLogging != null) streamTagLogging.Close();
lblExportStatus.Text = "export finished";
}
//################################################################
//#### GrpDisable() ##
//################################################################

///==========================================
/// <summary>
/// enable / disables all groups by archiv-selection change
///
/// Initialize all objects of Form1 and
/// Set default values
/// </summary>
public void GrpDisable()
{
grpDataSelection.Enabled = false;
grpExport.Enabled = false;
grpTimeInterval.Enabled = false;
btnRead.Enabled = false;
grpConnection.Enabled = true;
myGrid.Visible = false;
lbl_AnzArchTag.Text = "";
lblAnzEntries.Text = "";
}

//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+++++++++++++++++++++++++++++++++
//++ functions triggert by interface actions
++
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+++++++++++++++++++++++++++++++++
private void cmbTags_SelectedIndexChanged(object sender, EventArgs e)
{
//using trim() inorder to remove whitespaces!!
//replace() in order to replace '\' by '#'; '\' is not a valid chara
cter in filename
lblExportStatus.Text = "";
szValueName = cmbTags.Text.Trim().Replace('\\', '_');
txtExportFile.Text = szValueName + ".txt"; // Name der

TLG_ArchiveGetID(cmbTags.Text.Trim()); //ermitteln der aktuellen
ValueID

myGrid.Visible = false;
lblAnzEntries.Text = "";
}
private void rbtTagLogging_CheckedChanged(object sender, EventArgs e)
{
iArchiveSel = 1;
GrpDisable();
}
private void rbtAlarmLogging_CheckedChanged(object sender, EventArgs e)
{
iArchiveSel = 2;
GrpDisable();
}
private void rbtUserArchive_CheckedChanged(object sender, EventArgs e)
{
iArchiveSel = 3;
GrpDisable();
}
private void btnRead_Click(object sender, EventArgs e)
{
btnRead.UseWaitCursor = true;
GetData(); // start read data

btnRead.UseWaitCursor = false;
if (txtExportPath.Text.Length == 0) txtExportPath.Text = String.Form
at("c:\\data\\tmp");
if (iArchiveSel == 1) grpExport.Enabled = true;
myGrid.Visible = true;
}
private void btnExport_Click(object sender, EventArgs e)
{
export(); // start export
}
private void button2_Click(object sender, EventArgs e)
{
folderBrowserDialog1.ShowDialog();
txtExportPath.Text = folderBrowserDialog1.SelectedPath;
}
private void btnConDataBase_Click(object sender, EventArgs e)
{
grpConnection.Enabled = false;
ChangeComponent();
}
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
Application.Exit();
}

private void button1_Click(object sender, EventArgs e)
{
}
private void crystalReportViewer1_Load(object sender, EventArgs e)
{
}
private void txtCatalog_TextChanged(object sender, EventArgs e)
{
}








}
}

You might also like