| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915 |
- 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;
- bool _canAuto = false;
- 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;
- List<string> wvs = new List<string>();
-
- 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;
- double v = Convert.ToDouble(outputString);
-
- //saveCellBtn_Click(null, null);
- if ( _canAuto == true )
- {
- //AutoSaveData();
- if ( (v != 0) && (_prevValue != outputString))
- {
- wvs.Add(outputString);
- var iw = wvs.Count(i => i == outputString);
-
- if (iw >= 15)
- {
- wvs.Clear();
- _prevValue = outputString;
-
- saveCellBtn.RaiseEvent(new RoutedEventArgs(Button.ClickEvent, saveCellBtn));
- }
- else
- {
- _prevValue = "";
- }
- }
- else
- {
- wvs.Clear();
- }
-
-
- //saveCellBtn.RaiseEvent(new RoutedEventArgs(Button.ClickEvent, saveCellBtn));
- }
- }
- 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());
- if (measureGrid.CurrentItem == null)
- return;
- 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>>();
-
- _canAuto = false;
- changeAutoBtn();
-
- 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 (_canAuto != true)
- return;
- if (currentColumn == null)
- return;
-
- if (_isOver == true)
- return;
- /*
- if(_isFirstMeasure == true){
- _startUsing = DateTime.Now;
- _isFirstMeasure = false;
- }*/
- _canAuto = false;
- changeAutoBtn();
- 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
- {
- ;
- }
- _canAuto = true;
- changeAutoBtn();
- 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 autoBtn_Click(object sender, RoutedEventArgs e)
- {
- _canAuto = !_canAuto;
- changeAutoBtn();
-
-
- }
- void changeAutoBtn()
- {
- if (_canAuto == true)
- {
- autoBtn.Background = Brushes.Red;
- autoBtn.Content = "Stop Auto";
- }
- else
- {
- autoBtn.Background = Brushes.Green;
- autoBtn.Content = "Start Auto";
- }
- }
-
- 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;
- }
- }
-
-
-
-
-
-
-
- }
- }
|