| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851 |
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Windows;
- using System.Windows.Controls;
- using System.Windows.Data;
- using System.Windows.Documents;
- using System.Windows.Input;
- using System.Windows.Media;
- using System.Windows.Media.Imaging;
- using System.Windows.Navigation;
- using System.Windows.Shapes;
- using System.Globalization;
- using WpfLocalization;
- using System.Threading;
- using System.Data.SqlClient;
- using System.Data;
- using System.Diagnostics;
- using System.IO;
- using System.Collections;
- using System.IO.Ports;
- using System.Collections.ObjectModel;
- using System.Reflection;
- using System.Configuration;
- using System.Collections.Specialized;
- using System.Data.SqlServerCe;
- using System.ComponentModel;
- using System.Windows.Threading;
- using System.Data.OleDb;
- namespace WpfApplication19
- {
- /// <summary>
- /// Interaction logic for MainWindow.xaml
- /// </summary>
- ///
- public partial class MainWindow : Window
- {
- private bool isFullScreen = false;
- private Debug dw;
- public SqlConnection configConn, masterConn, transConn, proConn;
- private SqlCeConnection _opConn;
- //private SqlDataReader reader;
- string[] obTables = new string[] {"BEL-MAS-1", "BEL-MAS-3", "E-MAS-1", "E-MAS-3",
- "MG-MAS-1", "MG-MAS-3", "V-MAS-1", "V-MAS-3"};
- public SerialPort comport = new SerialPort();
- ObservableCollection<MeasurePoint> mps;
- int nextCol = 3;
- bool isMiddle = false, _haveMiddle = false;
- bool _isIn = false;
- public string inStarGS = "";
- public string midGS = "";
- string sMi16, sMi20, kind;
- enum RecordTypes { TopUnder, InOut }
- string[] masViews = new string[] { "bel_master_view", "e_master_view", "mg_master_view", "v_master_view" };
- List<string> list;
- string header;
- Stack<string> _lastAction = new Stack<string>();
- bool _isTkx = false;
- DateTime _lastTimeDataPort;
- bool _isCheck = false;
- DailyCheck _dc;
- Encoding encAscii = Encoding.ASCII;
- string obCondition;
- Dictionary<string, string> rolesDescription = new Dictionary<string, string>
- {
- {"qa_staff", "QA Staff"},{"user","User"}, {"admin", "Administrator"}, {"qa_man", "QA Ass't Manager"}
- };
- Dictionary<string, string> _sideMap = new Dictionary<string, string>
- {
- {"out", "in"},{"in","under"}, {"rim", "base"}, {"top", "under"}, {"outer", "inner"}
- };
- private double out0, out1;
- private double in0, in1;
- MeasurePoint currentMP;
- string currentColumn;
- Debug _debugWindow;
- Thread _aThread, _bThread;
- bool _clearThread = false, _canSent = true;
- int _pattern = 1;
- string _updated_at;
- private int _obLimit, _obCount, _ocLimit, _ocCount, _rhLimit, _rhCount;
- bool _isOver = false;
- bool _isFirstMeasure = true;
- DateTime _startUsing = new DateTime();
- int _usingTime;
- bool _isExisting = false;
- private List<string> _agreementList = new List<string>();
- string _currentValue, _prevValue = null;
- double _lower1, _upper1, _lower2, _upper2;
- string strAccessConnEMASTER = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\\\\192.168.0.253\\mgt\\master\\E-Master.mdb;Mode=Share Deny None";
- string strAccessConnBELMASTER = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\\\\192.168.0.253\\mgt\\master\\BEL-Master.mdb;Mode=Share Deny None";
- string strAccessConnMGMASTER = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\\\\192.168.0.253\\mgt\\master\\MG-Master.mdb;Mode=Share Deny None";
- string strAccessConnVMASTER = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\\\\192.168.0.253\\mgt\\master\\V-Master.mdb;Mode=Share Deny None";
-
- OleDbConnection accessConnEMASTER = null;
- OleDbConnection accessConnBELMASTER = null;
- OleDbConnection accessConnMGMASTER = null;
- OleDbConnection accessConnVMASTER = null;
- OleDbConnection tempConn = null;
- public MainWindow()
- {
- InitializeComponent();
- //dw = new Debug();
- //dw.Show();
- Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
- //Thread.CurrentThread.CurrentCulture.DateTimeFormat.ShortDatePattern = "dd/MM/yyyy";
- //Thread.CurrentThread.CurrentCulture = ci;
- //OBInterface obInterface = new OBInterface(comport);
- /*
- _debugWindow = new Debug();
- _debugWindow.Topmost = true;
- _debugWindow.Show();
- */
- LoginWindow loginWindow = new LoginWindow();
- var r = loginWindow.ShowDialog();
- if (r == false)
- return;
- //this.Hide();
- //loginWindow.Topmost = true;
- initSys();
- //forTesting();
- //for old ob box
- //_aThread = new Thread(new ThreadStart(Sender));
- _aThread = new Thread(new ThreadStart(Sender2));
- _aThread.Start();
- DispatcherTimer _timer = new DispatcherTimer();
- lotNo.Focus();
- }
- public void ResetHeaderUsage()
- {
- _isOver = false;
- if (header == "OB")
- {
- _obCount = 0;
- }
- else if (header == "OC")
- {
- _ocCount = 0;
- }
- else if (header == "RH")
- {
- _rhCount = 0;
- }
- }
- public void Sender2()
- {
- while (comport.IsOpen && _clearThread == false)
- {
- //Console.WriteLine("Hello");
- //string readCommand = String.Format("{0}{1}{2}{3}",0x002, 0x052, 0x031, 0x00D);
- string readCommand = encAscii.GetString(new byte[] { 0x02, 0x52, 0x31, 0x0D });
- if (_canSent == true)
- {
- try
- {
- comport.Write(readCommand);
- Thread.Sleep(500);
- }
- catch
- {
- Thread.Sleep(1000);
- }
- }
- /*
- if (!_debugWindow.Dispatcher.CheckAccess())
- {
- _debugWindow.Dispatcher.Invoke(
- System.Windows.Threading.DispatcherPriority.Normal,
- new Action(
- delegate()
- {
- _debugWindow.debugTextBox.AppendText("Sending\n");
- }
- ));
- }
- else
- {
- _debugWindow.debugTextBox.AppendText("Sending\n");
- }*/
- }
- }
- public void Sender()
- {
- while (comport.IsOpen && _clearThread == false)
- {
- //Console.WriteLine("Hello");
- comport.Write("S");
- Thread.Sleep(500);
- /*
- if (!_debugWindow.Dispatcher.CheckAccess())
- {
- _debugWindow.Dispatcher.Invoke(
- System.Windows.Threading.DispatcherPriority.Normal,
- new Action(
- delegate()
- {
- _debugWindow.debugTextBox.AppendText("Sending\n");
- }
- ));
- }
- else
- {
- _debugWindow.debugTextBox.AppendText("Sending\n");
- }*/
- }
- }
- public void AutoSaveData()
- {
- //Thread.Sleep(1500);
- if (_prevValue == null)
- {
- _prevValue = _currentValue;
- }
- TimeSpan ts = DateTime.Now - _lastTimeDataPort;
- //if (ts.Seconds >= 1 && _lastTimeDataPort != DateTime.MinValue)
- if (_lastTimeDataPort != DateTime.MinValue)
- {
- _lastTimeDataPort = DateTime.MinValue;
- if (_prevValue == _currentValue)
- {
- saveCellBtn.RaiseEvent(new RoutedEventArgs(Button.ClickEvent, saveCellBtn));
- }
- else
- {
- _prevValue = null;
- }
- }
- }
- private void forTesting()
- {
- var r = GetRecordType("114-78469F");
- Console.WriteLine(r);
- }
- private void initSys()
- {
- initDatabaseConnection();
- initCOMPort();
- //initMachineList();
- SqlDataReader reader = Utils.Query(proConn, "select * from sys_configs");
- string title;
- resetMenu();
- while (reader.Read())
- {
- title = reader["title"].ToString();
- //value = reader["value"];
- switch (title)
- {
- case "ob_limit":
- _obLimit = Convert.ToInt32(reader["value"]);
- break;
- case "oc_limit":
- _ocLimit = Convert.ToInt32(reader["value"]);
- break;
- case "rh_limit":
- _rhLimit = Convert.ToInt32(reader["value"]);
- break;
- default:
- //MessageBox.Show("Bad config variable :"+title);
- break;
- }
- }
- reader.Close();
- }
- private void resetMenu()
- {
- if (GlobalVars.user.empid == "root" ||
- GlobalVars.user.roles.Find(
- delegate(string s)
- {
- return s == "admin";
- }) != null)
- {
- configMenu.Visibility = Visibility.Visible;
- }
- else
- {
- configMenu.Visibility = Visibility.Collapsed;
- }
- }
- public void setFilterLogData(string q)
- {
- _isExisting = true;
- this._updated_at = q;
- }
- private List<string> GetRecordType(string pro2)
- {
- foreach (var view in masViews)
- {
- SqlCommand cmd = proConn.CreateCommand();
- string sql = @"
- select * from [" + view + "] v where v.PRO2='" + pro2 + "'";
- cmd.CommandText = sql;
- //Console.WriteLine(sql);
- SqlDataReader reader = cmd.ExecuteReader();
- if (!reader.HasRows)
- {
- reader.Close();
- continue;
- }
- bool hasIn, hasOut;
- while (reader.Read())
- {
- var mi17 = reader["MI17"].ToString();
- if (string.IsNullOrEmpty(mi17) || mi17 == "NULL")
- {
- hasOut = false;
- }
- else
- {
- hasOut = true;
- }
- string mi21 = reader["MI21"].ToString();
- if (string.IsNullOrEmpty(mi21) || mi21 == "NULL")
- {
- hasIn = false;
- }
- else
- {
- hasIn = true;
- }
- List<string> rList = new List<string>();
- if (_isTkx == true)
- {
- rList.Add("FA1");
- rList.Add("FA2");
- //rList.Add("MID");
- //rList.Add("IN*");
- reader.Close();
- point1Label.Content = "FA";
- point2Label.Content = "None";
- return rList;
- }
- if (view == "bel_master_view" || view == "e_master_view" || view == "mg_master_view")
- {
- if (reader["MP45"].ToString() != "NULL" && !string.IsNullOrEmpty(reader["MP45"].ToString().Trim()))
- {
- rList.Add(reader["MP45"].ToString().ToUpper());
- }
- point1Label.Content = reader["MP45"].ToString().ToUpper();
- //rList.Add("MID");
- //rList.Add("IN*");
- if (reader["MP49"].ToString() != "NULL" && !string.IsNullOrEmpty(reader["MP49"].ToString().Trim()))
- {
- rList.Add(reader["MP49"].ToString().ToUpper());
- point2Label.Content = reader["MP49"].ToString().ToUpper();
- }
- else
- {
- if (hasIn == true)
- {
- var side = reader["MP45"].ToString().ToLower();
- rList.Add(_sideMap[side].ToUpper());
- point2Label.Content = _sideMap[side].ToUpper();
- }
- }
- reader.Close();
- return rList;
- }
- else
- {
- if (reader["MP34"].ToString() != "NULL" && !string.IsNullOrEmpty(reader["MP34"].ToString().Trim()))
- {
- rList.Add(reader["MP34"].ToString().ToUpper());
- }
- point1Label.Content = reader["MP34"].ToString().ToUpper();
- //rList.Add("MID");
- //rList.Add("IN*");
- if (reader["MP39"].ToString() != "NULL" && !string.IsNullOrEmpty(reader["MP39"].ToString().Trim()))
- {
- rList.Add(reader["MP39"].ToString().ToUpper());
- point2Label.Content = reader["MP39"].ToString().ToUpper();
- }
- else
- {
- if (hasIn == true)
- {
- var side = reader["MP34"].ToString().ToLower();
- rList.Add(_sideMap[side].ToUpper());
- point2Label.Content = _sideMap[side].ToUpper();
- }
- }
- reader.Close();
- return rList;
- }
- }
- }
- return null;
- }
- //for old ob box
- void DataReceivedHandler(
- object sender,
- SerialDataReceivedEventArgs e)
- {
- SerialPort sp = (SerialPort)sender;
- byte[] data = new byte[2];
- data[0] = (byte)sp.ReadByte();
- data[1] = (byte)sp.ReadByte();
- //byte[] data = new byte[2];
- //int nByteRead = sp.Read(data, 0, 2);
- _lastTimeDataPort = DateTime.Now;
- byte[] bcddata = new byte[4];
- byte anddata = 240;
- byte tempdata;
- if (_pattern == 1)
- {
- anddata = (byte)240;
- bcddata[1] = (byte)(data[0] & anddata);
- bcddata[1] = (byte)(bcddata[1] >> 4);
- bcddata[3] = (byte)(data[1] & anddata);
- bcddata[3] = (byte)(bcddata[3] >> 4);
- anddata = (byte)1;
- bcddata[0] = (byte)(data[0] & (byte)anddata);
- anddata = (byte)15;
- bcddata[2] = (byte)(data[1] & (byte)anddata);
- tempdata = bcddata[3];
- bcddata[3] = (byte)(tempdata & (byte)1);
- bcddata[3] = (byte)(bcddata[3] << 1);
- tempdata = (byte)(tempdata >> 1);
- bcddata[3] = (byte)(bcddata[3] | (tempdata & (byte)1));
- bcddata[3] = (byte)(bcddata[3] << 1);
- tempdata = (byte)(tempdata >> 1);
- bcddata[3] = (byte)(bcddata[3] | (tempdata & (byte)1));
- bcddata[3] = (byte)(bcddata[3] << 1);
- tempdata = (byte)(tempdata >> 1);
- bcddata[3] = (byte)(bcddata[3] | (tempdata & (byte)1));
- tempdata = bcddata[2];
- bcddata[2] = (byte)(tempdata & (byte)1);
- bcddata[2] = (byte)(bcddata[2] << 1);
- tempdata = (byte)(tempdata >> 1);
- bcddata[2] = (byte)(bcddata[2] | (tempdata & (byte)1));
- bcddata[2] = (byte)(bcddata[2] << 1);
- tempdata = (byte)(tempdata >> 1);
- bcddata[2] = (byte)(bcddata[2] | (tempdata & (byte)1));
- bcddata[2] = (byte)(bcddata[2] << 1);
- tempdata = (byte)(tempdata >> 1);
- bcddata[2] = (byte)(bcddata[2] | (tempdata & (byte)1));
- }
- else
- {
- anddata = (byte)240;
- bcddata[1] = (byte)(data[0] & anddata);
- bcddata[1] = (byte)(bcddata[1] >> 4);
- bcddata[3] = (byte)(data[1] & anddata);
- bcddata[3] = (byte)(bcddata[3] >> 4);
- anddata = (byte)1;
- bcddata[0] = (byte)(data[0] & anddata);
- anddata = (byte)15;
- bcddata[2] = (byte)(data[1] & anddata);
- }
- Console.WriteLine("Data Received: {0}", data.Length);
- foreach (byte element in data)
- {
- Console.WriteLine("{0} = {1}", element, (char)element);
- }
- foreach (byte element in bcddata)
- {
- Console.WriteLine("oo {0} = {1}", element, element);
- }
- //Console.WriteLine("{0}.{1}{2}", Convert.ToString(bcddata[1]), Convert.ToString(bcddata[2]), Convert.ToString(bcddata[3]));
- string outputString = string.Format("{0}.{1}{2}", bcddata[1], bcddata[2], bcddata[3]);
- //_currentValue = outputString;
- //_currentValue = outputString;
- if (!readingBox.Dispatcher.CheckAccess())
- {
- readingBox.Dispatcher.Invoke(
- System.Windows.Threading.DispatcherPriority.Normal,
- new Action(
- delegate()
- {
- readingBox.Text = outputString;
- if (_dc != null)
- {
- _dc.measureBlock.Text = outputString;
- }
- //_dc.measureBlock.Text = outputString;
- }
- ));
- }
- //readingBox.Text = outputString;
- }
- //for new ob box
- void DataReceivedHandler2(
- object sender,
- SerialDataReceivedEventArgs e)
- {
- _canSent = false;
- SerialPort sp = (SerialPort)sender;
- byte[] data = new byte[11];
- bool readError = false;
- for (int i = 0; i < 11; i++)
- {
- try
- {
- data[i] = (byte)sp.ReadByte();
- }
- catch
- {
- readError = true;
- break;
- }
- }
- //data[0] = (byte)sp.ReadByte();
- //data[1] = (byte)sp.ReadByte();
- if (readError == true)
- return;
- //byte[] data = new byte[2];
- //int nByteRead = sp.Read(data, 0, 2);
- _lastTimeDataPort = DateTime.Now;
- //Console.WriteLine("{0}.{1}{2}", Convert.ToString(bcddata[1]), Convert.ToString(bcddata[2]), Convert.ToString(bcddata[3]));
- //string outputString = string.Format("{0}{1}{2}{3}{4}{5}{6}", data[1], data[2], data[3], data[4], data[5], data[6], data[7]);
- string outputString = encAscii.GetString(new byte[] { data[3], data[4], data[5], data[6], data[7] });
- //_currentValue = outputString;
- //_currentValue = outputString;
- if (!readingBox.Dispatcher.CheckAccess())
- {
- readingBox.Dispatcher.Invoke(
- System.Windows.Threading.DispatcherPriority.Normal,
- new Action(
- delegate()
- {
- if (data[9] == '1')
- {
- readingBox.Text = "Error";
- }
- else
- {
- readingBox.Text = outputString;
- saveCellBtn_Click(null, null);
- }
- if (_dc != null)
- {
- _dc.measureBlock.Text = outputString;
- }
- //_dc.measureBlock.Text = outputString;
- }
- ));
- }
- _canSent = true;
- //readingBox.Text = outputString;
- }
- private void initCOMPort()
- {
- if (comport.IsOpen)
- comport.Close();
- else
- {
- comport.PortName = Utils.getSetting("machinePort");
- /*
- comport.BaudRate = int.Parse(Utils.getSetting("baudRate"));
- comport.DataBits = int.Parse(Utils.getSetting("dataBits"));
- comport.StopBits = (StopBits)Enum.Parse(typeof(StopBits), Utils.getSetting("stopBits"));
- comport.Parity = (Parity)Enum.Parse(typeof(Parity), Utils.getSetting("parity"));
- */
- // for old ob box version
- //comport.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
- // for new ob
- comport.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler2);
- bool error = false;
- try
- {
- comport.RtsEnable = true;
- comport.Open();
- Thread.Sleep(1000);
- //comport.Close();
- //MessageBox.Show("Open Port Success");
- }
- catch (UnauthorizedAccessException) { error = true; }
- catch (IOException) { error = true; }
- catch (ArgumentException) { error = true; }
- if (error)
- {
- MessageBox.Show("Open Port Fail");
- }
- }
- }
- private void initDatabaseConnection()
- {
- try
- {
- _opConn = Utils.createSqlCeConnection("operatingDbCS");
- // Sample usage
- /*
- SqlCeDataReader reader;
- reader = Utils.Query(_opConn, "select * from UsingTime");
- while(reader.Read()){
- Console.WriteLine("hello");
- }
- reader.Close();
- */
- }
- catch (SqlCeException se)
- {
- MessageBox.Show("operatingDbCS : ", se.Message);
- }
- /*
- try
- {
- configConn = Utils.createSqlConnection("configDbCS");
- }
- catch (SqlException se)
- {
- MessageBox.Show("configDbCS : ", se.Message);
- }
- try
- {
- masterConn = Utils.createSqlConnection("masterDbCS");
- }
- catch (SqlException se)
- {
- MessageBox.Show("masterDbCS : ", se.Message);
- }
- try
- {
- transConn = Utils.createSqlConnection("tranDbCS");
- }
- catch (SqlException se)
- {
- MessageBox.Show("tranDbCS : ", se.Message);
- }
- */
- try
- {
- proConn = Utils.createSqlConnection("productionDbCS");
- transConn = Utils.createSqlConnection("productionDbCS");
- masterConn = Utils.createSqlConnection("productionDbCS");
- configConn = Utils.createSqlConnection("productionDbCS");
- }
- catch (SqlException se)
- {
- MessageBox.Show("productionDbCS : ", se.Message);
- }
- //mod: change config by move every table alias
- //transConn = masterConn = configConn = proConn;
- /*
- try
- {
- accessConnEMASTER = new OleDbConnection(strAccessConnEMASTER);
- accessConnEMASTER.Open();
- }
- catch (Exception ex)
- {
- MessageBox.Show("Error: Failed to create e-master connection. \n{0}", ex.Message);
- }
- try
- {
- accessConnBELMASTER = new OleDbConnection(strAccessConnBELMASTER);
- accessConnBELMASTER.Open();
- }
- catch (Exception ex)
- {
- MessageBox.Show("Error: Failed to create e-master connection. \n{0}", ex.Message);
- }
- try
- {
- accessConnMGMASTER = new OleDbConnection(strAccessConnMGMASTER);
- accessConnMGMASTER.Open();
- }
- catch (Exception ex)
- {
- MessageBox.Show("Error: Failed to create e-master connection. \n{0}", ex.Message);
- }
- try
- {
- accessConnVMASTER = new OleDbConnection(strAccessConnVMASTER);
- accessConnVMASTER.Open();
- }
- catch (Exception ex)
- {
- MessageBox.Show("Error: Failed to create e-master connection. \n{0}", ex.Message);
- } */
- }
- private void testDB()
- {
- /*
- string server = Utils.getSetting("dbServer");
- string user = Utils.getSetting("dbUser");
- string passwd = Utils.getSetting("dbPassword");
- string dbName = Utils.getSetting("dbName");
- var connectionString = "Data Source=" + server + ";User ID=" + user + ";Password=" + passwd + "; Initial Catalog=" + dbName;
- Console.WriteLine("cs = {0}", connectionString);
- SqlConnection sqlConnection = new SqlConnection(connectionString);
- SqlCommand catCMD = sqlConnection.CreateCommand();
- catCMD.CommandText = "SELECT count(*) as c FROM [V-MAS-3]";
- sqlConnection.Open();
- reader = catCMD.ExecuteReader();
- while (reader.Read())
- {
- Console.WriteLine("{0}", reader["c"]);
- }
- reader.Close();
- */
- }
- private void MenuItem_Click(object sender, RoutedEventArgs e)
- {
- Settings w = new Settings();
- w.Show();
- }
- private void closeWindows(object sender, EventArgs e)
- {
- //sqlConnection.Close();
- //_aThread.Join();
- // comport.Close();
- //_clearThread = true;
- //_debugWindow.Close();
- //_bThread.Abort();
- //dw.Close();
- }
- private void button1_Click(object sender, RoutedEventArgs e)
- {
- testDB();
- }
- private bool isAlreadyCheck(string ln)
- {
- SqlCommand catCMD = proConn.CreateCommand();
- string sql = @"SELECT * FROM lot_summary where lot_no = '" + ln + "'";
- catCMD.CommandText = sql;
- SqlDataReader reader = catCMD.ExecuteReader();
- bool r = reader.HasRows;
- reader.Close();
- return r;
- }
- private void find_Click(object sender, RoutedEventArgs e)
- {
- string ln = lotNo.Text;
- _startUsing = DateTime.Now;
- bool isFound = false;
- isMiddle = _isIn = false;
- _isExisting = false;
- _isCheck = false;
- _isTkx = false;
- midGS = "";
- inStarGS = "";
- measureGrid.ItemsSource = null;
- measureGrid.Items.Clear();
- nextCol = 3;
- middleText.Text = "Add Middle";
- inText.Text = "Add IN*";
- foreach (var view in masViews)
- {
- isFound = fillProData(ln, view);
- if (isFound == true)
- break;
- }
- if (isFound == false)
- {
- MessageBox.Show("Lot No.:" + ln + " Not Founded");
- return;
- }
- mps = new ObservableCollection<MeasurePoint>();
- list = GetRecordType(ln);
- if (list.Count == 0)
- {
- list.Add("OUT");
- list.Add("IN");
- point1Label.Content = "OUT";
- point2Label.Content = "IN";
- }
- if (isAlreadyCheck(ln))
- {
- //ChooseRecord cr = new ChooseRecord(ln);
- //cr.ShowDialog();
- _isCheck = true;
- ChooseRecord2 cr = new ChooseRecord2(ln);
- cr.ShowDialog();
- SqlDataReader reader = Utils.Query(proConn, "select * from data where lot_no = '" + ln + "' and updated_at = '" + this._updated_at + "' order by id");
- isMiddle = false;
- _haveMiddle = false;
- while (reader.Read())
- {
- var mp = new MeasurePoint();
- nextCol = Convert.ToInt32(reader["ndata"]);
- mp.Count = Convert.ToInt16(reader["row_no"]);
- mp.Type = reader["r_type"].ToString();
- if (mp.Type == "MID")
- {
- isMiddle = true;
- _haveMiddle = true;
- middleText.Text = "Remove Middle";
- }
- mp.SubOrder = Convert.ToInt16(reader["sub_order"]);
- mp.P1 = Math.Round(Convert.ToDouble(reader["p1"]), 2);
- mp.P2 = Math.Round(Convert.ToDouble(reader["p2"]), 2);
- mp.P3 = Math.Round(Convert.ToDouble(reader["p3"]), 2);
- mp.P4 = Math.Round(Convert.ToDouble(reader["p4"]), 2);
- mp.P5 = Math.Round(Convert.ToDouble(reader["p5"]), 2);
- mp.P6 = Math.Round(Convert.ToDouble(reader["p6"]), 2);
- mp.P7 = Math.Round(Convert.ToDouble(reader["p7"]), 2);
- mp.P8 = Math.Round(Convert.ToDouble(reader["p8"]), 2);
- mp.P9 = Math.Round(Convert.ToDouble(reader["p9"]), 2);
- mp.P10 = Math.Round(Convert.ToDouble(reader["p10"]), 2);
- mp.Avg = Math.Round(Convert.ToDouble(reader["avg"]), 2);
- mp.Grade = reader["grade"].ToString();
- mp.ResultGrade = reader["rgrade"].ToString();
- mp.Type = reader["r_type"].ToString();
- mps.Add(mp);
- // if row['sub_order'] == 1 and not have middle
- //add dummy mid row
- //if (Convert.ToInt32(reader["sub_order"]) == 1 && _haveMiddle == false)
- // mps.Add(new MeasurePoint() { Count = mp.Count, Type = "MID", SubOrder = 2 });
- }
- reader.Close();
- }
- else
- {
- for (int i = 0; i < 3; i++)
- {
- int count = 1;
- foreach (var l in list)
- {
- mps.Add(new MeasurePoint() { Count = i + 1, Type = l, SubOrder = count });
- count++;
- }
- }
- if (_isTkx == true)
- {
- measureGrid.Columns.ElementAt(nextCol--).Visibility = Visibility.Hidden;
- }
- }
- measureGrid.ItemsSource = mps;
- for (int i = 1; i < 10; i++)
- {
- measureGrid.Columns.ElementAt(i).Visibility = Visibility.Hidden;
- }
- for (int i = 1; i <= nextCol; i++)
- {
- measureGrid.Columns.ElementAt(i).Visibility = Visibility.Visible;
- }
- measureGrid.Focus();
- try
- {
- measureGrid.SelectedItem = measureGrid.Items[0];
- measureGrid.CurrentCell = new DataGridCellInfo(
- measureGrid.Items[0], measureGrid.Columns[1]);
- measureGrid.BeginEdit();
- }
- catch { }
- }
- private string getConditionRef(string id)
- {
- if (string.IsNullOrEmpty(id))
- {
- return "None";
- }
- SqlCommand cmd = configConn.CreateCommand();
- string sql = @"
- select * from [TABLE_TI-T4] t4 where t4.TIT4 =" + id;
- cmd.CommandText = sql;
- Console.WriteLine(sql);
- SqlDataReader reader = cmd.ExecuteReader();
- string condition = "";
- while (reader.Read())
- {
- condition = reader["TIT4NE"].ToString();
- }
- reader.Close();
- return condition;
- }
- private bool fillProData(string ln, string viewName)
- {
- /*
- join [V-MAS-3] v
- on p.PRO1 = v.TC
- left outer join [TABLE_TI-T4] t4
- on v.MI5 = t4.TIT4
-
- */
- string sql = @"
- SELECT * FROM " + viewName + " p " +
- "where p.PRO2 = '" + ln + "'";
- SqlDataReader reader = Utils.Query(proConn, sql);
- string pro1 = "";
- if (!reader.HasRows)
- {
- reader.Close();
- return false;
- }
- while (reader.Read())
- {
- string[] t = reader["MC20"].ToString().Split('/');
- string mc24 = reader["MC24"].ToString();
- string kind = reader["PRO17"].ToString();
- int gainSize;
- try
- {
- gainSize = Convert.ToInt32(t[0]);
- }
- catch (FormatException fe)
- {
- gainSize = 0;
- }
- if (gainSize >= 10 && gainSize <= 100 && kind == "V")
- header = "OB";
- if (gainSize >= 120 && gainSize <= 220 && kind == "V")
- header = "OC";
- if (gainSize >= 10 && gainSize <= 100 && mc24 == "MG")
- header = "OB";
- if (gainSize >= 10 && gainSize <= 100 && kind == "B")
- header = "OB";
- if (gainSize > 220 && kind == "V")
- header = "RH";
- if (gainSize > 120 && kind == "B")
- header = "RH";
- if (headerLabel.Content != header)
- {
- MessageBox.Show("Please Change Using Header to '" + header + "'");
- }
- headerLabel.Content = header;
- UsingTimeTB.Text = getUsingTime(header).ToString();
- Console.WriteLine("{0}", reader["PRO2"]);
- string codeString = reader["PRO1"].ToString();
- string temp2 = codeString[0] + "-" + codeString.Substring(1, 4) + "-" + codeString.Substring(5, 4) + "-" + codeString.Substring(9, 1);
- code.Text = temp2;
- pro1 = reader["PRO1"].ToString();
- customer.Text = reader["PRO1C"].ToString();
- if (customer.Text.Trim().ToLower().StartsWith("tkx"))
- {
- _isTkx = true;
- }
- noProduct.Text = reader["PRO5"].ToString();
- shape.Text = reader["PRO8"] + " " + reader["PRO9"];
- size.Text = reader["PRO10"] + "x" + reader["PRO11"] + "x" + reader["PRO12"];
- spec.Text = reader["PRO13"] + " " + reader["PRO14"] + " " + reader["PRO15"] + " " + reader["PRO16"]
- + " " + reader["PRO17"] + " " + reader["PRO18"];
- kind = reader["PRO17"] as string;
- int mi13 = Convert.ToInt32(reader["MI13"]);
- string samplingText = "";
- if (mi13 == 1)
- {
- samplingText = "All";
- }
- else if (mi13 == 2)
- {
- samplingText = "2 Pcs";
- }
- else if (mi13 == 3)
- {
- samplingText = "3 Pcs";
- }
- else if (mi13 == 4 || mi13 == 5)
- {
- samplingText = "5 Pcs";
- }
- sampling.Text = samplingText;
- double mi18 = Convert.ToDouble(reader["MI18"]);
- double mi19 = Convert.ToDouble(reader["MI19"]);
- //Console.WriteLine(mi18);
- double o1, o2;
- if (mi18 < mi19)
- {
- o1 = mi18;
- o2 = mi19;
- }
- else
- {
- o1 = mi19;
- o2 = mi18;
- }
- this.out0 = Math.Round(o1, 2);
- this.out1 = Math.Round(o2, 2);
- var mi16 = reader["MI16"].ToString();
- sMi16 = reader["MI16"].ToString();
- sMi16 = sMi16.Replace("\\", "");
- Console.WriteLine("mi16 = " + sMi16);
- //sMi20 = sMi20.Replace("\\", "");
- var mi17 = reader["MI17"].ToString();
- if (string.IsNullOrEmpty(mi17) || mi17 == "NULL")
- {
- mi17 = "None";
- }
- string temp = String.Format("{0:f} - {1:f} ({2}) {3}", o1, o2, mi16, mi17);
- outTB.Text = temp;
- _lower1 = o1;
- _upper1 = o2;
- double mi22 = Convert.ToDouble(reader["MI22"]);
- double mi23 = Convert.ToDouble(reader["MI23"]);
- var mi20 = reader["MI20"].ToString();
- sMi20 = reader["MI20"].ToString();
- sMi20 = sMi20.Replace("\\", "");
- string mi21 = reader["MI21"].ToString();
- if (string.IsNullOrEmpty(mi21) || mi21 == "NULL")
- {
- mi21 = "None";
- }
- //Console.WriteLine(mi18);
- if (mi22 < mi23)
- {
- o1 = mi22;
- o2 = mi23;
- }
- else
- {
- o1 = mi23;
- o2 = mi22;
- }
- this.in0 = Math.Round(o1, 2);
- this.in1 = Math.Round(o2, 2);
- _lower2 = o1;
- _upper2 = o2;
- temp = String.Format("{0:f} - {1:f} ({2}) {3} ", o1, o2, mi20, mi21);
- inTB.Text = temp;
- point.Text = getConditionRef(reader["MI14"].ToString());
- condition.Text = getConditionRef(reader["MI15"].ToString());
- this.obCondition = reader["ob_condition"].ToString();
- }
- reader.Close();
- reader = initAgreementList(ln, viewName, reader);
- return true;
- //return pro1;
- }
- private SqlDataReader initAgreementList(string ln, string viewName, SqlDataReader reader)
- {
- var sql2 = string.Format(@"select * from (
- select MI53 as ag, PRO2 from {0}
- union
- select MI55 as ag, PRO2 from {0}
- union
- select MI31 as ag, PRO2 from {0}
- union
- select MI33 as ag, PRO2 from {0}
- union
- select INSAGM as ag, PRO2 from {0}
- union
- select MARAGM as ag, PRO2 from {0}
- )x WHERE PRO2 = '{1}'", viewName, ln);
- reader = Utils.Query(proConn, sql2);
- //bool isHaveAgreement = false;
- agreementCB.Items.Clear();
- bool isHaveAgreement = false;
- while (reader.Read())
- {
- //_agreementList.Add(reader["ag"].ToString());
- var temp = reader["ag"].ToString();
- //agreementCB.Text = "hello";
- if (String.IsNullOrEmpty(temp) || temp == "NULL")
- continue;
- isHaveAgreement = true;
- var list = temp.Split(new char[] { '/', ',', '\\' });
- if (list.Length > 1)
- {
- foreach (var l in list)
- {
- if (l.Trim() != "")
- {
- agreementCB.Items.Add(new ComboBoxItem() { Content = l });
- }
- }
- }
- else
- agreementCB.Items.Add(new ComboBoxItem() { Content = temp });
- }
- if (isHaveAgreement == true)
- {
- agreementBtn.IsEnabled = true;
- agreementCB.IsEnabled = true;
- agreementCB.SelectedIndex = 0;
- }
- else
- {
- agreementBtn.IsEnabled = false;
- agreementCB.IsEnabled = false;
- }
- reader.Close();
- return reader;
- }
- private int getUsingTime(string header)
- {
- var reader = Utils.Query(_opConn, "select * from UsingTime");
- reader.Read();
- int v = 0;
- switch (header)
- {
- case "OB":
- v = Convert.ToInt32(reader["ob"]);
- _obCount = v;
- _obLimit = Convert.ToInt32(reader["ob_limit"]);
- break;
- case "OC":
- v = Convert.ToInt32(reader["oc"]);
- _ocCount = v;
- _ocLimit = Convert.ToInt32(reader["oc_limit"]);
- break;
- case "RH":
- v = Convert.ToInt32(reader["rh"]);
- _rhCount = v;
- _rhLimit = Convert.ToInt32(reader["rh_limit"]);
- break;
- default:
- MessageBox.Show("Bad Header Name");
- break;
- }
- reader.Close();
- return v;
- }
- /*
- private void lotNo_TextChanged(object sender, TextChangedEventArgs e)
- {
- //var s = lotNo.Text;
- //if(lotNo.Text.IndexOf('\n') != -1)
- // find_Click(null, null);
-
- }*/
- private void openScreenKB(object sender, RoutedEventArgs e)
- {
- Console.WriteLine("Open KB");
- }
- private void lotNo_MouseDoubleClick(object sender, MouseButtonEventArgs e)
- {
- }
- private void openScreenKB(object sender, MouseButtonEventArgs e)
- {
- string windir = Environment.GetEnvironmentVariable("WINDIR");
- string osk = null;
- if (osk == null)
- {
- osk = System.IO.Path.Combine(System.IO.Path.Combine(windir, "sysnative"), "osk.exe");
- if (!File.Exists(osk))
- {
- osk = null;
- }
- }
- if (osk == null)
- {
- osk = System.IO.Path.Combine(System.IO.Path.Combine(windir, "system32"), "osk.exe");
- if (!File.Exists(osk))
- {
- osk = null;
- }
- }
- if (osk == null)
- {
- osk = "osk.exe";
- }
- Process.Start(osk);
- }
- private void addRow_Click(object sender, RoutedEventArgs e)
- {
- if (measureGrid.ItemsSource == null)
- return;
- _lastAction.Push("row");
- MeasurePoint m = mps.Last();
- int count = 1;
- foreach (var l in list)
- {
- mps.Add(new MeasurePoint() { Count = m.Count + 1, Type = l, SubOrder = count });
- count++;
- }
- }
- private void addMeasureColumn_Click(object sender, RoutedEventArgs e)
- {
- _lastAction.Push("column");
- if (nextCol <= 10)
- {
- measureGrid.Columns.ElementAt(++nextCol).Visibility = Visibility.Visible;
- foreach (var item in measureGrid.Items)
- {
- //Console.WriteLine(item);
- MeasurePoint c = item as MeasurePoint;
- c.Avg = (c.P1 + c.P2 + c.P3 + c.P4 + c.P6 + c.P7 + c.P8 + c.P9 + c.P10) / nextCol;
- c.Avg = Math.Round(c.Avg, 2);
- if (c.SubOrder == 1)
- {
- c.Grade = computeGrade(sMi16, c.Avg, kind, "-", c.Type);
- }
- else if (c.SubOrder != 1 && c.Type != "MID" && c.Type != "IN*")
- {
- if (sMi20 != "0")
- c.Grade = computeGrade(sMi20, c.Avg, kind, "-", c.Type);
- else
- c.Grade = computeGrade(sMi16, c.Avg, kind, "-", c.Type);
- }
- }
- measureGrid.Items.Refresh();
- }
- }
- private string computeGrade(string size, double lower, string kind, string defValue, string type)
- {
- SqlCommand cmd = configConn.CreateCommand();
- if (type == "MID")
- {
- size = midGS;
- }
- else if (type == "IN*")
- {
- size = inStarGS;
- }
- int lotKind = 0;
- if (code.Text[0] == '1' || code.Text[0] == '2' || code.Text[0] == '9')
- {
- lotKind = 1;
- }
- else if (code.Text[0] == '3' || code.Text[0] == '4' || code.Text[0] == '5')
- {
- lotKind = 2;
- }
- if (double.IsNaN(lower))
- {
- lower = 0;
- }
- string sql = "";
- SqlDataReader reader;
- string value;
- if (lotKind == 1)
- {
- if (_isTkx == true)
- {
- sql = string.Format(@"select top 1 *
- FROM
- (
- select ABS('{1}' - round(TIT2D, 2)) AS diff, * from [TABLE_TI-T2-TKX] where TIT2R = '{0}'
- union all
- select ABS('{1}' - round(TIT2M,2)) AS diff, * from [TABLE_TI-T2-TKX] where TIT2R = '{0}'
- union all
- select ABS('{1}' - round(TIT2U,2)) AS diff, * from [TABLE_TI-T2-TKX] where TIT2R = '{0}'
- )
- x
- order by diff, TIT2G", size, lower);
- }
- else
- {
- sql = string.Format(@"SELECT * FROM [TABLE_TI-T2] WHERE (TIT2R = '{0}') AND (round(TIT2D,2) <= '{1}') AND (round(TIT2U,2) >= '{2}')", size, lower, lower);
- }
- cmd.CommandText = sql;
- reader = cmd.ExecuteReader();
- value = defValue;
- Console.WriteLine(sql);
- while (reader.Read())
- {
- value = reader["TIT2G"].ToString();
- break;
- }
- reader.Close();
- return value;
- }
- else if (lotKind == 2)
- {
- if (_isTkx == true)
- {
- sql = string.Format(@"select top 1 *
- FROM
- (
- select ABS('{1}' - round(TIT2D, 2)) AS diff, * from [TABLE-E_TI-T2-TKX] where TIT2R = '{0}'
- union all
- select ABS('{1}' - round(TIT2M,2)) AS diff, * from [TABLE-E_TI-T2-TKX] where TIT2R = '{0}'
- union all
- select ABS('{1}' - round(TIT2U,2)) AS diff, * from [TABLE-E_TI-T2-TKX] where TIT2R = '{0}'
- )
- x
- order by diff, TIT2G", size, lower);
- }
- else
- {
- sql = string.Format(@"SELECT * FROM [TABLE-E_TI-T2] WHERE (TIT2R = '{0}') AND (round(TIT2D,2) <= '{1}') AND (round(TIT2U,2) >= '{2}')", size, lower, lower);
- }
- cmd.CommandText = sql;
- Console.WriteLine(sql);
- //reader.Close();
- reader = cmd.ExecuteReader();
- value = defValue;
- while (reader.Read())
- {
- value = reader["TIT2G"].ToString();
- break;
- }
- reader.Close();
- return value;
- }
- else
- {
- return "-";
- }
- //return value;
- }
- //int row;
- private void measureGrid_RowEditEnding(object sender, DataGridRowEditEndingEventArgs e)
- {
- //MessageBox.Show("refresh");
- int row = e.Row.GetIndex();
- (sender as DataGrid).RowEditEnding -= measureGrid_RowEditEnding;
- (sender as DataGrid).CommitEdit();
- var c = mps[row];
- computeValues(c, true);
- measureGrid.Items.Refresh();
- (sender as DataGrid).RowEditEnding += measureGrid_RowEditEnding;
- }
- private void computeValues(MeasurePoint c, bool isCompGrade = false)
- {
- c.Avg = (c.P1 + c.P2 + c.P3 + c.P4 + c.P5 + c.P6 + c.P7 + c.P8 + c.P9 + c.P10) / nextCol;
- c.Avg = Math.Round(c.Avg, 2);
- if (isCompGrade == true)
- {
- if (c.SubOrder == 1)
- {
- c.Grade = computeGrade(sMi16, c.Avg, kind, "-", c.Type);
- }
- else if (c.SubOrder != 1 && c.Type != "MID" && c.Type != "IN*")
- {
- if (sMi20 != "0")
- c.Grade = computeGrade(sMi20, c.Avg, kind, "-", c.Type);
- else
- c.Grade = computeGrade(sMi16, c.Avg, kind, "-", c.Type);
- }
- else if (c.Type == "MID" || c.Type == "IN*")
- {
- c.Grade = computeGrade("0", c.Avg, kind, "-", c.Type);
- }
- }
- if (c.SubOrder == 1 || c.Type == "IN*" || c.Type == "MID" || c.Type == "FA1" || c.Type == "FA2")
- {
- if (this.header == "OB" || this.header == "OC")
- {
- if (c.Avg >= this.out0 && c.Avg <= this.out1)
- {
- c.ResultGrade = "OK";
- }
- else if (c.Avg < this.out0)
- {
- c.ResultGrade = "Hard";
- }
- else if (c.Avg > this.out1)
- {
- c.ResultGrade = "Soft";
- }
- }
- else
- {
- if (c.Avg >= this.out0 && c.Avg <= this.out1)
- {
- c.ResultGrade = "OK";
- }
- else if (c.Avg < this.out0)
- {
- c.ResultGrade = "Soft";
- }
- else if (c.Avg > this.out1)
- {
- c.ResultGrade = "Hard";
- }
- }
- }
- else if (c.SubOrder != 1)
- {
- if (this.header == "OB" || this.header == "OC")
- {
- if (c.Avg >= this.in0 && c.Avg <= this.in1)
- {
- c.ResultGrade = "OK";
- }
- else if (c.Avg < this.in0)
- {
- c.ResultGrade = "Hard";
- }
- else if (c.Avg > this.in1)
- {
- c.ResultGrade = "Soft";
- }
- }
- else
- {
- if (c.Avg >= this.in0 && c.Avg <= this.in1)
- {
- c.ResultGrade = "OK";
- }
- else if (c.Avg < this.in0)
- {
- c.ResultGrade = "Soft";
- }
- else if (c.Avg > this.in1)
- {
- c.ResultGrade = "Hard";
- }
- }
- }
- }
- private void measureGrid_KeyUp(object sender, KeyEventArgs e)
- {
- Console.WriteLine("hello");
- //MessageBox.Show(e.Key.ToString());
- var info = measureGrid.CurrentColumn;
- var item = measureGrid.CurrentItem as MeasurePoint;
- int col = info.DisplayIndex;
- var mp = (MeasurePoint)measureGrid.CurrentItem;
- int row = mps.IndexOf(mp);
- if (e.Key == Key.Tab)
- {
- //measureGrid.RaiseEvent(new RoutedEventArgs(DataGrid.rowediten));
- //MessageBox.Show("row " + item.Count.ToString());
- //MessageBox.Show("row " + mps.IndexOf(mp).ToString());
- //MessageBox.Show("col " + info.DisplayIndex.ToString());
- if (col < nextCol)
- {
- measureGrid.CurrentCell = new DataGridCellInfo(
- measureGrid.Items[row], measureGrid.Columns[col + 1]);
- measureGrid.BeginEdit();
- }
- else
- {
- try
- {
- measureGrid.CurrentCell = new DataGridCellInfo(
- measureGrid.Items[row + 1], measureGrid.Columns[1]);
- measureGrid.BeginEdit();
- }
- catch
- {
- measureGrid.CurrentCell = new DataGridCellInfo(
- measureGrid.Items[0], measureGrid.Columns[1]);
- measureGrid.BeginEdit();
- }
- }
- }
- if (e.Key == Key.Return)
- {
- if (isMiddle == false)
- row += 2;
- if (row > measureGrid.Items.Count)
- {
- measureGrid.CurrentCell = new DataGridCellInfo(
- measureGrid.Items[0], measureGrid.Columns[1]);
- measureGrid.BeginEdit();
- }
- }
- }
- private void measureGrid_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e)
- {
- /*
- row = e.Row.GetIndex();
- (sender as DataGrid).CellEditEnding -= measureGrid_CellEditEnding;
- (sender as DataGrid).CommitEdit();
- var c = mps[row];
- c.Avg = (c.P1 + c.P2 + c.P3 + c.P4 + c.P6 + c.P7 + c.P8 + c.P9 + c.P10) / (nextCol - 1);
- c.Grade = computeGrade(sMi16, c.Avg, kind, "-");
- (sender as DataGrid).CellEditEnding += measureGrid_CellEditEnding;
- */
- }
- private void measureGrid_LostFocus(object sender, RoutedEventArgs e)
- {
- /*
- measureGrid.LostFocus -= measureGrid_LostFocus;
- measureGrid.Items.Refresh();
- measureGrid.LostFocus += measureGrid_LostFocus;
- */
- }
- private void measureGrid_LostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
- {
- //measureGrid.Items.Refresh();
- }
- private void commitBtn_Click(object sender, RoutedEventArgs e)
- {
- if (measureGrid.ItemsSource == null)
- return;
- var now = DateTime.Now;
- var id = Utils.getSetting("currentMachine");
- double sum = 0;
- int count = 0;
- List<List<float>> s = new List<List<float>>();
- _isExisting = true;
- Dictionary<string, List<double>> sumType = new Dictionary<string, List<double>>();
- foreach (var item in measureGrid.Items)
- {
- //Console.WriteLine(item);
- MeasurePoint mp = item as MeasurePoint;
- if (mp.Avg == null)
- {
- mp.Avg = 0;
- }
- if (mp.Avg == 0)
- continue;
- if (mp.Grade == null)
- {
- mp.Grade = "-";
- }
- if (mp.ResultGrade == null)
- {
- mp.ResultGrade = "-";
- }
- /*
- if (mp.Type == "MID" && this.isMiddle == false)
- continue;
- if (mp.Type == "IN*" && _isIn == false)
- continue;
- */
- if (sumType.ContainsKey(mp.Type.Trim()) == false)
- {
- sumType[mp.Type.Trim()] = new List<double>();
- }
- (sumType[mp.Type.Trim()] as List<double>).Add(mp.Avg);
- string sql = string.Format(" insert into data(lot_no, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, row_no, avg, grade, rgrade, r_type, created_at, updated_at, ndata, sub_order, machine_id, code, header) " +
- " values ('{0}', {1}, {2}, {3}, {4}, {5}, {6}, {7}, {8}, {9}, {10}, {11}, {12}, '{13}', '{14}', '{15}', '{16}', '{17}', {18}, {19}, {20}, '{21}', '{22}' )"
- , lotNo.Text.Trim(), mp.P1, mp.P2, mp.P3, mp.P4, mp.P5, mp.P6, mp.P7, mp.P8, mp.P9, mp.P10, mp.Count, mp.Avg, mp.Grade.Trim(), mp.ResultGrade.Trim(), mp.Type.Trim(), now, now, nextCol, mp.SubOrder, id, code.Text.Trim(), this.header);
- sum += mp.Avg;
- //var s0 = lotNo.Text.Trim();
- /*
- var tempList = new List<float>();
- for(int i = 1; i < nextCol; i++){
- tempList.Add(mp.GetValue("P"+i));
-
- }
- s.Add(tempList);
- */
- count++;
- using (SqlCommand command = new SqlCommand(sql, proConn))
- {
- command.ExecuteNonQuery();
- }
- }
- //Math.Round(
- int i = 0;
- string[] keys = new string[sumType.Keys.Count];
- sumType.Keys.CopyTo(keys, 0);
- for (int k = 0; k < keys.Length; k++)
- {
- keys[k] = "'" + keys[k] + "'";
- }
- //List<string> avgValues = new List<string>();
- string[] values = new string[sumType.Keys.Count];
- int j = 0;
- string[] columns = new string[sumType.Keys.Count];
- string[] columnValues = new string[sumType.Keys.Count];
- foreach (var name in sumType)
- {
- var temp = name.Value as List<double>;
- double st = 0.0;
- foreach (double n in temp)
- {
- st += n;
- }
- values[j] = Math.Round((double)(st / temp.Count), 2).ToString();
- columns[j] = "avg" + j + "_name";
- columnValues[j] = "avg" + j;
- j++;
- }
- double avg = Math.Round(sum / count, 2);
- string grade = "-";
- if (Convert.ToInt32(sMi16) <= Convert.ToInt32(sMi20))
- {
- grade = computeGrade(sMi16, avg, kind, "-", "OUT");
- }
- else
- {
- if (Convert.ToInt32(sMi20) == 0)
- grade = computeGrade(sMi16, avg, kind, "-", "OUT");
- else
- grade = computeGrade(sMi20, avg, kind, "-", "OUT");
- }
- try
- {
- string sql2 = string.Format("insert into lot_summary(lot_no, created_at, avg, code, start_time, end_time, grade, machine_id, " + String.Join(",", columns) + "," + String.Join(",", columnValues) + ") values('{0}', '{1}', {2}, '{3}', '{4}', '{5}', '{6}', {7}, {8}, {9})",
- lotNo.Text.Trim(), now, avg, code.Text.Trim(), _startUsing, now, grade.Trim(), id, String.Join(",", keys), String.Join(",", values
- ));
- using (SqlCommand command = new SqlCommand(sql2, proConn))
- {
- command.ExecuteNonQuery();
- }
- _updated_at = now.ToString();
- PrintLabel(lotNo.Text, now);
- MessageBox.Show("Commit Complete");
- lotNo.Focus();
- lotNo.SelectAll();
- }
- catch (Exception ex)
- {
- MessageBox.Show("Data Input Error "+ ex.Message);
- }
- }
- private void PrintLabel(string lotNo, DateTime dt)
- {
- string sql = string.Format("select * from data where lot_no = '{0}' and created_at = '{1}' order by id", lotNo, dt);
- SqlDataReader reader = Utils.Query(proConn, sql);
- string s = "";
- int n = 0;
- List<double> outs = new List<double>();
- List<double> ins = new List<double>();
- bool outValid = false;
- bool inValid = false;
- string inAvg = "";
- string outAvg = "";
- int row = 0;
- int nrow = 0;
- while (reader.Read())
- {
- nrow++;
- n = Convert.ToInt32(reader["ndata"]);
- string r_type = reader["r_type"].ToString();
- try
- {
- r_type = r_type.Substring(0, 3);
- }
- catch
- {
- ;
- }
- s += string.Format("{0,3}", r_type.ToUpper()) + " ";
- for (int i = 1; i <= n; i++)
- {
- if (n > 3)
- {
- s += string.Format("{0,-3:0.00}", Convert.ToDouble(reader["p" + i])) + " ";
- }
- else
- {
- s += string.Format("{0,-3:0.00}", Convert.ToDouble(reader["p" + i])) + " ";
- }
-
- row++;
- }
- //s = s.Trim();
- var grade = reader["grade"].ToString().Trim();
- var rgrade = reader["rgrade"].ToString().Trim();
- try
- {
- if (n >= 5)
- rgrade = rgrade.Substring(0, 2);
- }
- catch
- {
- ;
- }
- //if (reader["rgrade"].ToString().ToLower() != "ok")
- //{
- // s += string.Format(" {0,-6:*0.00*}", Convert.ToDouble(reader["avg"])) + " " + string.Format("{0,-2}",grade) + " " + rgrade;
- //}
- //else
- //{
- if (n >= 5)
- {
- s += string.Format("{0,5:0.00}", Convert.ToDouble(reader["avg"])) + " " + string.Format("{0,-2}", grade) + " " + rgrade;
- }
- else
- {
- s += string.Format("{0,7:0.00}", Convert.ToDouble(reader["avg"])) + " " + string.Format("{0,-2}", grade) + " " + rgrade;
- }
- //}
- //s = s.Trim();
- s += "\n";
-
- /*
- UPP,UPPE = Out
- LOW,LOWE = In
- Rim = Out
- Base =In
- Soko = In
- IN* = In
- */
- if (r_type.ToUpper() == "OUT" || r_type.ToUpper() == "TOP" || r_type.ToUpper() == "FA1" || r_type.ToUpper() == "UPP" || r_type.ToUpper() == "UPPE" || r_type.ToUpper() == "RIM")
- {
- outs.Add(Convert.ToDouble(reader["avg"]));
- }
- if (r_type.ToUpper() == "IN" || r_type.ToUpper() == "UNDER" || r_type.ToUpper() == "UND" || r_type.ToUpper() == "FA2" || r_type.ToUpper() == "LOW" || r_type.ToUpper() == "LOWE" || r_type.ToUpper() == "BASE" || r_type.ToUpper() == "SOKO" || r_type.ToUpper() == "IN*")
- {
- ins.Add(Convert.ToDouble(reader["avg"]));
- }
- }
- //string avg = string.Format("{0.00}", Convert.ToDouble(reader["avg"]));
-
- double[] inArray = new double[] {
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
- double[] outArray = new double[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
- double sumIns = 0;
- double sumOuts = 0;
-
- for (int i = 0; i < ins.Count; i++)
- {
- inArray[i] = ins[i];
- sumIns += ins[i];
- }
- for (int i = 0; i < outs.Count; i++)
- {
- outArray[i] = outs[i];
- sumOuts += outs[i];
- }
- double avgIns = 0;
- if (ins.Count == 0)
- avgIns = 0;
- else
- avgIns = sumIns / ins.Count;
-
- double avgOut = 0;
- if(outs.Count == 0 )
- avgOut = 0;
- else
- avgOut = sumOuts / outs.Count;
-
- reader.Close();
- sql = string.Format("select m.name , ls.avg, ls.grade, ls.start_time, ls.end_time, ls.code from lot_summary ls, machines m where ls.lot_no = '{0}' and ls.created_at = '{1}' and ls.machine_id = m.id", lotNo, dt);
- reader = Utils.Query(proConn, sql);
- var temp = list;
- var types = string.Join("/", temp.ToArray());
- string code = "";
- string et = "";
- while (reader.Read())
- {
- code = reader["code"].ToString();
- s += string.Format("{0} Use {1}Times {2} AVG {3:0.00} {4}\n", reader["name"].ToString(), UsingTimeTB.Text.Trim(), types, Convert.ToDouble(reader["avg"]), reader["grade"].ToString());
- var startTime = Convert.ToDateTime(reader["start_time"]);
- var endTime = Convert.ToDateTime(reader["end_time"]);
- et = string.Format("{0:dd/MM/yyyy HH:mm:ss}", endTime);
- s += string.Format("Date:{0:dd/MM/yyyy} Time:{1:HH:mm}-{2:HH:mm}\n", startTime, startTime, endTime);
- }
- code = code.Replace("-", "");
- string tableName = "";
- try
- {
- accessConnEMASTER = new OleDbConnection(strAccessConnEMASTER);
- accessConnEMASTER.Open();
- }
- catch (Exception ex)
- {
- MessageBox.Show("Error: Failed to create e-master connection. \n{0}", ex.Message);
- }
- try
- {
- accessConnBELMASTER = new OleDbConnection(strAccessConnBELMASTER);
- accessConnBELMASTER.Open();
- }
- catch (Exception ex)
- {
- MessageBox.Show("Error: Failed to create e-master connection. \n{0}", ex.Message);
- }
- try
- {
- accessConnMGMASTER = new OleDbConnection(strAccessConnMGMASTER);
- accessConnMGMASTER.Open();
- }
- catch (Exception ex)
- {
- MessageBox.Show("Error: Failed to create e-master connection. \n{0}", ex.Message);
- }
- try
- {
- accessConnVMASTER = new OleDbConnection(strAccessConnVMASTER);
- accessConnVMASTER.Open();
- }
- catch (Exception ex)
- {
- MessageBox.Show("Error: Failed to create e-master connection. \n{0}", ex.Message);
- }
- if (code[0] == '1' || code[0] == '9')
- {
- tempConn = accessConnVMASTER;
- tableName = "V-REREKI";
- }
- if (code[0] == '2')
- {
- tempConn = accessConnMGMASTER;
- tableName = "MG-REREKI";
- }
- if (code[0] == '3' || code[0] == '4')
- {
- tempConn = accessConnEMASTER;
- tableName = "E-REREKI";
- }
- if (code[0] == '5')
- {
- tempConn = accessConnBELMASTER;
- tableName = "BEL-REREKI";
- }
- OleDbCommand deleteCommand = new OleDbCommand("delete from ["+tableName+"] where RE01 = '"+code+"' and RE02 = '"+lotNo+"'", tempConn);
- deleteCommand.ExecuteNonQuery();
- //int lotCount = (int)selectCountCommand.ExecuteScalar();
- //if (lotCount == 0)
- //{
- string rereki = string.Format("insert into [" + tableName + "](RE01, RE02, RE03,RE04, [OB-O1], [OB-O2], [OB-O3], [OB-O4], [OB-O5], [OB-O6], [OB-O7], [OB-O8],[OB-O9], [OB-O10], [OB-O11], [OB-O12], [OB-O13], [OB-O14], [OB-O15],[OB-O16], [OB-O17], [OB-O18], [OB-O19], [OB-O20], [OB-O21], [OB-O22], [OB-O23], [OB-O24], [OB-O25],[OB-O26], [OB-O27],[OB-O28],[OB-O29],[OB-O30], [OB-I1], [OB-I2], [OB-I3], [OB-I4], [OB-I5], [OB-I6], [OB-I7], [OB-I8], [OB-I9], [OB-I10], [OB-I11], [OB-I12], [OB-I13], [OB-I14], [OB-I15], [OB-I16], [OB-I17], [OB-I18], [OB-I19], [OB-I20], [OB-I21], [OB-I22], [OB-I23], [OB-I24], [OB-I25], [OB-I26], [OB-I27], [OB-I28], [OB-I29], [OB-I30], [OB-O], [OB-I])"
- + "values('{0}', '{1}', '{2}', {3}, {4}, {5}, {6}, {7}, {8}, {9}, {10}, {11}, {12},{13}, {14}, {15},{16}, {17}, {18},{19},{20},{21},{22}, {23},{24}, {25}, {26}, {27}, {28},{29},{30},{31},{32},{33},{34},{35},{36}, {37},{38}, {39},{40}, {41},{42},{43},{44},{45},{46},{47},{48}, {49},{50}, {51}, {52}, {53}, {54}, {55}, {56}, {57}, {58}, {59},{60},{61},{62},{63},{64}, {65})", code, lotNo, et, nrow, outArray[0], outArray[1], outArray[2], outArray[3], outArray[4], outArray[5], outArray[6], outArray[7], outArray[8], outArray[9], outArray[10], outArray[11], outArray[12], outArray[13], outArray[14], outArray[15], outArray[16], outArray[17], outArray[18], outArray[19], outArray[20], outArray[21], outArray[22], outArray[23], outArray[24], outArray[25], outArray[26], outArray[27], outArray[28], outArray[29], inArray[0], inArray[1], inArray[2], inArray[3], inArray[4], inArray[5], inArray[6], inArray[7], inArray[8], inArray[9], inArray[10], inArray[11], inArray[12], inArray[13], inArray[14], inArray[15], inArray[16], inArray[17], inArray[18], inArray[19], inArray[20], inArray[21], inArray[22], inArray[23], inArray[24], inArray[25], inArray[26], inArray[27], inArray[28], inArray[29], avgOut, avgIns);
- OleDbCommand insertCmd = new OleDbCommand(rereki, tempConn);
- //MessageBox.Show("re = " + rereki);
- insertCmd.ExecuteNonQuery();
- //close all db access
- accessConnBELMASTER.Close();
- accessConnEMASTER.Close();
- accessConnMGMASTER.Close();
- accessConnVMASTER.Close();
- //}
-
- reader.Close();
- //Utils.Query(proConn, "select P1, P2, P3, P4, P5, P6, P7, P8, P9, P10 from lot_summary where lot_no =
- //Printer.Print(s, n); // 14/06/19
- printMultipage(s, n); // latest
- //Printer.Print(s);
- //var p = new Printer();
- }
- void printMultipage(string s, int n)
- {
- var lines = s.Split('\n');
- const int NL = 8;
- var el = lines.Count() / NL;
- string postFix = "";
-
- for (var i = 0; i < el; i++)
- {
- var pages = String.Format("Lot No. {0} {1}\n", lotNo.Text, this.obCondition);
- //pages += String.Format("Std.Wb={0:0.##}g\nStd.I-5-5={1:0.##}g\n", stdWbUI.Text, i55UI.Text);
- for (var j = 0; j < NL; j++)
- {
- pages += lines[j + (i * NL)] + "\n";
- }
- Printer.Print(pages);
- }
- /*
- Printer p = new Printer();
- Console.WriteLine("printer print");
- p.PrintDoc(s);*/
- var remain = lines.Count() % NL;
- if (remain == 0)
- return;
- var pager = String.Format("Lot No. {0} {1}\n", lotNo.Text, this.obCondition);
- //pager += String.Format("Std.Wb={0:0.##}g\nStd.I-5-5={1:0.##}g\n", stdWbUI.Text, i55UI.Text);
- for (var j = el * NL; j < lines.Count(); j++)
- {
- if (lines[j] == "")
- continue;
- pager += lines[j] + "\n";
- }
- Printer.Print(pager);
- }
- private void measureGrid_LoadingRow(object sender, DataGridRowEventArgs e)
- {
- /*
- DataGridRow c = e.Row;
- MeasurePoint mp = e.Row.Item as MeasurePoint;
- if (mp.Type == "MID" && this.isMiddle == false)
- {
- c.Visibility = Visibility.Collapsed;
- }
- if (mp.Type == "IN*" && _isIn == false)
- {
- c.Visibility = Visibility.Collapsed;
- }
- */
- }
- private void addMiddleBtn_Click(object sender, RoutedEventArgs e)
- {
- if (measureGrid.ItemsSource == null)
- return;
- _lastAction.Push("middle");
- this.isMiddle = !this.isMiddle;
- if (this.isMiddle == false)
- {
- middleText.Text = "Add Middle";
- RemoveMid();
- }
- else
- {
- middleText.Text = "Remove Middle";
- EditMIDWindow w = new EditMIDWindow();
- w.ShowDialog();
- AddMid();
- }
- //this.measureGrid.CommitEdit();
- measureGrid.Items.Refresh();
- }
- private void RemoveMid()
- {
- list.Remove("MID");
- ObservableCollection<MeasurePoint> temp = new ObservableCollection<MeasurePoint>();
- foreach (var m in mps)
- {
- if (m.Type != "MID")
- {
- temp.Add(m);
- }
- }
- mps = temp;
- measureGrid.ItemsSource = null;
- measureGrid.ItemsSource = mps;
- }
- private void AddMid()
- {
- list.Insert(1, "MID");
- ObservableCollection<MeasurePoint> temp = new ObservableCollection<MeasurePoint>();
- foreach (var m in mps)
- {
- temp.Add(m);
- if (m.SubOrder == 1)
- {
- temp.Add(new MeasurePoint() { Type = "MID", SubOrder = m.SubOrder + 1, Count = m.Count });
- }
- }
- mps = temp;
- measureGrid.ItemsSource = null;
- measureGrid.ItemsSource = mps;
- }
- private void deleteData_Click(object sender, RoutedEventArgs e)
- {
- this.currentMP.setValue(currentColumn, 0);
- this.computeValues(currentMP, true);
- measureGrid.Items.Refresh();
- }
- private void measureGrid_BeginningEdit(object sender, DataGridBeginningEditEventArgs e)
- {
- this.currentColumn = e.Column.Header.ToString();
- this.currentMP = (MeasurePoint)e.Row.Item;
- cellIndicattor.Text = "(" + currentMP.Type + "-" + currentMP.Count + ", " + currentColumn + ")";
- }
- private void measureGrid_SelectedCellsChanged(object sender, SelectedCellsChangedEventArgs e)
- {
- //this.currentMP = (MeasurePoint)measureGrid.CurrentItem;
- //this.currentColumn = measureGrid.CurrentColumn.Header.ToString();
- //cellIndicattor.Text = "("+currentMP.Type + "-" +currentMP.Count+", "+currentColumn+")";
- }
- private void measureGrid_CurrentCellChanged(object sender, EventArgs e)
- {
- try
- {
- this.currentColumn = measureGrid.CurrentColumn.Header.ToString();
- this.currentMP = (MeasurePoint)measureGrid.CurrentItem;
- cellIndicattor.Text = "(" + currentMP.Type + "-" + currentMP.Count + ", " + currentColumn + ")";
- //this.computeValues(currentMP);
- }
- catch (NullReferenceException ne) { }
- }
- private void saveCellBtn_Click(object sender, RoutedEventArgs e)
- {
- measureGrid.Focus();
- if (currentColumn == null)
- return;
- if (_isOver == true)
- return;
- /*
- if(_isFirstMeasure == true){
- _startUsing = DateTime.Now;
- _isFirstMeasure = false;
- }*/
- if (currentColumn != "Average" && currentColumn != "Grade" && currentColumn != "Result Grade")
- {
- this.currentMP.setValue(currentColumn, Convert.ToDouble(readingBox.Text));
- //var c = measureGrid.SelectedValue;
- this.computeValues(currentMP, true);
- }
- try
- {
- var info = measureGrid.CurrentColumn;
- var item = measureGrid.CurrentItem as MeasurePoint;
- int col = info.DisplayIndex;
- var mp = (MeasurePoint)measureGrid.CurrentItem;
- int row = mps.IndexOf(mp);
- //measureGrid.RaiseEvent(new RoutedEventArgs(DataGrid.rowediten));
- //MessageBox.Show("row " + item.Count.ToString());
- //MessageBox.Show("row " + mps.IndexOf(mp).ToString());
- //MessageBox.Show("col " + info.DisplayIndex.ToString());
- measureGrid.Items.Refresh();
- measureGrid.Focus();
- if (col < nextCol)
- {
- measureGrid.CurrentCell = new DataGridCellInfo(
- measureGrid.Items[row], measureGrid.Columns[col + 1]);
- measureGrid.BeginEdit();
- }
- else
- {
- try
- {
- //this.computeValues(currentMP, true);
- measureGrid.CurrentCell = new DataGridCellInfo(
- measureGrid.Items[row + 1], measureGrid.Columns[1]);
- measureGrid.SelectedItem = measureGrid.Items[row + 1];
- measureGrid.BeginEdit();
- }
- catch
- {
- measureGrid.CurrentCell = new DataGridCellInfo(
- measureGrid.Items[0], measureGrid.Columns[1]);
- measureGrid.SelectedItem = measureGrid.Items[0];
- measureGrid.BeginEdit();
- }
- }
- }
- catch
- {
- ;
- }
- updateUsingTime(this.header);
- }
- private void updateUsingTime(string p, int n = -1)
- {
- switch (p)
- {
- case "OB":
- _obCount++;
- _usingTime = _obCount;
- if (_obCount > _obLimit)
- {
- _obCount = _obLimit;
- Alert alert = new Alert();
- alert.SetAlertMsg("OB Header Exceeds Usage Limit");
- alert.ShowDialog();
- _isOver = true;
- }
- _isOver = false;
- if (n == -1)
- {
- Utils.Query(_opConn, "update UsingTime set ob = " + _obCount);
- UsingTimeTB.Text = _obCount.ToString();
- }
- else
- {
- Utils.Query(_opConn, "update UsingTime set ob = " + n);
- UsingTimeTB.Text = n.ToString();
- _obCount = n;
- }
- break;
- case "OC":
- _ocCount++;
- _usingTime = _ocCount;
- if (_ocCount > _ocLimit)
- {
- _ocCount = _ocLimit;
- Alert alert = new Alert();
- alert.SetAlertMsg("OC Header Exceeds Usage Limit");
- alert.ShowDialog();
- _isOver = true;
- }
- _isOver = false;
- if (n == -1)
- {
- Utils.Query(_opConn, "update UsingTime set oc = " + _ocCount);
- UsingTimeTB.Text = _ocCount.ToString();
- }
- else
- {
- Utils.Query(_opConn, "update UsingTime set oc = " + n);
- UsingTimeTB.Text = n.ToString();
- _ocCount = n;
- }
- break;
- case "RH":
- _rhCount++;
- _usingTime = _rhCount;
- if (_rhCount > _rhLimit)
- {
- _rhCount = _rhLimit;
- Alert alert = new Alert();
- alert.SetAlertMsg("RH Header Exceeds Usage Limit");
- alert.ShowDialog();
- _isOver = true;
- }
- _isOver = false;
- if (n == -1)
- {
- Utils.Query(_opConn, "update UsingTime set rh = " + _rhCount);
- UsingTimeTB.Text = _rhCount.ToString();
- }
- else
- {
- Utils.Query(_opConn, "update UsingTime set rh = " + n);
- UsingTimeTB.Text = n.ToString();
- _rhCount = n;
- }
- break;
- default:
- //MessageBox.Show("Please Find a Lot NO First");
- break;
- }
- }
- public void refreshUsingTime()
- {
- string p = this.header;
- string sql = string.Format("select {0} as n from UsingTime", this.header.ToLower());
- var reader = Utils.Query(_opConn, sql);
- reader.Read();
- UsingTimeTB.Text = reader["n"].ToString();
- if (p == "OB")
- {
- _obCount = Convert.ToInt32(reader["n"]);
- }
- else if (p == "OC")
- {
- _ocCount = Convert.ToInt32(reader["n"]);
- }
- }
- private void IntranetBtn_Click(object sender, RoutedEventArgs e)
- {
- SqlDataReader reader = Utils.Query(proConn, "select value from sys_configs where title = 'internal_url'");
- reader.Read();
- string target = reader["value"].ToString();
- //string target = reader["value"].Read().ToString();
- try
- {
- System.Diagnostics.Process.Start(target);
- }
- catch (System.ComponentModel.Win32Exception noBrowser)
- {
- if (noBrowser.ErrorCode == -2147467259)
- MessageBox.Show(noBrowser.Message);
- }
- catch (System.Exception other)
- {
- MessageBox.Show(other.Message);
- }
- reader.Close();
- }
- private void undoBtn_Click(object sender, RoutedEventArgs e)
- {
- if (_lastAction.Count == 0)
- return;
- string action = _lastAction.Pop();
- if (action == "middle")
- {
- this.isMiddle = !this.isMiddle;
- if (this.isMiddle == false)
- {
- middleText.Text = "Add Middle";
- RemoveMid();
- }
- else
- {
- middleText.Text = "Remove Middle";
- AddMid();
- }
- }
- if (action == "in")
- {
- _isIn = !_isIn;
- if (_isIn == false)
- {
- inText.Text = "Add IN*";
- RemoveIn();
- }
- else
- {
- inText.Text = "Remove IN*";
- AddIn();
- }
- }
- else if (action == "row")
- {
- for (int i = 0; i < list.Count; i++)
- {
- mps.RemoveAt(mps.Count - 1);
- }
- }
- else if (action == "column")
- {
- measureGrid.Columns.ElementAt(nextCol--).Visibility = Visibility.Hidden;
- foreach (var item in measureGrid.Items)
- {
- //Console.WriteLine(item);
- MeasurePoint c = item as MeasurePoint;
- c.setValue((nextCol + 1).ToString(), (float)0.0);
- c.Avg = (c.P1 + c.P2 + c.P3 + c.P4 + c.P6 + c.P7 + c.P8 + c.P9 + c.P10) / (nextCol);
- c.Avg = Math.Round(c.Avg, 2);
- if (c.SubOrder == 1)
- {
- c.Grade = computeGrade(sMi16, c.Avg, kind, "-", c.Type);
- }
- else if (c.SubOrder != 1 && c.Type != "MID" && c.Type != "IN*")
- {
- if (sMi20 != "0")
- c.Grade = computeGrade(sMi20, c.Avg, kind, "-", c.Type);
- else
- c.Grade = computeGrade(sMi16, c.Avg, kind, "-", c.Type);
- }
- }
- }
- else if (action == "remove_column")
- {
- measureGrid.Columns.ElementAt(++nextCol).Visibility = Visibility.Visible;
- foreach (var item in measureGrid.Items)
- {
- //Console.WriteLine(item);
- MeasurePoint c = item as MeasurePoint;
- c.setValue((nextCol).ToString(), (float)0.0);
- computeValues(c, true);
- }
- }
- measureGrid.Items.Refresh();
- }
- private void printBtn_Click(object sender, RoutedEventArgs e)
- {
- if (_isExisting == true)
- {
- PrintLabel(lotNo.Text, Convert.ToDateTime(_updated_at));
- }
- else
- {
- MessageBox.Show("You can print when you have commited data");
- }
- }
- private void agreementBtn_Click(object sender, RoutedEventArgs e)
- {
- var fileName = agreementCB.Text;
- try
- {
- //System.Diagnostics.Process.Start(@"agreements\" + fileName);
- var server = Utils.getSetting("webServerURL");
- string data = string.Format(@"title={0}&empid={1}&password={2}", fileName, GlobalVars.user.empid, GlobalVars.user.password);
- WebAppConnector wp = new WebAppConnector()
- {
- Uri = Utils.getSetting("webServerURL") + "/agreements/title.json",
- Method = "POST",
- PostData = data
- };
- Response r = null;
- try
- {
- r = wp.sendRequest();
- }
- catch
- {
- MessageBox.Show("Cannot connect to webserver :" + server);
- return;
- }
- string ans = (string)r.jsonBody["msg"];
- //Console.WriteLine((JArray)r.jsonBody["roles"]);
- if (r.status == "OK" && ans == "y")
- {
- System.Diagnostics.Process.Start(server + (string)r.jsonBody["url"]);
- }
- else
- {
- MessageBox.Show("Cannot find agreement file");
- }
- }
- catch (Win32Exception ew)
- {
- MessageBox.Show(ew.Message);
- }
- }
- private void thaiMenu_Checked(object sender, RoutedEventArgs e)
- {
- engMenu.IsChecked = false;
- //var selectedItem = comboBoxLanguage.SelectedItem as ComboBoxItem;
- var culture = CultureInfo.GetCultureInfo("th-TH");
- Dispatcher.Thread.CurrentCulture = culture;
- Dispatcher.Thread.CurrentUICulture = culture;
- LocalizationManager.UpdateValues();
- }
- private void engMenu_Checked(object sender, RoutedEventArgs e)
- {
- thaiMenu.IsChecked = false;
- var culture = CultureInfo.GetCultureInfo("en-US");
- Dispatcher.Thread.CurrentCulture = culture;
- Dispatcher.Thread.CurrentUICulture = culture;
- LocalizationManager.UpdateValues();
- }
- private void windowItem_Checked(object sender, RoutedEventArgs e)
- {
- this.WindowStyle = WindowStyle.SingleBorderWindow;
- this.WindowState = WindowState.Normal;
- this.isFullScreen = false;
- fullScreenItem.IsChecked = false;
- }
- private void fullScreenItem_Checked(object sender, RoutedEventArgs e)
- {
- this.WindowStyle = WindowStyle.None;
- this.WindowState = WindowState.Maximized;
- this.isFullScreen = true;
- windowItem.IsChecked = false;
- }
- private void measureGrid_KeyDown(object sender, KeyEventArgs e)
- {
- }
- private void measureGrid_Loaded(object sender, RoutedEventArgs e)
- {
- //MessageBox.Show("Refresh Finish");
- }
- private void measureGrid_SourceUpdated(object sender, DataTransferEventArgs e)
- {
- MessageBox.Show("refresh finish");
- }
- private void measureGrid_ColumnDisplayIndexChanged(object sender, DataGridColumnEventArgs e)
- {
- }
- private void measureGrid_PreviewKeyDown(object sender, KeyEventArgs e)
- {
- }
- private void lotNo_MouseDown(object sender, MouseButtonEventArgs e)
- {
- //lotNo.SelectAll();
- }
- private void lotNo_GotFocus(object sender, RoutedEventArgs e)
- {
- //lotNo.SelectAll();
- }
- private void lotNo_GotKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
- {
- lotNo.SelectAll();
- }
- private void lotNo_GotMouseCapture(object sender, MouseEventArgs e)
- {
- lotNo.SelectAll();
- }
- private void resetBtn_Click(object sender, RoutedEventArgs e)
- {
- updateUsingTime(this.header, 0);
- measureGrid.Focus();
- try
- {
- measureGrid.CurrentCell = new DataGridCellInfo(
- measureGrid.Items[0], measureGrid.Columns[1]);
- measureGrid.SelectedItem = measureGrid.Items[0];
- measureGrid.BeginEdit();
- }
- catch
- {
- }
- }
- private void editUsingTime_Click(object sender, RoutedEventArgs e)
- {
- EditUsingTime editUsingTime = new EditUsingTime();
- editUsingTime.ShowDialog();
- }
- private void addInBtn_Click(object sender, RoutedEventArgs e)
- {
- //measureGrid.ItemsSource = null;
- if (measureGrid.ItemsSource == null)
- return;
- _isIn = !_isIn;
- if (_isIn == false)
- {
- inText.Text = "Add IN*";
- RemoveIn();
- }
- else
- {
- inText.Text = "Remove IN*";
- EditINWindow w = new EditINWindow();
- w.ShowDialog();
- AddIn();
- }
- //ObservableCollection<MeasurePoint> temp = new ObservableCollection<MeasurePoint>();
- _lastAction.Push("in");
- measureGrid.Items.Refresh();
- /*
- for(int i = 0; i < mps.Count; i++){
- var mp = mps[i];
- if(mp.SubOrder == 1){
- mps.Insert(mps.IndexOf(mp) + 1, new MeasurePoint() { Count = mp.Count, Type = "IN*", SubOrder = 3});
- }
- }
- measureGrid.ItemsSource = mps;
- */
- //measureGrid.ItemsSource = null;
- //measureGrid.Items.Add(0, new MeasurePoint() { Count = 1, Type = "In"});
- }
- private void RemoveIn()
- {
- list.Remove("IN*");
- ObservableCollection<MeasurePoint> temp = new ObservableCollection<MeasurePoint>();
- foreach (var m in mps)
- {
- if (m.Type != "IN*")
- {
- temp.Add(m);
- }
- }
- mps = temp;
- measureGrid.ItemsSource = null;
- measureGrid.ItemsSource = mps;
- }
- private void AddIn()
- {
- list.Insert(1, "IN*");
- ObservableCollection<MeasurePoint> temp = new ObservableCollection<MeasurePoint>();
- foreach (var m in mps)
- {
- temp.Add(m);
- if (m.SubOrder == 1)
- {
- temp.Add(new MeasurePoint() { Type = "IN*", SubOrder = m.SubOrder + 1, Count = m.Count });
- }
- }
- mps = temp;
- measureGrid.ItemsSource = null;
- measureGrid.ItemsSource = mps;
- }
- private void dailyCheckBtn_Click(object sender, RoutedEventArgs e)
- {
- _dc = new DailyCheck();
- //_dc.Show();
- _dc.ShowDialog();
- //_dc.ShowDialog();
- }
- private void removeMeasureColumn_Click(object sender, RoutedEventArgs e)
- {
- _lastAction.Push("remove_column");
- measureGrid.Columns.ElementAt(nextCol).Visibility = Visibility.Hidden;
- if (nextCol <= 10)
- {
- measureGrid.Columns.ElementAt(--nextCol).Visibility = Visibility.Visible;
- foreach (var item in measureGrid.Items)
- {
- //Console.WriteLine(item);
- MeasurePoint c = item as MeasurePoint;
- c.setValue((nextCol + 1).ToString(), 0);
- computeValues(c, true);
- }
- measureGrid.Items.Refresh();
- }
- }
- private void lotNo_KeyDown(object sender, KeyEventArgs e)
- {
- if (e.Key == Key.Return)
- {
- //MessageBox.Show("Hello");
- find_Click(null, null);
- }
- }
- private void checkLogin_Click(object sender, RoutedEventArgs e)
- {
- var server = Utils.getSetting("webServerURL");
- //string data = string.Format(@"title={0}", fileName);
- WebAppConnector wp = new WebAppConnector()
- {
- Uri = Utils.getSetting("webServerURL") + "/sites/get_current_user.json",
- Method = "POST",
- PostData = ""
- };
- Response r = null;
- try
- {
- r = wp.sendRequest();
- }
- catch
- {
- MessageBox.Show("Cannot connect to webserver :" + server);
- }
- string ans = (string)r.jsonBody["u"];
- //Console.WriteLine((JArray)r.jsonBody["roles"]);
- }
- private void searchAgreementBtn_Click(object sender, RoutedEventArgs e)
- {
- SearchAgreement sa = new SearchAgreement();
- sa.ShowDialog();
- }
- private void editINStar_Click(object sender, RoutedEventArgs e)
- {
- EditINWindow w = new EditINWindow();
- w.ShowDialog();
- foreach (var item in measureGrid.Items)
- {
- MeasurePoint c = item as MeasurePoint;
- computeValues(c, true);
- }
- measureGrid.Items.Refresh();
- }
- private void editMID_Click(object sender, RoutedEventArgs e)
- {
- EditMIDWindow w = new EditMIDWindow();
- w.ShowDialog();
- foreach (var item in measureGrid.Items)
- {
- MeasurePoint c = item as MeasurePoint;
- computeValues(c, true);
- }
- measureGrid.Items.Refresh();
- }
- private void logoutMenu_Click(object sender, RoutedEventArgs e)
- {
- this.Hide();
- LoginWindow lw = new LoginWindow();
- var r = lw.ShowDialog();
- resetMenu();
- }
- private void about_Click(object sender, RoutedEventArgs e)
- {
- Window1 w = new Window1();
- w.ShowDialog();
- }
- private void Window_Closing(object sender, CancelEventArgs e)
- {
- if (comport.IsOpen)
- {
- comport.Close();
- _clearThread = true;
- }
- }
- }
- }
|