public void MakePacket(bool swap) { String err; StructXMLParser.ItemsToPacket(this.Items, swap, PacketBuffer, out PacketDataSize, IsDynamicPacket); //if (err != null && err.Length > 0) throw new Exception(err); }
public DlgMsgMaker(CPacketStruct ns, String saveFile, bool swapWhenMakePacket) : base() { InitializeComponent(); T_Comment.Text = ns.Infos.Comment; String dir = saveFile.Substring(0, saveFile.LastIndexOf("\\")); if (Directory.Exists(dir) == false) { Directory.CreateDirectory(dir); } _xmlFile = saveFile.Substring(0, saveFile.LastIndexOf("\\") + 1) + "msg.xml"; _saveFile = saveFile; _swapWhenMakePacket = swapWhenMakePacket; _ns = ns; if (ns == null) { if (File.Exists(_xmlFile)) { //List<CStructItem> items = CustomParser.XMLParser.FromXml(_xmlFile); T_Msg.Text = StructXMLParser.XmlToCode(_xmlFile); } else if (File.Exists(_saveFile)) { T_Msg.Text = File.ReadAllText(_saveFile); } } else { T_Msg.Text = ns.NativeText; } B_Help.Click += new EventHandler(B_Help_Click); /* * if (ns.nativeText != null && ns.nativeText.Length > 0) * { * T_Msg.Text = ns.nativeText; * } * else * { * try * { * if (File.Exists(_xmlFile)) * { * //List<CStructItem> items = CustomParser.XMLParser.FromXml(_xmlFile); * T_Msg.Text = XMLParser.ToCode(_xmlFile); * } * else if (File.Exists(_saveFile)) * { * T_Msg.Text = File.ReadAllText(_saveFile); * } * } * catch { } * } */ }
public void setNativeText(string str, bool swapWhenMakePacket) { NativeText = str; //Items = StructXMLParser.CodeToItems(str, this); if (this.IsDynamicPacket == false) { MakePacket(swapWhenMakePacket); } }
void B_Save_Click(object sender, EventArgs e) { for (int i = 0; i < _modifiedItems.Count; i++) { CPacketStruct item = _modifiedItems.Values.ElementAt(i); String name = _modifiedItems.Keys.ElementAt(i); StructXMLParser.ItemsToXml(item.Items, _packetDir + "\\" + name + "\\Msg.xml", item.Infos); } _modifiedItems.Clear(); P_Table.RowStyles[3] = new RowStyle(System.Windows.Forms.SizeType.Absolute, 0); P_Table.RowStyles[3] = new RowStyle(System.Windows.Forms.SizeType.Absolute, 25); }
public void SaveFile() { //File.WriteAllText(_saveFile, T_Msg.Text); _ns.NativeText = T_Msg.Text;//.setNativeText(ss); //_ns.Items = StructXMLParser.CodeToItems(T_Msg.Text, _ns); if (_ns.IsDynamicPacket == false) { _ns.MakePacket(_swapWhenMakePacket); } CStructInfo info = new CStructInfo(T_Comment.Text, DateTime.Now); StructXMLParser.ItemsToXml(_ns.Items, _xmlFile, info); }
public void AddNewItem(CPacketStruct parserObj = null, String name = null) { #region 기존에 같은 이름이 있는지 검사후 있으면 이름 붙여줌. List <object> names = V_Data.GetAColumnData(0); name = (name == null)?"Untitled" : name; String newName = name; int count = 0; while (Directory.Exists(_packetDir + "\\" + (newName)) == true) { newName = name + (count++); } #endregion #region 새 디렉토리 만들고 Msg.txt파일 만들어 내용 넣어줌. String newDir = _packetDir + "\\" + newName; if (Directory.Exists(newDir) == false) { Directory.CreateDirectory(newDir); } if (parserObj == null) { parserObj = new CPacketStruct(); DlgMsgMaker dlg = new DlgMsgMaker(parserObj, newDir + "\\Msg.txt", _endian == Endians.Big); DialogResult result = dlg.ShowDialog(); if (result == DialogResult.Abort || result == DialogResult.Cancel) { return; } //parserObj.Items = StructXMLParser.CodeToItems(parserObj.NativeText, parserObj); StructXMLParser.ItemsToXml(parserObj.Items, newDir + "\\Msg.xml", parserObj.Infos); } else { parserObj.MakeMsgText(); CPacketStruct oldObj = parserObj; parserObj = new CPacketStruct(); parserObj.NativeText = oldObj.NativeText; //parserObj.Items = StructXMLParser.CodeToItems(oldObj.NativeText, parserObj); StructXMLParser.ItemsToXml(parserObj.Items, newDir + "\\Msg.xml", parserObj.Infos); } #endregion #region 표에 줄 삽입 Dictionary <String, object> rels = new Dictionary <string, object>(); parserObj.IsStringWithNullEnd = _isStringWithNullEnd; parserObj.Endian = _endian; parserObj.StringEncoding = _strEncoding; String msgName = newName; bool integrity; try { parserObj.MakePacket(_endian == Endians.Big); integrity = true; } catch (Exception e) { MessageBox.Show(msgName + ":" + e.Message); integrity = true; } rels["integrity"] = integrity; rels["parser"] = parserObj; rels["msg"] = parserObj.NativeText; EasyGridRow row = V_Data.AddARow(rels, new object[] { false, msgName, "edit", "send", "X", "", }); if (integrity == false) { (row[(int)Titles.name] as EasyGridTextBoxCell).FontColor = Color.Red; } #endregion V_Data.RefreshList(); saveNameList(); }
public void initList() { V_Data.ClearData(); //if (packetDir != null) _packetDir = packetDir; if (_packetDir == null) { return; } String listDir = _packetDir;// = _baseDir+"\\PacketList"; String orderFile = _packetDir + "\\ListOrder.txt"; makeNewOrderIfNotExists(); List <String> listOrder = new List <string>(); #region 순서를 가져옴 StreamReader sr = new StreamReader(File.OpenRead(orderFile)); String line; //String rootDir = Directory.GetCurrentDirectory() + "\\"; while ((line = sr.ReadLine()) != null) { if (line.Trim().Length > 0) { listOrder.Add(line); //if (line.IndexOf(rootDir) == 0) listOrder.Add(line); //else listOrder.Add(rootDir + line); } } sr.Close(); #endregion String[] dirs = Directory.GetDirectories(_packetDir); for (int i = 0; i < dirs.Length; i++) { String name = dirs[i].Substring(dirs[i].LastIndexOf("\\") + 1); if (name.Equals("Backups")) { continue; //백업디렉토리는 제외.. } if (listOrder.Contains(name) == false) //만일 리스트에 없으면.. { File.Delete(orderFile); makeNewOrderIfNotExists(); listOrder.Clear(); for (int d = 0; d < dirs.Length; d++)//새로만듬.. { name = dirs[i].Substring(dirs[i].LastIndexOf("\\") + 1); if (name.Equals("Backups")) { continue; //백업디렉토리는 제외.. } listOrder.Add(name); } break; } } //if (Directory.Exists(listDir) == false) Directory.CreateDirectory(listDir); //else { //CStructParser parser;// = new CStructParser(); //foreach (String dir in Directory.GetDirectories(listDir)) foreach (String name in listOrder) { String Msg = ""; bool integrity = false; String path = _packetDir + "\\" + name; String msgXml = path + "\\Msg.xml"; String msgTxt = path + "\\Msg.txt"; CPacketStruct parser = new CPacketStruct(); IList <CPacketItem> itemsList = null; Dictionary <String, object> rels = new Dictionary <string, object>(); //try { if (File.Exists(msgXml)) { //try { itemsList = StructXMLParser.XmlToItems(msgXml, parser); Msg = StructXMLParser.ItemsToCode(itemsList); integrity = true; } //catch { /* * integrity = false; * if (File.Exists(msgTxt)) * { * Msg = File.ReadAllText(msgTxt); * } * else * { * * MessageBox.Show(msgXml + "이나 "+ msgTxt+" 가 없습니다.메시지를 다시 작성하십시오.");//필수파일 * File.WriteAllText(msgTxt, ""); * * } */ //} } else if (File.Exists(msgTxt)) { Msg = File.ReadAllText(msgTxt); } else { //MessageBox.Show(msgXml + "이나 " + msgTxt + " 가 없습니다.메시지를 다시 작성하십시오.");//필수파일 if (Directory.Exists(path)) { Directory.Delete(path, true); } //File.WriteAllText(msgTxt,""); } } //catch { // continue; } String comment = ""; if (File.Exists(path + "\\Comment.txt")) { comment = File.ReadAllText(path + "\\Comment.txt"); } Dictionary <String, String> states = new Dictionary <string, string>(); if (File.Exists(path + "\\States.txt")) { String[] lines = File.ReadAllLines(path + "\\States.txt"); for (int i = 0; i < lines.Length; i++) { String[] tokens = lines[i].Split("=;".ToCharArray(), StringSplitOptions.RemoveEmptyEntries); if (tokens.Length > 1) { states[tokens[0].ToLower().Trim()] = tokens[1].ToLower().Trim(); } } } bool isChecked = (states.ContainsKey("check")) ? (states["check"].Equals("y") || states["check"].Equals("true")) : false; parser.IsStringWithNullEnd = _isStringWithNullEnd; parser.Endian = _endian; parser.StringEncoding = _strEncoding; String msgName = name; //try { if (itemsList == null) { parser.MakePacket(Msg, _endian == Endians.Big); integrity = true; } else { //parser.Items.Clear(); parser.Items.CopyFrom(itemsList); //parser.Items = itemsList as List<CPacketItem>; parser.MakePacket(_endian == Endians.Big); } } //catch(Exception e) { // MessageBox.Show(msgName+":"+e.Message); integrity = true; } rels["integrity"] = integrity; rels["parser"] = parser; rels["msg"] = Msg; EasyGridRow row = V_Data.AddARow(rels, new object[] { isChecked, msgName, "edit", "send", "X", comment }); if (integrity == false) { (row[(int)Titles.name] as EasyGridTextBoxCell).FontColor = Color.Red; } if (isChecked) { row.RowBackMode = RowBackModes.Gray; } } } if (V_Data.Rows.Count > 0) { if (_startIndex < V_Data.Rows.Count) { V_Data.Rows[_startIndex].RowBackMode = FormAdders.EasyGridViewCollections.RowBackModes.Red; } //V_Data.Rows[0].RowBackCustomColor = Color.FromArgb(255, 222, 222); } V_Data.RefreshList(); }
public void MakeMsgText() { NativeText = StructXMLParser.ItemsToCode(Items); }
/// <summary> /// 내부의 NativeText에 지정된 C문법의 text를 분석하여 /// 패킷을 생성하고, 그 패킷에 해당하는 string을 리턴한다. /// 만일 에러가 발생하면 exception을 발생시킨다. /// exeption의 원인은 exeption.Message에 있다. /// 이 메시지를 호출하고 난 뒤에, PacketBuffer에 보면 메시지가 생성되어 있고, /// PacketDataSize안에는 그 사이즈가 있다. /// </summary> /// <param name="str">분석을 원하는 c문법의 text</param> /// <returns>패킷에 해당하는 string. type1,값1,값2/type2,값3,값4...식의 포멧이다.</returns> public void MakePacket(String str, bool swap) { if (str == null || str.Length == 0) { str = NativeText; } else { NativeText = str; } Items.Clear(); Items.CopyFrom(StructXMLParser.CodeToItems(str, null)); MakePacket(swap); #region old /* * * CStructParser ns = new CStructParser(); * * String[] lines = str.Split(";".ToCharArray()); //각 라인으로 나누어서 * object[] initValues; * for (int i = 0; i < lines.Length; i++) * {//각 라인들 * String line = lines[i]; * line = removeOuterWhiteSpace(line); * * if(line.Length==0) continue; * * int firstSpace = -1; * int secondSpace = -1; * int thirdSpace = -1; * int typeSpace = -1; * try * { * firstSpace = line.IndexOf(' '); * secondSpace = line.IndexOf(' ', firstSpace+1); * thirdSpace = line.IndexOf(' ', secondSpace+1); * } * catch { } * if (firstSpace < 0) firstSpace = line.IndexOf('['); * if (firstSpace < 0) firstSpace = line.IndexOf('='); * if (firstSpace < 0) firstSpace = line.Length; * String type = line.Substring(0, firstSpace); * * if (TypeHandling.getTypeFromTypeName(type) == null) * {//첫번째 토큰에서 제대로된 타입이 검출안되면 * if (secondSpace > 0) type = line.Substring(0, secondSpace); //두번째 검색 * else * { * setError("타입정의가 맞지 않습니다.", i, line); //두번째 스페이스가 없으면 에러 * return null; * } * * if (TypeHandling.getTypeFromTypeName(type) == null) * {//두번째 토큰에서 타입틀리면 * if (thirdSpace > 0) type = line.Substring(0, thirdSpace);//세번째 검색 * else * { * setError("타입정의가 맞지 않습니다.", i, line);//세번째 스페이스 없으면 에러 * return null; * } * * if (TypeHandling.getTypeFromTypeName(type) == null) * { //세번째 토큰에서도 타입이 틀리다면 * setError("타입정의가 맞지 않습니다.", i, line); //무조건 에러 * return null; * } * else * { * typeSpace = thirdSpace; * } * } * else * { * typeSpace = secondSpace; * } * } * else * { * typeSpace = firstSpace; * } * type = type.ToLower(); * String rest = line.Substring(typeSpace); * * if (type.ToLower().Equals("string") == false) rest = rest.Trim();// rest.Replace(" ", ""); //string이 아니라면 나머지에서는 빈칸이 필요없다. * * //초기값 입력받기 * bool isSwap = false; * if(rest.Length>5 && rest.Substring(0,5).ToLower().Equals("swap@")){//swap명령어. * rest = rest.Substring(5);//명령어 삭제. * isSwap = true;//값을 핸들링할 때 swap한다. * } * String initValue = "0"; //기본값은 0이다. * String[] token = rest.Split("=".ToCharArray(), StringSplitOptions.RemoveEmptyEntries); * int openBracket; * int closeBracket; * if (token.Length == 2) * { * token[0] = token[0].Trim(); * token[1] = token[1].Trim(); * initValue = token[1]; * * } * else if (token.Length > 2) * { * setError("= 이 2번 이상 들어갑니다.", i, line); * return null; * } * * rest = token[0]; //=오른쪽의 값은 잘라버림. * //배열검사 * openBracket = rest.IndexOf('['); * closeBracket = rest.IndexOf(']'); * * int arrSize = 1; * * if (openBracket > 0 || closeBracket > 0) //배열인지 검사하여 * { * if (openBracket < 0 || closeBracket < 0) * { * setError("배열을 나타내는 [,] 기호 둘 중 하나가 없습니다", i, line); * return null; * } * String numStr = rest.Substring(openBracket + 1, closeBracket - openBracket - 1); * * if (numStr.Length == 0) * { * arrSize = initValue.Split(",".ToCharArray()).Length; * rest = rest.Substring(0, openBracket); //배열 크기를 가져왔으므로 배열기호그룹 삭제 * } * else * { * int num = -1; * if (Int32.TryParse(numStr, out num) == false) * { * setError("배열기호[] 안에는 정수가 와야합니다.", i, line); * return null; * } * else * { * if (num <= 0) * { * setError("배열의 크기는 1보다 작을 수 없습니다.", i, line); * return null; * } * else * { * arrSize = num; * rest = rest.Substring(0, openBracket); //배열 크기를 가져왔으므로 배열기호그룹 삭제 * } * } * } * } //배열검사 끝. * * //초기값 검사 * openBracket = initValue.IndexOf('{'); * closeBracket = initValue.IndexOf('}'); * //initValues.Add(new object[arrSize]);//값 배열을 만들어줌 * initValues = new object[arrSize]; * if (openBracket >= 0 || closeBracket >= 0 || initValue.IndexOf(',')>=0) //배열형식의 초기값이라면 * { * if (openBracket < 0 || closeBracket < 0) * { * setError("{ 나 } 중에서 하나가 없습니다.", i, line); * return null; * } * String numStr = initValue.Substring(openBracket + 1, closeBracket - openBracket - 1); //브래킷 내부의 내용 가져옴 * token = numStr.Split(",".ToCharArray()); * * * * if (token.Length > arrSize) //배열의 크기보다 클 때 * { * setError("배열의 크기를 넘어서 초기화를 시도했습니다. size:" + arrSize + " this:" + token.Length, i, line); * return null; * } * string newInitStr = ""; * for (int j = 0; j < token.Length; j++) //초기값들의 타입을 검사한다. * { * Int64 intValue = 0; * Double doubleValue = 0.0; * String strValue = ""; * if (type.Equals("string") == false && token[j].Length == 0) initValues[j] = 0;// initValues[i][j] = 0; * * switch (TypeHandling.getValueAndType(token[j], ref intValue, ref doubleValue, ref strValue)) * {//hex나 oct형식등을 모두 숫자형으로 먼저 치환한다. * case TypeHandling.TypeName.Integer: * if (isSwap) * { * if (TypeHandling.getTypeFromTypeName(type) == typeof(byte)) initValues[j] = Swaper.swap<byte>((byte)intValue); * else if (TypeHandling.getTypeFromTypeName(type) == typeof(short)) initValues[j] = Swaper.swap<short>((short)intValue); * else if (TypeHandling.getTypeFromTypeName(type) == typeof(int)) initValues[j] = Swaper.swap<int>((int)intValue); * else if (TypeHandling.getTypeFromTypeName(type) == typeof(long)) initValues[j] = Swaper.swap<long>((long)intValue); * else if (TypeHandling.getTypeFromTypeName(type) == typeof(ushort)) initValues[j] = Swaper.swap<ushort>((ushort)intValue); * else if (TypeHandling.getTypeFromTypeName(type) == typeof(uint)) initValues[j] = Swaper.swap<uint>((uint)intValue); * else if (TypeHandling.getTypeFromTypeName(type) == typeof(ulong)) initValues[j] = Swaper.swap<ulong>((ulong)intValue); * } * else * { * initValues[j] = intValue; * } * break; * case TypeHandling.TypeName.Float: * initValues[j] = doubleValue; * break; * case TypeHandling.TypeName.String: * initValues[j] = strValue; * break; * } * if (j != 0) newInitStr += ","; * newInitStr += initValues[j].ToString(); * if (TypeHandling.isValidType(initValues[j].ToString(), type) == false) * { * setError("초기값이 타입과 다릅니다.Type:" + type + " value:" + token[j], i, line); * return null; * } * * } * initValue = newInitStr; * * }else //배열형식이 아니라 단순값일 때 * { * Int64 intValue = 0; * Double doubleValue = 0.0; * String strValue = ""; * if (type.Equals("string") == false && initValue.Length == 0) initValues[0] = 0; * * * * * switch (TypeHandling.getValueAndType(initValue, ref intValue, ref doubleValue, ref strValue)) * {//hex나 oct형식등을 모두 숫자형으로 먼저 치환한다. * case TypeHandling.TypeName.Integer: * //initValues[i][0] = intValue; * if (isSwap) * { * if (TypeHandling.getTypeFromTypeName(type) == typeof(byte)) initValues[0] = Swaper.swap<byte>((byte)intValue); * else if (TypeHandling.getTypeFromTypeName(type) == typeof(short)) initValues[0] = Swaper.swap<short>((short)intValue); * else if (TypeHandling.getTypeFromTypeName(type) == typeof(int)) initValues[0] = Swaper.swap<int>((int)intValue); * else if (TypeHandling.getTypeFromTypeName(type) == typeof(long)) initValues[0] = Swaper.swap<long>((long)intValue); * else if (TypeHandling.getTypeFromTypeName(type) == typeof(ushort)) initValues[0] = Swaper.swap<ushort>((ushort)intValue); * else if (TypeHandling.getTypeFromTypeName(type) == typeof(uint)) initValues[0] = Swaper.swap<uint>((uint)intValue); * else if (TypeHandling.getTypeFromTypeName(type) == typeof(ulong)) initValues[0] = Swaper.swap<ulong>((ulong)intValue); * } * else * { * initValues[0] = intValue; * } * break; * case TypeHandling.TypeName.Float: * initValues[0] = doubleValue; * break; * case TypeHandling.TypeName.String: * initValues[0] = strValue; * break; * } * * if (TypeHandling.isValidType(initValues[0].ToString(), type) == false) * { * String error = "초기값이 타입과 다릅니다."; * if(TypeHandling.getTypeKind(initValue)== TypeHandling.TypeName.HexString) error+=" hex값을 넣어주실 때는 unsigned 타입으로 지정하십시오."; * setError(error, i, line); * return null; * } * * * initValue = initValues[0].ToString(); * * } * //초기값 검사 끝 * rest = rest.Replace(" ", ""); * //변수명검사 * for (int j = 0; j < rest.Length; j++) //변수명 검사 * { * if ((Char.IsLetterOrDigit(rest[j]) == false) && rest[j].Equals('_')==false) * { * setError("변수명에는 기호가 들어갈 수 없습니다.", i, line); * return null; * } * else if (j == 0 && Char.IsDigit(rest[j])) * { * setError("변수명의 첫번째에는 숫자가 들어갈 수 없습니다.", i, line); * return null; * } * }//변수명 검사 끝 * if (rest.Length == 0) rest = "var" + i; * CStructItem item = new CStructItem(rest, type, arrSize, initValues); * item.IsSwap = isSwap; * item.InitString = initValue; * ns.Items.Add(item); * * * }//각 라인들 검색 끝 * this.Items.Clear(); * this.Items = ns.Items; */ #endregion //simpleText = MakeMsg(); //return simpleText; }