/// <summary> /// Lets users run the "FIXINFLO" procedure directly from HydrometTools. /// This is a procedure that calculates the inflow for some GP's more complicated reservoirs, and it is not run by the archiver. /// </summary> /// <param name="user"></param> /// <param name="password"></param> /// <param name="cbtt"></param> /// <param name="t1"></param> /// <param name="t2"></param> /// <returns></returns> public static string RunGPFixInflowProc(string user, string password, string cbtt, DateTime t1, DateTime t2) { if (cbtt.Trim() == "" || Regex.IsMatch(cbtt, "[^a-zA-z0-9]")) { return("Error: invalid cbtt or pcode"); } if (t2 <= t1) { return("Error: Invalid Dates (@fixinflo) -- ending date must be greater than beginning"); } string tmpFile_com = FileUtility.GetTempFileName(".com"); TextFile tf_com = new TextFile(tmpFile_com); string t = DateTime.Now.ToString(timeFormat).ToLower(); string remoteFile_com = "huser1:[edits]run_math_" + user + t + ".com"; string unixRemoteFile_com = VmsToUnixPath(remoteFile_com); tf_com.Add("$! -- Fixinflo script --- "); AddVmsScriptHeader(user, tf_com); tf_com.Add("INTERPRET FIXINFLO/NODEBUG " + t1.ToString("yyyyMMMdd") + " " + cbtt.Trim() + " " + t2.ToString("yyyyMMMdd")); tf_com.SaveAsVms(tf_com.FileName); if (!SendFile(user, password, tf_com.FileName, unixRemoteFile_com)) { return("Error sending file to server '" + remoteFile_com + "'"); } string rval = SendFileAndRunCommand(user, password, tmpFile_com, unixRemoteFile_com, "@" + remoteFile_com); return(rval); }
public static TextFile Build_GetDelegate(string getDelegateFunctionName, Type delType) { TextFile tf = new TextFile(); TextFile tfFun = tf.Add("JSDataExchangeMgr.GetJSArg<{0}>(() => ", JSNameMgr.CsFullName(delType)).BraceIn(); { TextFile tfIf = tfFun.Add("if (JSApi.isFunctionS((int)JSApi.GetType.Arg))").BraceIn(); { tfIf.Add("return {0}(JSApi.getFunctionS((int)JSApi.GetType.Arg));", getDelegateFunctionName); tfIf.BraceOut(); } TextFile tfElse = tfFun.Add("else").BraceIn(); { tfElse.Add("return ({0})JSMgr.datax.getObject((int)JSApi.GetType.Arg);", JSNameMgr.CsFullName(delType)); tfElse.BraceOut(); } tfFun.BraceOut().Add(");"); } return(tf); }
public static string RunRatingTableMath(string user, string password, string cbtt, string pcodeIn, string pcodeOut, DateTime t1, DateTime t2, bool ace = false) { if (cbtt.Trim() == "" || Regex.IsMatch(cbtt, "[^a-zA-z0-9]") || pcodeIn.Trim() == "" || Regex.IsMatch(pcodeIn, "[^a-zA-z0-9]") || pcodeOut.Trim() == "" || Regex.IsMatch(pcodeOut, "[^a-zA-z0-9]")) { return("Error: invalid cbtt or pcode"); } if (t2 <= t1) { return("Error: Invalid Dates (%rating) -- ending date must be greater than beginning"); } string tmpFile_dfp = FileUtility.GetTempFileName(".dfp"); // create script. string tmpFile_com = FileUtility.GetTempFileName(".com"); TextFile tf_dfp = new TextFile(tmpFile_dfp); TextFile tf_com = new TextFile(tmpFile_com); CreateRatingMathCommands(user, cbtt, pcodeIn, pcodeOut, t1, t2, tf_dfp, ace); string t = DateTime.Now.ToString(timeFormat).ToLower(); string remoteFile_dfp = "huser1:[edits]math_cmds_" + user + t + ".dfp"; string remoteFile_com = "huser1:[edits]run_math_" + user + t + ".com"; string unixRemoteFile_dfp = VmsToUnixPath(remoteFile_dfp); string unixRemoteFile_com = VmsToUnixPath(remoteFile_com); tf_com.Add("$! -- Archiver script --- "); AddVmsScriptHeader(user, tf_com); tf_com.Add("$day"); tf_com.Add("@" + remoteFile_dfp); tf_dfp.SaveAsVms(tf_dfp.FileName); tf_com.SaveAsVms(tf_com.FileName); if (!SendFile(user, password, tmpFile_dfp, unixRemoteFile_dfp)) { return("Error sending file to server '" + remoteFile_com + "'"); } var command = "@" + remoteFile_com; if (HydrometInfoUtility.HydrometServerFromPreferences() == HydrometHost.GreatPlains) { command = "submit/nolog " + remoteFile_com; } string rval = SendFileAndRunCommand(user, password, tmpFile_com, unixRemoteFile_com, command); return(rval); }
private static void RatingEquation(string cbtt, string pcodeIn, string pcodeOut, TextFile tf, bool ace) { if (HydrometInfoUtility.HydrometServerFromPreferences() == HydrometHost.GreatPlains && pcodeIn.ToLower().Trim() == "fb" && ace) { tf.Add(cbtt + "/" + "ace" + ":=%rating(" + cbtt + "/" + pcodeIn + ")"); tf.Add(cbtt + "/" + pcodeOut + ":=" + cbtt + "/ace"); tf.Add("remove " + cbtt + "/ace"); } else { tf.Add(cbtt + "/" + pcodeOut + ":=%rating(" + cbtt + "/" + pcodeIn + ")"); } }
static void GenAttributeForClassIfNeeded(Type type, TextFile tf) { if (stubName != "" && !stubName.EndsWith("/")) { stubName += "/"; } tf.Add("[Bridge.FileName(\"pluginstub/" + stubName + $"{GetValidTypeName(type.Name)}\")]"); tf.Add("[Bridge.IgnoreCast]"); tf.Add("[Bridge.IgnoreGeneric]"); if (type.Name.Equals("RequireComponent")) { tf.Add("[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]"); } GenNamespaceIfNeeded(type, tf); }
static TextFile GenEnum() { TextFile tf = new TextFile(); string typeName = type.ToString(); // tf.AddLine().Add("// {0}", typeName); // remove name space int lastDot = typeName.LastIndexOf('.'); if (lastDot >= 0) { typeName = typeName.Substring(lastDot + 1); } if (typeName.IndexOf('+') >= 0) { return(null); } TextFile tfDef = tf.Add("Bridge.define(\"{0}\", {{", JSNameMgr.JsFullName(type)).In(); tfDef.Add("$kind: \"enum\","); TextFile tfSta = tfDef.Add("statics: {").In(); Type uType = Enum.GetUnderlyingType(type); FieldInfo[] fields = type.GetFields(BindingFlags.GetField | BindingFlags.Public | BindingFlags.Static); for (int i = 0; i < fields.Length; i++) { string v = ""; if (uType == typeof(ulong)) { v = System.Convert.ToUInt64(fields[i].GetValue(null)).ToString(); } else { v = System.Convert.ToInt64(fields[i].GetValue(null)).ToString(); } tfSta.Add("{0}: {1}{2}", fields[i].Name, v, i == fields.Length - 1 ? "" : ","); } tfSta.BraceOut(); //tfDef.BraceOutSC(); tfDef.Out().Add("});"); return(tf); }
public IdahoPowerRatingTables(string cbtt) { this.cbtt = cbtt; // Get and assign rating table file from the web string idprURL = "https://ps.idahopower.com/RatingsService/Index?id=XXXX"; downloadURL = idprURL.Replace("XXXX", cbtt); var newData = Web.GetPage(idprURL.Replace("XXXX", cbtt)); if (newData.Count() == 0) { throw new Exception("OWRD data not found. Check inputs or retry later."); } TextFile newRDB = new TextFile(); foreach (var item in newData) { newRDB.Add(item); } this.webRdbTable = newRDB; // Get and assign RDB file properties var properties = newData[1].Split(',').ToList(); this.stationNumber = properties[0].Split(' ')[0].ToString(); this.ratingBeginDate = DateTime.Parse(properties[4].ToString()); this.ratingEndDate = DateTime.Parse(properties[5].ToString()); this.expandedPoints = Convert.ToInt16(properties[6]); this.originalPoints = Convert.ToInt16(properties[7]); this.remarks = properties[8]; this.equation = properties[9]; }
static void GenJsMessageIDs() { TextFile tf = new TextFile(null, "// auto gen"); tf.Add("// 记录每个脚本事件对应的ID号"); TextFile tfK = tf.Add("Bridge.MessageIDs = ").BraceIn(); for (int i = 0; i < infos.Length; i++) { Info info = infos[i]; tfK.Add("\"{0}\": {1},", info.methodName, i); } tfK.BraceOutSC(); string s = tf.Format(-1); File.WriteAllText(JsFile, s); }
// [MenuItem("JS for Unity/Generate JS Enum Bindings")] // public static void GenerateEnumBindings() // { // JSGenerator2.OnBegin(); // // for (int i = 0; i < JSBindingSettings.enums.Length; i++) // { // JSGenerator2.Clear(); // JSGenerator2.type = JSBindingSettings.enums[i]; // JSGenerator2.GenerateEnum(); // } // // JSGenerator2.OnEnd(); // // Debug.Log("Generate JS Enum Bindings finish. total = " + JSBindingSettings.enums.Length.ToString()); // } //public static Dictionary<Type, string> typeClassName = new Dictionary<Type, string>(); //static string className = string.Empty; public static void GenBindings(Type[] arrEnums, Type[] arrClasses) { JSGenerator.OnBegin(); TextFile tfAll = new TextFile(); TextFile tfFun = tfAll.Add("(function ($hc) {").In().Add("\"use strict\";"); int hc = 1; // enums for (int i = 0; i < arrEnums.Length; i++) { JSGenerator.Clear(); JSGenerator.type = arrEnums[i]; TextFile tf = JSGenerator.GenEnum(); if (tf != null) { tfFun.Add("if ($hc < {0}) {{ return; }}", hc++); tfFun.AddLine().Add(tf.Ch); } } // classes for (int i = 0; i < arrClasses.Length; i++) { JSGenerator.Clear(); JSGenerator.type = arrClasses[i]; //if (!typeClassName.TryGetValue(type, out className)) // className = type.Name; TextFile tf = JSGenerator.GenerateClass(); tfFun.Add("if ($hc < {0}) {{ return; }}", hc++); tfFun.AddLine() //.Add("if (Bridge.findObj(\"{0}\") == null) {{", type.JsFullName()) //.In() .Add(tf.Ch) //.BraceOut() ; } tfFun.Out().Add("})(1000000);"); File.WriteAllText(JSMgr.jsGenFile, tfAll.Format(-1)); JSGenerator.OnEnd(); Debug.Log("Generate JS Bindings OK. enum " + arrEnums.Length.ToString() + ", class " + arrClasses.Length.ToString()); }
public static void BuildProperties(TextFile tfStatic, TextFile tfInst, Type type, List <MemberInfoEx> properties, int slot) { for (int i = 0; i < properties.Count; i++) { MemberInfoEx infoEx = properties[i]; if (infoEx.Ignored) { continue; } PropertyInfo property = infoEx.member as PropertyInfo; ParameterInfo[] ps = property.GetIndexParameters(); string indexerParamA = string.Empty; string indexerParamB = string.Empty; string indexerParamC = string.Empty; for (int j = 0; j < ps.Length; j++) { indexerParamA += "ind" + j.ToString(); indexerParamB += "ind" + j.ToString() + ", "; if (j < ps.Length - 1) { indexerParamA += ", "; } indexerParamC += ", ind" + j.ToString(); } MethodInfo[] accessors = property.GetAccessors(); bool isStatic = accessors[0].IsStatic; // 特殊情况,当[]时,property.Name=Item string mName = Member_AddSuffix(property.Name, infoEx.GetOverloadIndex()); TextFile tf = isStatic ? tfStatic : tfInst; tf.Add("get{0}: function ({1}) {{ return CS.Call({2}, {3}, {4}, {5}{6}{7}); }},", mName, indexerParamA, (int)JSVCall.Oper.GET_PROPERTY, slot, i, (isStatic ? "true" : "false"), (isStatic ? "" : ", this"), indexerParamC); tf.Add("set{0}: function ({1}v) {{ return CS.Call({2}, {3}, {4}, {5}{6}{7}, v); }},", mName, indexerParamB, (int)JSVCall.Oper.SET_PROPERTY, slot, i, (isStatic ? "true" : "false"), (isStatic ? "" : ", this"), indexerParamC); } }
static void GenAMessage(Info info) { TextFile tf = new TextFile(null, "// auto gen"); tf.Add("using UnityEngine;"); tf.Add("using UnityEngine.UI;"); tf.AddLine(); TextFile tfNs = tf.Add("namespace jsb").BraceIn(); { TextFile tfC = tfNs.Add("public class {0} : MonoBehaviour", info.className).BraceIn(); { TextFile tfM = tfC.Add("public void {0}", info.signature).BraceIn(); { tfM.Add("JSComponent[] coms = GetComponents<JSComponent>();") .Add("if (coms == null || coms.Length == 0)") .BraceIn() .Add("Destroy(this);") .Add("return;") .BraceOut() .AddLine() .Add("foreach (var com in coms)"); TextFile tfF = tfM.BraceIn(); { tfF.Add("com.RecvMsg({0});", info.argList); } tfF.BraceOut(); } tfM.BraceOut(); } tfC.BraceOut(); } tfNs.BraceOut(); string s = tf.Format(-1); File.WriteAllText(CsDir + "/" + info.className + ".cs", s); }
/// <summary> /// Allow users to compute daily ratings. Computes ratings from daily gage heights and forebay elevations. /// </summary> /// <param name="user"></param> /// <param name="password"></param> /// <param name="cbtt"></param> /// <param name="pcodeIn"></param> /// <param name="pcodeOut"></param> /// <param name="t1"></param> /// <param name="t2"></param> /// <param name="ace"></param> /// <returns></returns> public static string RunRatingTableMathArchives(string user, string password, string cbtt, string pcodeIn, string pcodeOut, DateTime t1, DateTime t2, bool ace = false) { if (cbtt.Trim() == "" || Regex.IsMatch(cbtt, "[^a-zA-z0-9]") || pcodeIn.Trim() == "" || Regex.IsMatch(pcodeIn, "[^a-zA-z0-9]") || pcodeOut.Trim() == "" || Regex.IsMatch(pcodeOut, "[^a-zA-z0-9]")) { return("Error: invalid cbtt or pcode"); } if (t2 <= t1) { return("Error: Invalid Dates (%rating) -- ending date must be greater than beginning"); } if (ace) { pcodeOut = "ACE"; } string tmpFile_com = FileUtility.GetTempFileName(".com"); TextFile tf_com = new TextFile(tmpFile_com); string t = DateTime.Now.ToString(timeFormat).ToLower(); string remoteFile_com = "huser1:[edits]run_daily_rating" + user + t + ".com"; string unixRemoteFile_com = VmsToUnixPath(remoteFile_com); tf_com.Add("$! -- Rating_Daily script --- "); AddVmsScriptHeader(user, tf_com); tf_com.Add("$INTERPRET DLY_RATING/NODEBUG " + t1.ToString("yyyyMMMdd") + " " + t2.ToString("yyyyMMMdd") + " " + cbtt.Trim().ToUpper() + " " + pcodeIn.ToUpper() + " " + pcodeOut.ToUpper()); tf_com.SaveAsVms(tf_com.FileName); if (!SendFile(user, password, tf_com.FileName, unixRemoteFile_com)) { return("Error sending file to server '" + remoteFile_com + "'"); } string rval = SendFileAndRunCommand(user, password, tmpFile_com, unixRemoteFile_com, "@" + remoteFile_com); return(rval); }
private static void CreateRawDataCommands(string user, string cbtt, DateTime t1, DateTime t2, TextFile tf) { /* * day=2010Jun14 * g/00:00,23:59/route=huser1:[jdoty]route.dat/brief mck * day=2010Jun15 * g/a/route=huser1:[jdoty]route.dat/brief mck * day=2010Jun16 */ bool singleDay = t1.Date == t2.Date; tf.Add("$! -- rawdata script --- "); AddVmsScriptHeader(user, tf); tf.Add("$ rawdata"); tf.Add("day=" + t1.ToString("yyyyMMMdd")); if (singleDay) { tf.Add("g/" + t1.ToString("HH") + ":" + t1.ToString("mm") + "," + t2.ToString("HH") + ":" + t2.ToString("mm") + "/route=huser1:[edits]route.dat/brief " + cbtt); } else // multi day { tf.Add("g/" + t1.ToString("HH") + ":" + t1.ToString("mm") + ",23:59/route=huser1:[edits]route.dat/brief " + cbtt); DateTime t = t1.Date.AddDays(1); while (t <= t2.Date) { tf.Add("day=" + t.ToString("yyyyMMMdd")); if (t.Date == t2.Date) {// final value. look at hour and minute. tf.Add("g/00:00," + t2.ToString("HH") + ":" + t2.ToString("mm") + "/route=huser1:[edits]route.dat/brief " + cbtt); } else { tf.Add("g/all/route=huser1:[edits]route.dat/brief " + cbtt); } t = t.Date.AddDays(1); } } tf.Add("$ Exit"); }
private static void AddVmsScriptHeader(string user, TextFile tf) { string un = System.Security.Principal.WindowsIdentity.GetCurrent().Name.ToString(); tf.Add("$! generated by HydrometTools " + DateTime.Now.ToString()); tf.Add("$! username: "******" " + user); tf.Add("$! ----------------------------------"); tf.Add("$interpret:== $SUTRON$:[rtcm]rtcm"); tf.Add("$define/user_mode sys$output nl:"); tf.Add("$define/user_mode sys$error nl:"); HydrometHost svr = HydrometInfoUtility.HydrometServerFromPreferences(); if (svr == HydrometHost.PN || svr == HydrometHost.Yakima || svr == HydrometHost.PNLinux) { tf.Add("$set process/priv=syslck"); } tf.Add("$DAY:== $SUTRON$:[DAYFILE]DAYFILE"); }
public static void BuildFields(TextFile tfStatic, TextFile tfInst, Type type, List <MemberInfoEx> fields, int slot) { TextFile tfStatic2 = null, tfInst2 = null; for (int i = 0; i < fields.Count; i++) { MemberInfoEx infoEx = fields[i]; if (infoEx.Ignored) { continue; } FieldInfo field = infoEx.member as FieldInfo; if (field.IsStatic) { if (tfStatic2 == null) { tfStatic2 = tfStatic.Add("$fields: {").In(); tfStatic2.Out().Add("},"); } } else { if (tfInst2 == null) { tfInst2 = tfInst.Add("$fields: {").In(); tfInst2.Out().Add("},"); } } } for (int i = 0; i < fields.Count; i++) { MemberInfoEx infoEx = fields[i]; if (infoEx.Ignored) { continue; } FieldInfo field = infoEx.member as FieldInfo; TextFile tf = field.IsStatic ? tfStatic2 : tfInst2; tf.Add("{0}: {{", field.Name).In() .Add("get: function () {{ return CS.Call({0}, {1}, {2}, {3}{4}); }},", (int)JSVCall.Oper.GET_FIELD, slot, i, (field.IsStatic ? "true" : "false"), (field.IsStatic ? "" : ", this")) .Add("set: function (v) {{ return CS.Call({0}, {1}, {2}, {3}{4}, v); }}", (int)JSVCall.Oper.SET_FIELD, slot, i, (field.IsStatic ? "true" : "false"), (field.IsStatic ? "" : ", this")) .Out().Add("},"); } }
public IdahoPowerRatingTables(string cbtt, string stationId) { this.cbtt = cbtt; // Get and assign rating table file from the web string idprURL = "https://ps.idahopower.com/RatingsService/Index?id=S-QRiv.Rating@XXXX"; downloadURL = idprURL.Replace("XXXX", stationId); if (stationId.IndexOf('@') > 0) { downloadURL = idprURL.Replace("@XXXX", " " + stationId); } var newData = Web.GetPage(downloadURL); if (newData.Count() == 0) { throw new Exception("Idaho Power data not found. Check inputs or retry later."); } //if( newData.Length <5 ) //{ // var err = String.Join("\n", newData); // throw new Exception("Idaho Power:" +err); //} TextFile newRDB = new TextFile(); foreach (var item in newData) { newRDB.Add(item); } this.webRdbTable = newRDB; // Get and assign RDB file properties //var properties = newData[1].Split(',').ToList(); //this.stationNumber = properties[0].Split(' ')[0].ToString(); //this.ratingBeginDate = DateTime.Parse(properties[4].ToString()); //try //{ this.ratingEndDate = DateTime.Parse(properties[5].ToString()); } //catch //{ this.ratingEndDate = DateTime.MaxValue; } //this.expandedPoints = Convert.ToInt16(properties[6]); //this.originalPoints = Convert.ToInt16(properties[7]); //this.remarks = properties[8]; //this.equation = properties[9]; }
static void GenNamespaceIfNeeded(Type type, TextFile tf) { if (namespaceInterceptor == null) { return; } var ns = namespaceInterceptor(type); if (ns != null) { tf.Add($"[Bridge.Namespace(\"{ns}\")]"); } // var ns = type.Namespace; // if (string.IsNullOrEmpty(ns) || !ns.Contains("UnityEngine")) { // return; // } // tf.Add($"[Bridge.Namespace(\"{Utils.EscapeNamespace(ns)}\")]"); }
static bool handleEvents(TextFile tfClass, Type type, Action <Type> OnNewType) { var eventInfos = type.GetEvents(); if (eventInfos.Length <= 0) { return(false); } foreach (var eventInfo in eventInfos) { StringBuilder sb = new StringBuilder(); var methodInfo = eventInfo.GetAddMethod(); if (methodInfo.IsPublic) { sb.Append("public "); } else if (methodInfo.IsFamily) { // sb.Append("protected "); sb.Append("public "); } else if (methodInfo.IsAssembly) { // sb.Append("internal "); sb.Append("public "); } if (methodInfo.IsStatic) { sb.Append("static "); } OnNewType(eventInfo.EventHandlerType); sb.Append("event "); sb.Append(typefn(eventInfo.EventHandlerType, type.Namespace, CsNameOption.CompilableWithT)); sb.Append(" "); sb.Append(eventInfo.Name); sb.Append(";"); tfClass.Add(sb.ToString()); } return(true); }
public void ParseFile(BinaryDataReader br) { br.ByteOrder = ByteOrder.LittleEndian; uint filesize = br.ReadUInt32(); br.BaseStream.Position = 0x40; event2File = br.ReadByte() != 0; //idk how to check otherwise br.Position = (event2File) ? 0x40 : 0x50; Name1 = Encoding.ASCII.GetString(br.ReadBytes(0x40)).Replace("\0", ""); Name2 = (event2File) ? null : Encoding.ASCII.GetString(br.ReadBytes(0x40)).Replace("\0", ""); br.BaseStream.Position = (event2File) ? 0xCC : 0xF0; var offs = GetChunks(br, FILE_COUNT); for (int i = 0; i < MSBT_COUNT; i++) { br.Position = offs[i].Item1; /* we have to copy the file into a buffer to avoid padding problems */ byte[] buffer = br.ReadBytes(offs[i + 1].Item1 - offs[i].Item1); //should be safe since MSBT_COUNT < FILE_COUNT using (MemoryStream ms = new MemoryStream(buffer)) { TextFile.Add(new Msbt(ms)); } } br.Position = offs[IMAGE_INDEX].Item1; using (MemoryStream ms = new MemoryStream()) { BinaryWriter bw = new BinaryWriter(ms); bw.Write(br.ReadBytes(offs[IMAGE_INDEX].Item2)); Img = (Bitmap)Image.FromStream(ms); } br.BaseStream.Position = offs[URL_INDEX].Item1; Url = Encoding.ASCII.GetString(br.ReadBytes(offs[URL_INDEX].Item2)).Replace("\0", ""); }
/// <summary> /// Runs multiple Archive commands in a single batch /// </summary> /// <param name="user"></param> /// <param name="password"></param> /// <param name="commands"></param> /// <returns></returns> public static string RunArchiveCommands(string user, string password, string[] commands) { //interpret/nodebug acm 2010Jun14 mck fb string rval = ""; var tmpFile = FileUtility.GetTempFileName(".txt"); TextFile tf = new TextFile(tmpFile); AddVmsScriptHeader(user, tf); foreach (var item in commands) { tf.Add(item); rval += "\n" + item; } tf.SaveAsVms(tf.FileName); string t = DateTime.Now.ToString(timeFormat).ToLower(); string remoteFile = "huser1:[edits]run_archiver_" + user + t + ".com"; string unixRemoteFile = VmsToUnixPath(remoteFile); rval += "\n" + SendFileAndRunCommand(user, password, tmpFile, unixRemoteFile, "@" + remoteFile); return(rval); }
static void handleInterfaceProblems(TextFile tfClass, Type cType, Action <Type> OnNewType) { Type[] interfaces = cType.GetValidInterfaces(); Action <Type, MethodInfo> actionMethod = (iType, method) => { StringBuilder sbDef = new StringBuilder(); sbDef.Append("extern "); if (!(method.IsSpecialName && method.Name == "op_Implicit")) { sbDef.Append(typefn(method.ReturnType, cType.Namespace, CsNameOption.CompilableWithT) + " "); } OnNewType(method.ReturnType); sbDef.Append(iType.CsFullName(CsNameOption.CompilableWithT) + "."); // 这句是重点 sbDef.Append(MethodNameString(cType, method)); if (method.IsGenericMethodDefinition) { Type[] argus = method.GetGenericArguments(); args t_args = new args(); foreach (var a in argus) { t_args.Add(a.Name); } sbDef.Append(t_args.Format(args.ArgsFormat.GenericT)); } sbDef.Append("("); ParameterInfo[] ps = method.GetParameters(); { sbDef.Append(Ps2String(cType, ps)); sbDef.Append(");"); foreach (var p in ps) { OnNewType(p.ParameterType); } } tfClass.Add(sbDef.ToString()); }; Action <Type, PropertyInfo> actionPro = (iType, pro) => { OnNewType(pro.PropertyType); ParameterInfo[] ps = pro.GetIndexParameters(); args iargs = new args(); bool isIndexer = (ps.Length > 0); if (isIndexer) { for (int j = 0; j < ps.Length; j++) { iargs.AddFormat("{0} {1}", typefn(ps[j].ParameterType, cType.Namespace), ps[j].Name); OnNewType(ps[j].ParameterType); } } MethodInfo getm = pro.GetGetMethod(); MethodInfo setm = pro.GetSetMethod(); bool canGet = getm != null && getm.IsPublic; bool canSet = setm != null && setm.IsPublic; string getset = ""; { if (canGet) { getset += "get;"; } if (canSet) { getset += " set;"; } } string vo = string.Empty; if (isIndexer) { tfClass.Add("extern {4}{0} {1}{2} {{ {3} }}", typefn(pro.PropertyType, cType.Namespace), iType.CsFullName(CsNameOption.CompilableWithT) + ".this", // 这句是重点 iargs.Format(args.ArgsFormat.Indexer), getset, vo); } else { tfClass.Add("extern {3}{0} {1} {{ {2} }}", typefn(pro.PropertyType, cType.Namespace), iType.CsFullName(CsNameOption.CompilableWithT) + "." + // 这句是重点 pro.Name, getset, vo); } }; foreach (Type iType in interfaces) { GeneratorHelp.ATypeInfo ti = GeneratorHelp.CreateTypeInfo(iType); for (int i = 0; i < ti.Methods.Count; i++) { MemberInfoEx infoEx = ti.Methods[i]; MethodInfo method = infoEx.member as MethodInfo; actionMethod(iType, method); } for (int i = 0; i < ti.Pros.Count; i++) { MemberInfoEx infoEx = ti.Pros[i]; PropertyInfo pro = infoEx.member as PropertyInfo; actionPro(iType, pro); } // 特殊处理,BridgeProj工程 if (iType == typeof(ICollection)) { tfClass.Add("bool System.Collections.ICollection.IsReadOnly { get; }"); } } }
private static void CreateRatingMathCommands(string user, string cbtt, string pcodeIn, string pcodeOut, DateTime t1, DateTime t2, TextFile tf, bool ace) { /* * day= 2010Jun14 * g/00:00, 23:59/fb,af mck * math/fb,af * mck/af:=%rating(mck/fb) * exit * update * clear * * day= 2010Jun15 * g/a/fb,af mck * math/fb,af * mck/af:=%rating(mck/fb) * exit * update * clear * * * === GP Region has different column names (instead of AF using ACE in rating table) * day= 2010Jun15 * g/a/fb,af gibr * math/fb,af * gibr/ace:=%rating(gibr/fb) * gibr/af :=gibr/ace * remove gibr/ace * exit * update * clear * */ bool singleDay = t1.Date == t2.Date; tf.Add("day=" + t1.ToString("yyyyMMMdd")); if (singleDay) { tf.Add("FORMAT=NULL"); tf.Add("g/" + t1.ToString("HH") + ":" + t1.ToString("mm") + "," + t2.ToString("HH") + ":" + t2.ToString("mm") + "/" + pcodeIn + "," + pcodeOut + " " + cbtt); tf.Add("math/" + pcodeIn + "," + pcodeOut); RatingEquation(cbtt, pcodeIn, pcodeOut, tf, ace); tf.Add("exit"); tf.Add("update"); tf.Add("clear"); } else // multi day { tf.Add("FORMAT=NULL"); tf.Add("g/" + t1.ToString("HH") + ":" + t1.ToString("mm") + ",23:59/" + pcodeIn + "," + pcodeOut + " " + cbtt); tf.Add("math/" + pcodeIn + "," + pcodeOut); RatingEquation(cbtt, pcodeIn, pcodeOut, tf, ace); //tf.Add(cbtt + "/" + pcodeOut + ":=%rating(" + cbtt + "/" + pcodeIn + ")"); tf.Add("exit"); tf.Add("update"); tf.Add("clear"); DateTime t = t1.Date.AddDays(1); while (t <= t2.Date) { tf.Add("day=" + t.ToString("yyyyMMMdd")); if (t.Date == t2.Date) {// final value. look at hour and minute. tf.Add("g/00:00," + t2.ToString("HH") + ":" + t2.ToString("mm") + "/" + pcodeIn + "," + pcodeOut + " " + cbtt); } else { tf.Add("g/a/" + pcodeIn + "," + pcodeOut + " " + cbtt); } tf.Add("math/" + pcodeIn + "," + pcodeOut); RatingEquation(cbtt, pcodeIn, pcodeOut, tf, ace); tf.Add("exit"); tf.Add("update"); tf.Add("clear"); t = t.Date.AddDays(1); } } }
static void handlePros(TextFile tfClass, Type type, GeneratorHelp.ATypeInfo ti, Action <Type> OnNewType) { Action <PropertyInfo> action = (pro) => { bool isI = type.IsInterface; OnNewType(pro.PropertyType); ParameterInfo[] ps = pro.GetIndexParameters(); args iargs = new args(); bool isIndexer = (ps.Length > 0); if (isIndexer) { for (int j = 0; j < ps.Length; j++) { iargs.AddFormat("{0} {1}", typefn(ps[j].ParameterType, type.Namespace), ps[j].Name); OnNewType(ps[j].ParameterType); } } MethodInfo getm = pro.GetGetMethod(); MethodInfo setm = pro.GetSetMethod(); bool canGet = getm != null && getm.IsPublic; bool canSet = setm != null && setm.IsPublic; string getset = ""; if (!isI) { if (canGet) { getset += string.Format("get {{ return default({0}); }}", typefn(pro.PropertyType, type.Namespace)); } if (canSet) { getset += " set {}"; } } else { if (canGet) { getset += "get;"; } if (canSet) { getset += " set;"; } } string vo = string.Empty; if (!isI) { vo = "public "; if ((getm != null && getm.IsStatic) || (setm != null && setm.IsStatic)) { vo += "static "; } if (!type.IsValueType) { if ((getm != null && getm.IsVirtual) || (setm != null && setm.IsVirtual)) { vo += ((getm != null && getm.GetBaseDefinition() != getm) || (setm != null && setm.GetBaseDefinition() != setm)) ? "override " : "virtual "; } } } if (isIndexer) { tfClass.Add("{3}{0} this{1} {{ {2} }}", typefn(pro.PropertyType, type.Namespace), iargs.Format(args.ArgsFormat.Indexer), getset, vo); } else { tfClass.Add("{3}{0} {1} {{ {2} }}", typefn(pro.PropertyType, type.Namespace), pro.Name, getset, vo); } }; bool hasNoneIndexer = false; for (int i = 0; i < ti.Pros.Count; i++) { MemberInfoEx infoEx = ti.Pros[i]; PropertyInfo pro = infoEx.member as PropertyInfo; if (pro.GetIndexParameters().Length == 0) { hasNoneIndexer = true; action(pro); } } if (hasNoneIndexer) { tfClass.AddLine(); } for (int i = 0; i < ti.Pros.Count; i++) { MemberInfoEx infoEx = ti.Pros[i]; PropertyInfo pro = infoEx.member as PropertyInfo; if (pro.GetIndexParameters().Length > 0) { action(pro); } } }
public static string RunArchiver(string user, string password, string[] cbtt, string pcode, DateTime t1, DateTime t2, bool previewOnly) { string tmpFile = FileUtility.GetTempFileName(".txt"); // create script. TextFile tf = new TextFile(tmpFile); for (int i = 0; i < cbtt.Length; i++) { if (cbtt[i].Trim() == "" || Regex.IsMatch(cbtt[i], "[^a-zA-z0-9]")) { return("Error: invalid cbtt"); } if (Regex.IsMatch(pcode, "[^a-zA-z0-9\\.]")) { return("Error: invalid character in pcode"); } if (pcode.Trim() == "") { return("Error: empty pcode not allowed! "); } if (t2 < t1) { return("Error: Invalid Dates -- ending date is less than the beginning date"); } tf.Add("$! -- Archiver script --- "); AddVmsScriptHeader(user, tf); /* * interpret/nodebug acm 2010Jun14 mck fb * interpret/nodebug acm 2010Jun15 mck fb * * */ DateTime t = t1.Date; if (pcode == "ALL") { pcode = ""; } while (t <= t2.Date) { tf.Add(DayFiles.ArchiveCommand(cbtt[i], pcode, t)); t = t.AddDays(1); } //tf.Add("$ Mail/subject=\"Archiver data has run for cbtt=[" + cbtt + "] \" run_archiver.com ktarbet"); } if (previewOnly) { return(String.Join("\n", tf.FileData)); } else { tf.SaveAsVms(tf.FileName); string t = DateTime.Now.ToString(timeFormat).ToLower(); string remoteFile = "huser1:[edits]run_archiver_" + user + t + ".com"; string unixRemoteFile = VmsToUnixPath(remoteFile); string rval = SendFileAndRunCommand(user, password, tmpFile, unixRemoteFile, "@" + remoteFile); return(rval); } }
static void GenInterfaceOrStructOrClass(Type type, TypeStatus ts, Func <Type, TypeStatus> getParent, Action <Type> onNewType) { TextFile tfFile = null; if (type.DeclaringType != null) { ts.IsInnerType = true; TypeStatus tsParent = getParent(type.DeclaringType); if (tsParent == null || tsParent.status == TypeStatus.Status.Wait) { return; } if (tsParent.status == TypeStatus.Status.Ignored) { ts.status = TypeStatus.Status.Ignored; return; } tfFile = tsParent.tf.FindByTag("epos"); } if (tfFile == null) { tfFile = new TextFile(); } ts.tf = tfFile; ts.status = TypeStatus.Status.Exported; GeneratorHelp.ATypeInfo ti = GeneratorHelp.CreateTypeInfo(type); StringBuilder sb = new StringBuilder(); TextFile tfNs = tfFile; //string dir = Dir; if (type.DeclaringType == null && !string.IsNullOrEmpty(type.Namespace)) { tfNs = tfFile.Add("namespace {0}", type.Namespace).BraceIn(); tfNs.BraceOut(); } tfNs.Add("[Bridge.FileName(\"csw\")]"); TextFile tfClass = null; sb.Remove(0, sb.Length); { if (type.IsPublic || type.IsNestedPublic) { sb.Append("public "); } if (type.IsClass) { if (type.IsAbstract && type.IsSealed) { sb.Append("static "); } //else if (type.IsAbstract) // sb.Append("abstract "); //else if (type.IsSealed) // sb.Append("sealed "); //if (type.is) } if (type.IsInterface) { sb.Append("interface "); } else if (type.IsValueType) { sb.Append("struct "); } else { sb.Append("class "); } string className = type.CsFullName(CsNameOption.CompilableWithT); int dot = className.LastIndexOf("."); if (dot >= 0) { className = className.Substring(dot + 1); } sb.Append(className); Type vBaseType = type.ValidBaseType(); Type[] interfaces = type.GetDeclaringInterfaces(); if (vBaseType != null || interfaces.Length > 0) { sb.Append(" : "); args a = new args(); if (vBaseType != null) { a.Add(typefn(vBaseType, type.Namespace)); onNewType(vBaseType); } foreach (var i in interfaces) { a.Add(typefn(i, type.Namespace)); onNewType(i); } sb.Append(a.ToString()); } tfClass = tfNs.Add(sb.ToString()).BraceIn(); tfClass.BraceOut(); } tfClass.AddTag("epos"); for (int i = 0; i < ti.Fields.Count; i++) { MemberInfoEx infoEx = ti.Fields[i]; FieldInfo field = infoEx.member as FieldInfo; tfClass.Add("public {0}{1} {2};", (field.IsStatic ? "static " : ""), typefn(field.FieldType, type.Namespace), field.Name); onNewType(field.FieldType); } if (ti.Fields.Count > 0) { tfClass.AddLine(); } for (int i = 0; i < ti.Cons.Count; i++) { MemberInfoEx infoEx = ti.Cons[i]; ConstructorInfo con = infoEx.member as ConstructorInfo; if (type.IsValueType) { // 结构体不需要无参数构造函数 if (con == null || con.GetParameters().Length == 0) { continue; } } string ctorName = type.Name; if (type.IsGenericTypeDefinition) { int flag = ctorName.LastIndexOf('`'); if (flag >= 0) { ctorName = ctorName.Substring(0, flag); } } tfClass.Add("public extern {0}({1});", ctorName, con == null ? "" : Ps2String(type, con.GetParameters())); if (con != null) { foreach (var p in con.GetParameters()) { onNewType(p.ParameterType); } } } if (ti.Cons.Count > 0) { tfClass.AddLine(); } handlePros(tfClass, type, ti, onNewType); if (ti.Pros.Count > 0) { tfClass.AddLine(); } handleMethods(tfClass, type, ti, onNewType); if (!type.IsInterface) { handleInterfaceProblems(tfClass, type, onNewType); } }
static void GenEnum(Type type, TypeStatus ts, Func <Type, TypeStatus> getParent, Action <Type> onNewType) { TextFile tfFile = null; if (type.DeclaringType != null) { onNewType(type.DeclaringType); ts.IsInnerType = true; TypeStatus tsParent = getParent(type.DeclaringType); if (tsParent == null || tsParent.status == TypeStatus.Status.Wait) { return; } if (tsParent.status == TypeStatus.Status.Ignored) { ts.status = TypeStatus.Status.Ignored; return; } tfFile = tsParent.tf.FindByTag("epos"); } if (tfFile == null) { tfFile = new TextFile(); } ts.tf = tfFile; ts.status = TypeStatus.Status.Exported; //GeneratorHelp.ATypeInfo ti = GeneratorHelp.CreateTypeInfo(type); StringBuilder sb = new StringBuilder(); TextFile tfNs = tfFile; if (type.DeclaringType == null && !string.IsNullOrEmpty(type.Namespace)) { tfNs = tfFile.Add("namespace {0}", type.Namespace).BraceIn(); tfNs.BraceOut(); } tfNs.Add("[Bridge.FileName(\"csw\")]"); Type uType = Enum.GetUnderlyingType(type); TextFile tfClass = null; sb.Remove(0, sb.Length); { if (type.IsPublic || type.IsNestedPublic) { sb.Append("public "); } sb.Append("enum "); sb.Append(type.Name); if (uType != typeof(int)) { sb.AppendFormat(" : {0}", uType.CsFullName()); } tfClass = tfNs.Add(sb.ToString()).BraceIn(); tfClass.BraceOut(); } FieldInfo[] fields = type.GetFields(BindingFlags.GetField | BindingFlags.Public | BindingFlags.Static); for (int i = 0; i < fields.Length; i++) { FieldInfo field = fields[i]; string v = ""; if (uType == typeof(ulong)) { v = System.Convert.ToUInt64(field.GetValue(null)).ToString(); } else { v = System.Convert.ToInt64(field.GetValue(null)).ToString(); } tfClass.Add("{0} = {1},", field.Name, v); } }
public static void GenWraps(Type[] arrEnums, Type[] arrClasses, HashSet <string> bridgeTypes) { GeneratorHelp.ClearTypeInfo(); Dictionary <Type, TypeStatus> dict = new Dictionary <Type, TypeStatus>(); Action <Type> onNewType = null; onNewType = (nt) => { while (true) { if (nt.IsByRef || nt.IsArray) { nt = nt.GetElementType(); continue; } if (nt.IsGenericType && !nt.IsGenericTypeDefinition) { foreach (var ga in nt.GetGenericArguments()) { onNewType(ga); } nt = nt.GetGenericTypeDefinition(); continue; } if (nt.IsGenericParameter) { return; } break; } if (!bridgeTypes.Contains(nt.FullName) && !dict.ContainsKey(nt)) { dict.Add(nt, new TypeStatus()); } }; Func <Type, TypeStatus> getParent = (type) => { if (dict.ContainsKey(type)) { return(dict[type]); } return(null); }; foreach (var type in arrEnums) { onNewType(type); } foreach (var type in arrClasses) { onNewType(type); } while (true) { Type[] keys = new Type[dict.Count]; dict.Keys.CopyTo(keys, 0); foreach (Type type in keys) { TypeStatus ts = dict[type]; if (ts.status != TypeStatus.Status.Wait) { continue; } if (ShouldIgnoreType(type)) { ts.status = TypeStatus.Status.Ignored; continue; } if (type.IsEnum) { GenEnum(type, ts, getParent, onNewType); } else if (typeof(Delegate).IsAssignableFrom(type)) { GenDelegate(type, ts, getParent, onNewType); } else { GenInterfaceOrStructOrClass(type, ts, getParent, onNewType); } } bool bContinue = false; foreach (var kv in dict) { if (kv.Value.status == TypeStatus.Status.Wait) { bContinue = true; break; } } if (!bContinue) { break; } } TextFile tfAll = new TextFile(); tfAll.Add("#pragma warning disable 626, 824"); foreach (var kv in dict) { if (kv.Value.status == TypeStatus.Status.Exported && !kv.Value.IsInnerType) { tfAll.Add(kv.Value.tf.Ch); tfAll.AddLine(); } } tfAll.Add("#pragma warning restore 626, 824"); File.WriteAllText(JSBindingSettings.CswFilePath, tfAll.Format(-1)); }
static void GenMMgr(string className) { TextFile tf = new TextFile(null, "// auto gen"); tf.Add("using UnityEngine;"); tf.Add("using UnityEngine.UI;"); tf.Add("using System;"); tf.Add("using System.Collections;"); tf.Add("using System.Collections.Generic;"); tf.Add("using jsb;"); tf.AddLine(); TextFile tfNs = tf.Add("namespace jsb").BraceIn(); { TextFile tfC = tfNs.Add("public class {0}", className).BraceIn(); { tfC.Add("static Dictionary<string, int[]> jID = new Dictionary<string, int[]>();"); { tfC.AddMultiline(@" static int[] GetJsClassMessages(string jsFullName) { if (jID.ContainsKey(jsFullName)) return jID[jsFullName]; if (!JSMgr.vCall.CallJSFunctionName(JSCache.GetBridgeJsID(), ""getLMsgs"", jsFullName)) throw new Exception(""call Bridge.getLMsgs failed!""); string str = JSApi.getStringS((int)JSApi.GetType.JSFunRet); if (string.IsNullOrEmpty(str)) { jID[jsFullName] = null; return null; } string[] arr = str.Split(','); int[] r = new int[arr.Length]; for (int i = 0; i < arr.Length; i++) r[i] = int.Parse(arr[i]); jID[jsFullName] = r; return r; }"); } tfC.AddLine(); { tfC.AddMultiline(@" public static void CreateMessages(string jsFullName, GameObject go) { int[] ids = GetJsClassMessages(jsFullName); if (ids == null) return; // ID号 JS和CS保持一致才不会错 for (int i = 0; i < ids.Length; i++) { Type type = MessageTypes[ids[i]]; if (go.GetComponent(type) == null) go.AddComponent(type); } }"); } tfC.AddLine(); { TextFile tfM = tfC.Add("static Type[] MessageTypes = new Type[]").BraceIn(); { for (int i = 0; i < infos.Length; i++) { Info info = infos[i]; tfM.Add("typeof(jsb.{0}),", info.className); } } tfM.BraceOutSC(); } } tfC.BraceOut(); } tfNs.BraceOut(); string s = tf.Format(-1); File.WriteAllText(CsDir + "/" + className + ".cs", s); }
/// <summary> /// Get TextFile from disk, memory, or web /// </summary> private void GetFileReference() { if (m_filename.Contains("http") && !s_cache.ContainsKey(m_filename)) { Logger.WriteLine("Reading file from web: '" + m_filename + "'"); System.Net.WebClient client = new System.Net.WebClient(); Stream stream = client.OpenRead(m_filename); StreamReader reader = new StreamReader(stream); String content = reader.ReadToEnd(); string[] stringSeparators = new string[] { "\r\n" }; string[] lines = content.Split(stringSeparators, StringSplitOptions.None); m_textFile = new TextFile(); foreach (var line in lines) { if (line != "") { m_textFile.Add(line); } } int max_cache_size = 3; if (s_cache.Count >= max_cache_size) { s_cache.Clear(); Logger.WriteLine(" s_cache.Clear();"); } s_cache.Add(m_filename, m_textFile); } else if (!s_cache.ContainsKey(m_filename)) { Logger.WriteLine("reading file from disk: " + Path.GetFileName(m_filename)); if (!File.Exists(m_filename)) { Logger.WriteLine("File does not exist: '" + m_filename + "'"); } m_textFile = new TextFile(m_filename); int max_cache_size = 3; if (s_cache.Count >= max_cache_size) { s_cache.Clear(); Logger.WriteLine(" s_cache.Clear();"); } s_cache.Add(m_filename, m_textFile); } else { // already in memory. Logger.WriteLine("Found file in cache: " + Path.GetFileName(m_filename)); m_textFile = s_cache[m_filename]; if (!m_filename.Contains("http")) { FileInfo fi = new FileInfo(m_filename); if (fi.LastWriteTime > m_textFile.LastWriteTime) { Logger.WriteLine("File has changed... updating cache"); m_textFile = new TextFile(m_filename); s_cache[m_filename] = m_textFile; } } } }
static void handleMethods(TextFile tfClass, Type type, GeneratorHelp.ATypeInfo ti, Action <Type> OnNewType) { Action <MethodInfo> action = (method) => { StringBuilder sbDef = new StringBuilder(); bool isI = type.IsInterface; if (!isI) { if (method.IsPublic) { sbDef.Append("public "); } else if (method.IsFamily) { sbDef.Append("protected "); } else if (method.IsAssembly) { sbDef.Append("internal "); } if (method.IsStatic) { sbDef.Append("static "); } sbDef.Append("extern "); if (method.GetBaseDefinition() != method) { sbDef.Append("override "); } else if (!type.IsValueType && method.IsVirtual && !type.IsValueType) { sbDef.Append("virtual "); } } if (!(method.IsSpecialName && method.Name == "op_Implicit")) { sbDef.Append(typefn(method.ReturnType, type.Namespace, CsNameOption.CompilableWithT) + " "); } OnNewType(method.ReturnType); sbDef.Append(MethodNameString(type, method)); if (method.IsGenericMethodDefinition) { Type[] argus = method.GetGenericArguments(); args t_args = new args(); foreach (var a in argus) { t_args.Add(a.Name); } sbDef.Append(t_args.Format(args.ArgsFormat.GenericT)); } sbDef.Append("("); bool hasExtensionAttribute = (method.GetCustomAttributes(typeof(System.Runtime.CompilerServices.ExtensionAttribute), false).Length > 0); ParameterInfo[] ps = method.GetParameters(); { sbDef.Append(Ps2String(type, ps, hasExtensionAttribute)); sbDef.Append(");"); foreach (var p in ps) { OnNewType(p.ParameterType); } } tfClass.Add(sbDef.ToString()); }; bool hasSpecial = false; for (int i = 0; i < ti.Methods.Count; i++) { MemberInfoEx infoEx = ti.Methods[i]; MethodInfo method = infoEx.member as MethodInfo; if (method.IsSpecialName) { hasSpecial = true; action(method); } } if (hasSpecial) { tfClass.AddLine(); } for (int i = 0; i < ti.Methods.Count; i++) { MemberInfoEx infoEx = ti.Methods[i]; MethodInfo method = infoEx.member as MethodInfo; if (!method.IsSpecialName) { action(method); } } }